diff --git a/0001-two-sum/0001-two-sum.cpp b/0001-two-sum/0001-two-sum.cpp new file mode 100644 index 00000000..78b71a2f --- /dev/null +++ b/0001-two-sum/0001-two-sum.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + + int n = nums.size(); + + unordered_map mp; + + for(int i = 0; i < n; ++i) + { + if(mp.find(target - nums[i]) != mp.end()) + { + return {i, mp[target - nums[i]]}; + } + mp[nums[i]] = i; + } + + return {}; + + } +}; \ No newline at end of file diff --git a/0001-two-sum/NOTES.md b/0001-two-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0001-two-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0001-two-sum/README.md b/0001-two-sum/README.md new file mode 100644 index 00000000..140e3104 --- /dev/null +++ b/0001-two-sum/README.md @@ -0,0 +1,38 @@ +

1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+ +

You may assume that each input would have exactly one solution, and you may not use the same element twice.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [2,7,11,15], target = 9
+Output: [0,1]
+Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
+
+ +

Example 2:

+ +
Input: nums = [3,2,4], target = 6
+Output: [1,2]
+
+ +

Example 3:

+ +
Input: nums = [3,3], target = 6
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
  • Only one valid answer exists.
  • +
+ +

 

+Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?
\ No newline at end of file diff --git a/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.cpp b/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.cpp new file mode 100644 index 00000000..03a436d5 --- /dev/null +++ b/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int lengthOfLongestSubstring(string s) { + + int i = 0, j = 0, n = s.size(); + + unordered_map mp; + + int ans = 0; + + while( j < n) + { + ++mp[s[j]]; + + if(mp.size() == j - i + 1) + ans = max(ans, j - i + 1); + else if(mp.size() < j - i + 1) + { + --mp[s[i]]; + if(mp[s[i]] == 0) + mp.erase(s[i]); + ++i; + } + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0003-longest-substring-without-repeating-characters/README.md b/0003-longest-substring-without-repeating-characters/README.md new file mode 100644 index 00000000..857ec8b4 --- /dev/null +++ b/0003-longest-substring-without-repeating-characters/README.md @@ -0,0 +1,33 @@ +

3. Longest Substring Without Repeating Characters

Medium


Given a string s, find the length of the longest substring without repeating characters.

+ +

 

+

Example 1:

+ +
Input: s = "abcabcbb"
+Output: 3
+Explanation: The answer is "abc", with the length of 3.
+
+ +

Example 2:

+ +
Input: s = "bbbbb"
+Output: 1
+Explanation: The answer is "b", with the length of 1.
+
+ +

Example 3:

+ +
Input: s = "pwwkew"
+Output: 3
+Explanation: The answer is "wke", with the length of 3.
+Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 5 * 104
  • +
  • s consists of English letters, digits, symbols and spaces.
  • +
+
\ No newline at end of file diff --git a/0004-median-of-two-sorted-arrays/0004-median-of-two-sorted-arrays.cpp b/0004-median-of-two-sorted-arrays/0004-median-of-two-sorted-arrays.cpp new file mode 100644 index 00000000..caf6766a --- /dev/null +++ b/0004-median-of-two-sorted-arrays/0004-median-of-two-sorted-arrays.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + if(nums2.size() < nums1.size()) + return findMedianSortedArrays(nums2,nums1); + + int n1 = nums1.size(), n2 = nums2.size(); + int low = 0, high = nums1.size(); + + int l1,l2 , r1, r2; + + while(low <= high) + { + int cut1 = (low + high) / 2; + int cut2 = (n1 + n2 + 1)/2 - cut1; + + l1 = cut1 == 0 ? INT_MIN : nums1[cut1-1]; + l2 = cut2 == 0 ? INT_MIN : nums2[cut2-1]; + + r1 = cut1 == n1 ? INT_MAX : nums1[cut1]; + r2 = cut2 == n2 ? INT_MAX : nums2[cut2]; + + + if(l1 <= r2 and l2 <= r1) + { + if((n1 + n2)%2 == 0) + { + return (max(l1,l2) + min(r1,r2)) / 2.0; + } + else + return max(l1,l2); + } + else if(l1 > r2) + high = cut1 - 1; + else + low = cut1 + 1; + } + + return 0.0; + } +}; \ No newline at end of file diff --git a/0004-median-of-two-sorted-arrays/NOTES.md b/0004-median-of-two-sorted-arrays/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0004-median-of-two-sorted-arrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0004-median-of-two-sorted-arrays/README.md b/0004-median-of-two-sorted-arrays/README.md new file mode 100644 index 00000000..e547cad4 --- /dev/null +++ b/0004-median-of-two-sorted-arrays/README.md @@ -0,0 +1,31 @@ +

4. Median of Two Sorted Arrays

Hard


Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

+ +

The overall run time complexity should be O(log (m+n)).

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,3], nums2 = [2]
+Output: 2.00000
+Explanation: merged array = [1,2,3] and median is 2.
+
+ +

Example 2:

+ +
Input: nums1 = [1,2], nums2 = [3,4]
+Output: 2.50000
+Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m
  • +
  • nums2.length == n
  • +
  • 0 <= m <= 1000
  • +
  • 0 <= n <= 1000
  • +
  • 1 <= m + n <= 2000
  • +
  • -106 <= nums1[i], nums2[i] <= 106
  • +
+
\ No newline at end of file diff --git a/0005-longest-palindromic-substring/0005-longest-palindromic-substring.cpp b/0005-longest-palindromic-substring/0005-longest-palindromic-substring.cpp new file mode 100644 index 00000000..c47bc3c6 --- /dev/null +++ b/0005-longest-palindromic-substring/0005-longest-palindromic-substring.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + string longestPalindrome(string s) { + + int n = s.size(); + + int maxi = 0; + + string ans; + + function helper = [=](int start, int end){ + + while( start >= 0 and end < n) + { + if(s[start] == s[end]) + { + --start, ++end; + } + else + break; + } + + return s.substr(start+1, end-start-1); + + }; + + for(int i = 0; i < n; ++i) + { + string oddCase = helper(i,i); + + if(oddCase.length() > maxi) + { + maxi = oddCase.length(); + ans = oddCase; + } + + string evenCase = helper(i,i+1); + + if(evenCase.length() > maxi) + { + maxi = evenCase.length(); + ans = evenCase; + } + } + + + return ans; + + } +}; \ No newline at end of file diff --git a/0005-longest-palindromic-substring/NOTES.md b/0005-longest-palindromic-substring/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0005-longest-palindromic-substring/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0005-longest-palindromic-substring/README.md b/0005-longest-palindromic-substring/README.md new file mode 100644 index 00000000..ea3d6571 --- /dev/null +++ b/0005-longest-palindromic-substring/README.md @@ -0,0 +1,24 @@ +

5. Longest Palindromic Substring

Medium


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

+ +

 

+

Example 1:

+ +
Input: s = "babad"
+Output: "bab"
+Explanation: "aba" is also a valid answer.
+
+ +

Example 2:

+ +
Input: s = "cbbd"
+Output: "bb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consist of only digits and English letters.
  • +
+
\ No newline at end of file diff --git a/0006-zigzag-conversion/0006-zigzag-conversion.cpp b/0006-zigzag-conversion/0006-zigzag-conversion.cpp new file mode 100644 index 00000000..9f22a4ea --- /dev/null +++ b/0006-zigzag-conversion/0006-zigzag-conversion.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + string convert(string s, int numRows) { + + int n = s.size(); + + vector v(numRows); + string ans; + + if(numRows == 1) + return s; + + int k = 0; + bool ok = true; + for(int i = 0; i6. Zigzag Conversion

Medium


The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

+ +
P   A   H   N
+A P L S I I G
+Y   I   R
+
+ +

And then read line by line: "PAHNAPLSIIGYIR"

+ +

Write the code that will take a string and make this conversion given a number of rows:

+ +
string convert(string s, int numRows);
+
+ +

 

+

Example 1:

+ +
Input: s = "PAYPALISHIRING", numRows = 3
+Output: "PAHNAPLSIIGYIR"
+
+ +

Example 2:

+ +
Input: s = "PAYPALISHIRING", numRows = 4
+Output: "PINALSIGYAHRPI"
+Explanation:
+P     I    N
+A   L S  I G
+Y A   H R
+P     I
+
+ +

Example 3:

+ +
Input: s = "A", numRows = 1
+Output: "A"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • +
  • 1 <= numRows <= 1000
  • +
+
\ No newline at end of file diff --git a/0009-palindrome-number/0009-palindrome-number.cpp b/0009-palindrome-number/0009-palindrome-number.cpp new file mode 100644 index 00000000..0d8a867c --- /dev/null +++ b/0009-palindrome-number/0009-palindrome-number.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool isPalindrome(int x) { + + if(x < 0 or (x % 10 == 0 and x != 0)) + return false; + + int rev = 0; + + while(rev < x) + { + rev = (rev * 10) + (x%10); + x /= 10; + } + + return (rev == x or rev/10 == x); + } +}; \ No newline at end of file diff --git a/0009-palindrome-number/NOTES.md b/0009-palindrome-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0009-palindrome-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0009-palindrome-number/README.md b/0009-palindrome-number/README.md new file mode 100644 index 00000000..135519db --- /dev/null +++ b/0009-palindrome-number/README.md @@ -0,0 +1,33 @@ +

9. Palindrome Number

Easy


Given an integer x, return true if x is a palindrome, and false otherwise.

+ +

 

+

Example 1:

+ +
Input: x = 121
+Output: true
+Explanation: 121 reads as 121 from left to right and from right to left.
+
+ +

Example 2:

+ +
Input: x = -121
+Output: false
+Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
+
+ +

Example 3:

+ +
Input: x = 10
+Output: false
+Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= x <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without converting the integer to a string?
\ No newline at end of file diff --git a/0011-container-with-most-water/0011-container-with-most-water.cpp b/0011-container-with-most-water/0011-container-with-most-water.cpp new file mode 100644 index 00000000..d7ba1774 --- /dev/null +++ b/0011-container-with-most-water/0011-container-with-most-water.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int maxArea(vector& height) { + + int start = 0, end = height.size()-1; + + int ans = 0; + + while(start < end) + { + int width = end - start; + + int area = min(height[start], height[end]) * width; + + ans = max(ans, area); + + if(height[start] < height[end]) + ++start; + else if(height[end] < height[start]) + --end; + else + ++start, --end; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0011-container-with-most-water/NOTES.md b/0011-container-with-most-water/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0011-container-with-most-water/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0011-container-with-most-water/README.md b/0011-container-with-most-water/README.md new file mode 100644 index 00000000..8fcd7fcd --- /dev/null +++ b/0011-container-with-most-water/README.md @@ -0,0 +1,31 @@ +

11. Container With Most Water

Medium


You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

+ +

Find two lines that together with the x-axis form a container, such that the container contains the most water.

+ +

Return the maximum amount of water a container can store.

+ +

Notice that you may not slant the container.

+ +

 

+

Example 1:

+ +
Input: height = [1,8,6,2,5,4,8,3,7]
+Output: 49
+Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
+
+ +

Example 2:

+ +
Input: height = [1,1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 2 <= n <= 105
  • +
  • 0 <= height[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0012. Integer to Roman.cpp b/0012. Integer to Roman.cpp index b5361ead..062c4d79 100644 --- a/0012. Integer to Roman.cpp +++ b/0012. Integer to Roman.cpp @@ -6,7 +6,7 @@ class Solution { string ans = ""; while(num >= 1000) - {l + { ans += "M"; num = num - 1000; } @@ -78,4 +78,4 @@ class Solution { // cout<> threeSum(vector& nums) { + + int n = nums.size(); + + vector> ans; + + sort(nums.begin(), nums.end()); + + for(int i = 0; i < n; ++i) + { + int j = i+1, k = n-1; + + while(j < k) + { + int sum = nums[i] + nums[j] + nums[k]; + + if(sum == 0) + { + ans.push_back({nums[i],nums[j],nums[k]}); + ++j, --k; + } + else if(sum > 0) + { + --k; + } + else + { + ++j; + } + } + } + + sort(ans.begin(), ans.end()); + + ans.erase(unique(ans.begin(),ans.end()), ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/0015-3sum/NOTES.md b/0015-3sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0015-3sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0015-3sum/README.md b/0015-3sum/README.md new file mode 100644 index 00000000..6dd16400 --- /dev/null +++ b/0015-3sum/README.md @@ -0,0 +1,39 @@ +

15. 3Sum

Medium


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

+ +

Notice that the solution set must not contain duplicate triplets.

+ +

 

+

Example 1:

+ +
Input: nums = [-1,0,1,2,-1,-4]
+Output: [[-1,-1,2],[-1,0,1]]
+Explanation: 
+nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
+nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
+nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
+The distinct triplets are [-1,0,1] and [-1,-1,2].
+Notice that the order of the output and the order of the triplets does not matter.
+
+ +

Example 2:

+ +
Input: nums = [0,1,1]
+Output: []
+Explanation: The only possible triplet does not sum up to 0.
+
+ +

Example 3:

+ +
Input: nums = [0,0,0]
+Output: [[0,0,0]]
+Explanation: The only possible triplet sums up to 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 3000
  • +
  • -105 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0017-letter-combinations-of-a-phone-number/0017-letter-combinations-of-a-phone-number.cpp b/0017-letter-combinations-of-a-phone-number/0017-letter-combinations-of-a-phone-number.cpp new file mode 100644 index 00000000..c5e92c43 --- /dev/null +++ b/0017-letter-combinations-of-a-phone-number/0017-letter-combinations-of-a-phone-number.cpp @@ -0,0 +1,47 @@ +class Solution { + +private: + void helper(int idx ,string ds, string& digits, map>& mp, vector& ans) + { + if(idx == digits.size()) + { + if(!ds.empty()) + ans.push_back(ds); + return; + } + + + vector curr = mp[digits[idx]]; + + for(int j = 0; j < curr.size(); ++j) + { + ds.push_back(curr[j]); + helper(idx+1, ds, digits, mp, ans); + ds.pop_back(); + } + + + } + +public: + vector letterCombinations(string digits) { + + map> mp; + + mp['2'] = {'a','b','c'}; + mp['3'] = {'d','e','f'}; + mp['4'] = {'g','h','i'}; + mp['5'] = {'j','k','l'}; + mp['6'] = {'m','n','o'}; + mp['7'] = {'p','q','r','s'}; + mp['8'] = {'t','u','v'}; + mp['9'] = {'w','x','y','z'}; + + vector ans; + + helper(0, "",digits, mp, ans); + + return ans; + + } +}; \ No newline at end of file diff --git a/0017-letter-combinations-of-a-phone-number/NOTES.md b/0017-letter-combinations-of-a-phone-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0017-letter-combinations-of-a-phone-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0017-letter-combinations-of-a-phone-number/README.md b/0017-letter-combinations-of-a-phone-number/README.md new file mode 100644 index 00000000..81e0b1fb --- /dev/null +++ b/0017-letter-combinations-of-a-phone-number/README.md @@ -0,0 +1,31 @@ +

17. Letter Combinations of a Phone Number

Medium


Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

+ +

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

+ +

 

+

Example 1:

+ +
Input: digits = "23"
+Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
+
+ +

Example 2:

+ +
Input: digits = ""
+Output: []
+
+ +

Example 3:

+ +
Input: digits = "2"
+Output: ["a","b","c"]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= digits.length <= 4
  • +
  • digits[i] is a digit in the range ['2', '9'].
  • +
+
\ No newline at end of file diff --git a/0018-4sum/0018-4sum.cpp b/0018-4sum/0018-4sum.cpp new file mode 100644 index 00000000..67139e92 --- /dev/null +++ b/0018-4sum/0018-4sum.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + + const int mod = 1e9 + 7; + + vector> fourSum(vector& nums, int target) { + + int n = nums.size(); + + vector> ans; + + sort(nums.begin(), nums.end()); + + for(int i = 0; i < n; ++i) + { + for(int j = i+1; j < n; ++j) + { + int k = j+1, l = n-1; + + while(k < l) + { + long long sum = (((((nums[i] % mod) + nums[j])% mod + nums[k])%mod + nums[l])%mod)%mod; + + if(sum == target) + { + ans.push_back({nums[i], nums[j], nums[k], nums[l]}); + ++k, --l; + } + else if(sum > target) + { + --l; + } + else + { + ++k; + } + } + } + } + + sort(ans.begin(), ans.end()); + + ans.erase(unique(ans.begin(), ans.end()), ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/0018-4sum/NOTES.md b/0018-4sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0018-4sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0018-4sum/README.md b/0018-4sum/README.md new file mode 100644 index 00000000..31fd5edd --- /dev/null +++ b/0018-4sum/README.md @@ -0,0 +1,32 @@ +

18. 4Sum

Medium


Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

+ +
    +
  • 0 <= a, b, c, d < n
  • +
  • a, b, c, and d are distinct.
  • +
  • nums[a] + nums[b] + nums[c] + nums[d] == target
  • +
+ +

You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,0,-1,0,-2,2], target = 0
+Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2], target = 8
+Output: [[2,2,2,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.cpp b/0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.cpp new file mode 100644 index 00000000..7059bd67 --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + + ListNode* fast = head, *slow = head; + + while(n--) + fast = fast->next; + + if(!fast) + return head->next; + + while(fast->next) + { + fast = fast->next; + slow = slow->next; + } + + slow->next = slow->next->next; + + return head; + } +}; \ No newline at end of file diff --git a/0019-remove-nth-node-from-end-of-list/NOTES.md b/0019-remove-nth-node-from-end-of-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0019-remove-nth-node-from-end-of-list/README.md b/0019-remove-nth-node-from-end-of-list/README.md new file mode 100644 index 00000000..b1ecfb61 --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list/README.md @@ -0,0 +1,34 @@ +

19. Remove Nth Node From End of List

Medium


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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], n = 2
+Output: [1,2,3,5]
+
+ +

Example 2:

+ +
Input: head = [1], n = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1,2], n = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is sz.
  • +
  • 1 <= sz <= 30
  • +
  • 0 <= Node.val <= 100
  • +
  • 1 <= n <= sz
  • +
+ +

 

+

Follow up: Could you do this in one pass?

+
\ No newline at end of file diff --git a/0020-valid-parentheses/0020-valid-parentheses.cpp b/0020-valid-parentheses/0020-valid-parentheses.cpp new file mode 100644 index 00000000..71580a51 --- /dev/null +++ b/0020-valid-parentheses/0020-valid-parentheses.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool isValid(string s) { + + stack st; + + for(auto itr : s) + { + if(itr == '(' or itr == '{' or itr == '[') + st.push(itr); + else if(!st.empty()) + { + if(st.top() == '(' and itr != ')') + return false; + if(st.top() == '{' and itr != '}') + return false; + if(st.top() == '[' and itr != ']') + return false; + st.pop(); + } + else + return false; + } + + return st.empty(); + + } +}; \ No newline at end of file diff --git a/0020-valid-parentheses/NOTES.md b/0020-valid-parentheses/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0020-valid-parentheses/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0020-valid-parentheses/README.md b/0020-valid-parentheses/README.md new file mode 100644 index 00000000..5c5bf1e2 --- /dev/null +++ b/0020-valid-parentheses/README.md @@ -0,0 +1,37 @@ +

20. Valid Parentheses

Easy


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

+ +

An input string is valid if:

+ +
    +
  1. Open brackets must be closed by the same type of brackets.
  2. +
  3. Open brackets must be closed in the correct order.
  4. +
  5. Every close bracket has a corresponding open bracket of the same type.
  6. +
+ +

 

+

Example 1:

+ +
Input: s = "()"
+Output: true
+
+ +

Example 2:

+ +
Input: s = "()[]{}"
+Output: true
+
+ +

Example 3:

+ +
Input: s = "(]"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of parentheses only '()[]{}'.
  • +
+
\ No newline at end of file diff --git a/0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.cpp b/0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.cpp new file mode 100644 index 00000000..c1682516 --- /dev/null +++ b/0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.cpp @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + + if(!list1) + return list2; + if(!list2) + return list1; + + if(list1->val < list2->val) + { + list1->next = mergeTwoLists(list1->next,list2); + return list1; + } + else + { + list2 ->next = mergeTwoLists(list1,list2->next); + return list2; + } + + } +}; \ No newline at end of file diff --git a/0021-merge-two-sorted-lists/NOTES.md b/0021-merge-two-sorted-lists/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0021-merge-two-sorted-lists/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0021-merge-two-sorted-lists/README.md b/0021-merge-two-sorted-lists/README.md new file mode 100644 index 00000000..d9a9154d --- /dev/null +++ b/0021-merge-two-sorted-lists/README.md @@ -0,0 +1,34 @@ +

21. Merge Two Sorted Lists

Easy


You are given the heads of two sorted linked lists list1 and list2.

+ +

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

+ +

Return the head of the merged linked list.

+ +

 

+

Example 1:

+ +
Input: list1 = [1,2,4], list2 = [1,3,4]
+Output: [1,1,2,3,4,4]
+
+ +

Example 2:

+ +
Input: list1 = [], list2 = []
+Output: []
+
+ +

Example 3:

+ +
Input: list1 = [], list2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both lists is in the range [0, 50].
  • +
  • -100 <= Node.val <= 100
  • +
  • Both list1 and list2 are sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/0022-generate-parentheses/0022-generate-parentheses.cpp b/0022-generate-parentheses/0022-generate-parentheses.cpp new file mode 100644 index 00000000..3d3bd40c --- /dev/null +++ b/0022-generate-parentheses/0022-generate-parentheses.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + + void generate(int openBracket, int closeBracket, int n, string ds, vector& answer) + { + if(openBracket == n and closeBracket == n) + { + answer.push_back(ds); + return; + } + + if(openBracket < n) + generate(openBracket+1, closeBracket, n, ds + '(', answer); + if(closeBracket < openBracket) + generate(openBracket, closeBracket+1, n, ds + ')', answer); + } + + vector generateParenthesis(int n) { + + vector answer; + + generate(0, 0, n, "", answer); + + return answer; + } +}; \ No newline at end of file diff --git a/0022-generate-parentheses/README.md b/0022-generate-parentheses/README.md new file mode 100644 index 00000000..154f576c --- /dev/null +++ b/0022-generate-parentheses/README.md @@ -0,0 +1,17 @@ +

22. Generate Parentheses

Medium


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

+ +

 

+

Example 1:

+
Input: n = 3
+Output: ["((()))","(()())","(())()","()(())","()()()"]
+

Example 2:

+
Input: n = 1
+Output: ["()"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+
\ No newline at end of file diff --git a/0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.cpp b/0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.cpp new file mode 100644 index 00000000..a4abcfe9 --- /dev/null +++ b/0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.cpp @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + ListNode* merge(ListNode* l1, ListNode* l2) + { + if(!l1) + return l2; + if(!l2) + return l1; + + if(l1->val < l2->val) + { + l1->next = merge(l1->next,l2); + return l1; + } + else + { + l2->next = merge(l1,l2->next); + return l2; + } + } + + ListNode* mergeKLists(vector& lists) { + + if(!lists.size()) + return nullptr; + + ListNode* head = lists[0]; + + for(int i = 1; i23. Merge k Sorted Lists

Hard


You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

+ +

Merge all the linked-lists into one sorted linked-list and return it.

+ +

 

+

Example 1:

+ +
Input: lists = [[1,4,5],[1,3,4],[2,6]]
+Output: [1,1,2,3,4,4,5,6]
+Explanation: The linked-lists are:
+[
+  1->4->5,
+  1->3->4,
+  2->6
+]
+merging them into one sorted list:
+1->1->2->3->4->4->5->6
+
+ +

Example 2:

+ +
Input: lists = []
+Output: []
+
+ +

Example 3:

+ +
Input: lists = [[]]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • k == lists.length
  • +
  • 0 <= k <= 104
  • +
  • 0 <= lists[i].length <= 500
  • +
  • -104 <= lists[i][j] <= 104
  • +
  • lists[i] is sorted in ascending order.
  • +
  • The sum of lists[i].length will not exceed 104.
  • +
+
\ No newline at end of file diff --git a/0025-reverse-nodes-in-k-group/0025-reverse-nodes-in-k-group.cpp b/0025-reverse-nodes-in-k-group/0025-reverse-nodes-in-k-group.cpp new file mode 100644 index 00000000..403c05e4 --- /dev/null +++ b/0025-reverse-nodes-in-k-group/0025-reverse-nodes-in-k-group.cpp @@ -0,0 +1,50 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + + if(!head or k == 1) + return head; + + ListNode* dummy = new ListNode(0); + + dummy->next = head; + + ListNode* prev = dummy, *nex = dummy, *curr = dummy; + + int cnt = 0; + + while(head) + { + ++cnt; + head = head->next; + } + + while(cnt >= k) + { + curr = prev->next; + nex = curr->next; + + for(int i = 1; i < k; ++i) + { + curr->next = nex->next; + nex->next = prev->next; + prev->next = nex; + nex = curr->next; + } + prev = curr; + cnt -= k; + } + + return dummy->next; + } +}; \ No newline at end of file diff --git a/0025-reverse-nodes-in-k-group/NOTES.md b/0025-reverse-nodes-in-k-group/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0025-reverse-nodes-in-k-group/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0025-reverse-nodes-in-k-group/README.md b/0025-reverse-nodes-in-k-group/README.md new file mode 100644 index 00000000..2c7afeca --- /dev/null +++ b/0025-reverse-nodes-in-k-group/README.md @@ -0,0 +1,31 @@ +

25. Reverse Nodes in k-Group

Hard


Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

+ +

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

+ +

You may not alter the values in the list's nodes, only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [2,1,4,3,5]
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5], k = 3
+Output: [3,2,1,4,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= k <= n <= 5000
  • +
  • 0 <= Node.val <= 1000
  • +
+ +

 

+

Follow-up: Can you solve the problem in O(1) extra memory space?

+
\ No newline at end of file diff --git a/0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.cpp b/0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.cpp new file mode 100644 index 00000000..4187bcf0 --- /dev/null +++ b/0026-remove-duplicates-from-sorted-array/0026-remove-duplicates-from-sorted-array.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + + int n = nums.size(); + + int cnt = 0; + + for(int i = 1; i < n; ++i) + { + if(nums[i] == nums[i-1]) + { + ++cnt; + } + else + nums[i-cnt] = nums[i]; + } + + return n - cnt; + + } +}; \ No newline at end of file diff --git a/0026-remove-duplicates-from-sorted-array/NOTES.md b/0026-remove-duplicates-from-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0026-remove-duplicates-from-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0026-remove-duplicates-from-sorted-array/README.md b/0026-remove-duplicates-from-sorted-array/README.md new file mode 100644 index 00000000..ec027591 --- /dev/null +++ b/0026-remove-duplicates-from-sorted-array/README.md @@ -0,0 +1,52 @@ +

26. Remove Duplicates from Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

+ +

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

+ +
    +
  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • +
  • Return k.
  • +
+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output: 2, nums = [1,2,_]
+Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,1,2,2,3,3,4]
+Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • nums is sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/0028-find-the-index-of-the-first-occurrence-in-a-string/0028-find-the-index-of-the-first-occurrence-in-a-string.cpp b/0028-find-the-index-of-the-first-occurrence-in-a-string/0028-find-the-index-of-the-first-occurrence-in-a-string.cpp new file mode 100644 index 00000000..2c944c3b --- /dev/null +++ b/0028-find-the-index-of-the-first-occurrence-in-a-string/0028-find-the-index-of-the-first-occurrence-in-a-string.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int strStr(string haystack, string needle) { + + int n = needle.size(); + vector lps(n,0); + + for(int i = 1; i < n; ++i) + { + int j = lps[i-1] ; + + while(j > 0 and needle[i] != needle[j]) + j = lps[j-1]; + + if(needle[i] == needle[j]) + ++j; + + lps[i] = j; + } + + + int i = 0, j = 0, m = haystack.length(); + + while(i < m) + { + if(haystack[i] == needle[j]) + { + ++i,++j; + } + else if(haystack[i] != needle[j]){ + if(j == 0) + ++i; + else + j = lps[j-1]; + } + if(j == n) + return i - n; + } + + return -1; + } +}; \ No newline at end of file diff --git a/0028-find-the-index-of-the-first-occurrence-in-a-string/NOTES.md b/0028-find-the-index-of-the-first-occurrence-in-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0028-find-the-index-of-the-first-occurrence-in-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0028-find-the-index-of-the-first-occurrence-in-a-string/README.md b/0028-find-the-index-of-the-first-occurrence-in-a-string/README.md new file mode 100644 index 00000000..d5c5e6e4 --- /dev/null +++ b/0028-find-the-index-of-the-first-occurrence-in-a-string/README.md @@ -0,0 +1,26 @@ +

28. Find the Index of the First Occurrence in a String

Medium


Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

+ +

 

+

Example 1:

+ +
Input: haystack = "sadbutsad", needle = "sad"
+Output: 0
+Explanation: "sad" occurs at index 0 and 6.
+The first occurrence is at index 0, so we return 0.
+
+ +

Example 2:

+ +
Input: haystack = "leetcode", needle = "leeto"
+Output: -1
+Explanation: "leeto" did not occur in "leetcode", so we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= haystack.length, needle.length <= 104
  • +
  • haystack and needle consist of only lowercase English characters.
  • +
+
\ No newline at end of file diff --git a/0031-next-permutation/0031-next-permutation.cpp b/0031-next-permutation/0031-next-permutation.cpp new file mode 100644 index 00000000..3551b1e4 --- /dev/null +++ b/0031-next-permutation/0031-next-permutation.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + void nextPermutation(vector& nums) { + + int n = nums.size(); + + int idx = -1; + + for(int i = n-2; i >= 0; --i) + { + if(nums[i] < nums[i+1]) + { + idx = i; + break; + } + } + + if(idx == -1) + { + reverse(nums.begin(), nums.end()); + return; + } + + for(int i = n-1; i > idx; --i) + { + if(nums[i] > nums[idx]) + { + swap(nums[i], nums[idx]); + break; + } + } + + reverse(nums.begin() + idx + 1, nums.end()); + } +}; \ No newline at end of file diff --git a/0031-next-permutation/NOTES.md b/0031-next-permutation/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0031-next-permutation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0031-next-permutation/README.md b/0031-next-permutation/README.md new file mode 100644 index 00000000..5d498653 --- /dev/null +++ b/0031-next-permutation/README.md @@ -0,0 +1,45 @@ +

31. Next Permutation

Medium


A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

+ +
    +
  • For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
  • +
+ +

The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

+ +
    +
  • For example, the next permutation of arr = [1,2,3] is [1,3,2].
  • +
  • Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
  • +
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
  • +
+ +

Given an array of integers nums, find the next permutation of nums.

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
Input: nums = [3,2,1]
+Output: [1,2,3]
+
+ +

Example 3:

+ +
Input: nums = [1,1,5]
+Output: [1,5,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.cpp b/0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.cpp new file mode 100644 index 00000000..7e2679b4 --- /dev/null +++ b/0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int search(vector& nums, int target) { + + int low = 0 , high = nums.size()-1; + + while(low <= high) + { + int mid = (low + high) >> 1; + + if(nums[mid] == target) + return mid; + + if(nums[low] <= nums[mid]) + { + if(nums[low] <= target and target <= nums[mid]) + high = mid-1; + else + low = mid+1; + } + else + { + if(nums[mid] <= target and nums[high] >= target) + low = mid+1; + else + high = mid-1; + } + } + + return -1; + } +}; \ No newline at end of file diff --git a/0033-search-in-rotated-sorted-array/NOTES.md b/0033-search-in-rotated-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0033-search-in-rotated-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0033-search-in-rotated-sorted-array/README.md b/0033-search-in-rotated-sorted-array/README.md new file mode 100644 index 00000000..0e622ad1 --- /dev/null +++ b/0033-search-in-rotated-sorted-array/README.md @@ -0,0 +1,30 @@ +

33. Search in Rotated Sorted Array

Medium


There is an integer array nums sorted in ascending order (with distinct values).

+ +

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

+ +

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [4,5,6,7,0,1,2], target = 0
+Output: 4
+

Example 2:

+
Input: nums = [4,5,6,7,0,1,2], target = 3
+Output: -1
+

Example 3:

+
Input: nums = [1], target = 0
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • All values of nums are unique.
  • +
  • nums is an ascending array that is possibly rotated.
  • +
  • -104 <= target <= 104
  • +
+
\ No newline at end of file diff --git a/0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp b/0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp new file mode 100644 index 00000000..16bba9d0 --- /dev/null +++ b/0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp @@ -0,0 +1,72 @@ +class Solution { +public: + + int binarySearchFirst(vector& nums, int target) + { + int start = 0, end = nums.size()-1; + + int first = - 1; + + while(start <= end) + { + int mid = start + (end - start)/ 2; + + if(nums[mid] == target) + { + first = mid; + end = mid-1; + } + else if(nums[mid] < target) + { + start = mid+1; + } + else + { + end = mid - 1; + } + } + + return first; + } + + int binarySearchEnd(vector& nums, int target) + { + int start = 0, end = nums.size()-1; + + int last = -1; + + while(start <= end) + { + int mid = start + (end - start)/ 2; + + if(nums[mid] == target) + { + last = mid; + start = mid+1; + } + else if(nums[mid] > target) + { + end = mid-1; + } + else + { + start = mid+1; + } + } + + return last; + } + + vector searchRange(vector& nums, int target) { + + int n = nums.size(); + + int first = -1, last = -1; + + first = binarySearchFirst(nums, target); + last = binarySearchEnd(nums, target); + + return {first, last}; + + } +}; \ No newline at end of file diff --git a/0034-find-first-and-last-position-of-element-in-sorted-array/README.md b/0034-find-first-and-last-position-of-element-in-sorted-array/README.md new file mode 100644 index 00000000..3ba57ee9 --- /dev/null +++ b/0034-find-first-and-last-position-of-element-in-sorted-array/README.md @@ -0,0 +1,27 @@ +

34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

+ +

If target is not found in the array, return [-1, -1].

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [5,7,7,8,8,10], target = 8
+Output: [3,4]
+

Example 2:

+
Input: nums = [5,7,7,8,8,10], target = 6
+Output: [-1,-1]
+

Example 3:

+
Input: nums = [], target = 0
+Output: [-1,-1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • nums is a non-decreasing array.
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/0040-combination-sum-ii/0040-combination-sum-ii.cpp b/0040-combination-sum-ii/0040-combination-sum-ii.cpp new file mode 100644 index 00000000..0e49d197 --- /dev/null +++ b/0040-combination-sum-ii/0040-combination-sum-ii.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + void helper(int idx, int target, vector ds, vector>& res, vector& candidates) + { + if(target == 0) + { + res.push_back(ds); + return; + } + + for(int i = idx; i < candidates.size(); ++i) + { + if(i != idx and candidates[i] == candidates[i-1]) + continue; + if(target - candidates[i] < 0) + break; + ds.push_back(candidates[i]); + helper(i+1, target-candidates[i], ds, res, candidates); + ds.pop_back(); + } + + } + + vector> combinationSum2(vector& candidates, int target) { + + vector ds; + vector> res; + + sort(candidates.begin(), candidates.end()); + + helper(0, target, ds, res, candidates); + + return res; + + } +}; \ No newline at end of file diff --git a/0040-combination-sum-ii/README.md b/0040-combination-sum-ii/README.md new file mode 100644 index 00000000..41ac5070 --- /dev/null +++ b/0040-combination-sum-ii/README.md @@ -0,0 +1,38 @@ +

40. Combination Sum II

Medium


Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

+ +

Each number in candidates may only be used once in the combination.

+ +

Note: The solution set must not contain duplicate combinations.

+ +

 

+

Example 1:

+ +
Input: candidates = [10,1,2,7,6,1,5], target = 8
+Output: 
+[
+[1,1,6],
+[1,2,5],
+[1,7],
+[2,6]
+]
+
+ +

Example 2:

+ +
Input: candidates = [2,5,2,1,2], target = 5
+Output: 
+[
+[1,2,2],
+[5]
+]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 100
  • +
  • 1 <= candidates[i] <= 50
  • +
  • 1 <= target <= 30
  • +
+
\ No newline at end of file diff --git a/0041-first-missing-positive/0041-first-missing-positive.cpp b/0041-first-missing-positive/0041-first-missing-positive.cpp new file mode 100644 index 00000000..285acdfb --- /dev/null +++ b/0041-first-missing-positive/0041-first-missing-positive.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int firstMissingPositive(vector& nums) { + + int n = nums.size(); + + for(int i = 0; i < n; ++i) + { + if(nums[i] <= 0) + nums[i] = n+1; + } + + for(int i = 0; i < n; ++i) + { + if(abs(nums[i])-1 >= 0 and abs(nums[i])-1 < n) + { + if(nums[abs(nums[i])-1] >= 0) + nums[abs(nums[i])-1] = -nums[abs(nums[i])-1]; + } + } + + for(int i = 0; i < n; ++i) + { + if(nums[i] >= 0) + return i+1; + } + + return n+1; + } +}; \ No newline at end of file diff --git a/0041-first-missing-positive/README.md b/0041-first-missing-positive/README.md new file mode 100644 index 00000000..8c35883a --- /dev/null +++ b/0041-first-missing-positive/README.md @@ -0,0 +1,34 @@ +

41. First Missing Positive

Hard


Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,0]
+Output: 3
+Explanation: The numbers in the range [1,2] are all in the array.
+
+ +

Example 2:

+ +
Input: nums = [3,4,-1,1]
+Output: 2
+Explanation: 1 is in the array but 2 is missing.
+
+ +

Example 3:

+ +
Input: nums = [7,8,9,11,12]
+Output: 1
+Explanation: The smallest positive integer 1 is missing.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0042-trapping-rain-water/0042-trapping-rain-water.cpp b/0042-trapping-rain-water/0042-trapping-rain-water.cpp new file mode 100644 index 00000000..6ea2c60c --- /dev/null +++ b/0042-trapping-rain-water/0042-trapping-rain-water.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int trap(vector& height) { + + int n = height.size(); + + int i = 0, j = n-1, ans = 0; + + int leftMax = 0, rightMax = 0; + + while(i < j) + { + leftMax = max(leftMax, height[i]); + rightMax = max(rightMax, height[j]); + + ans += min(leftMax, rightMax) - min(height[i], height[j]); + + if(height[i] <= height[j]) + ++i; + else + --j; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0042-trapping-rain-water/NOTES.md b/0042-trapping-rain-water/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0042-trapping-rain-water/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0042-trapping-rain-water/README.md b/0042-trapping-rain-water/README.md new file mode 100644 index 00000000..9d727dd1 --- /dev/null +++ b/0042-trapping-rain-water/README.md @@ -0,0 +1,25 @@ +

42. Trapping Rain Water

Hard


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

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: height = [4,2,0,3,2,5]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 1 <= n <= 2 * 104
  • +
  • 0 <= height[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0044-wildcard-matching/0044-wildcard-matching.cpp b/0044-wildcard-matching/0044-wildcard-matching.cpp new file mode 100644 index 00000000..d746615d --- /dev/null +++ b/0044-wildcard-matching/0044-wildcard-matching.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + bool isMatch(string s, string p) { + + int n=p.size(); + int m=s.size(); + vector> dp(n+1,vector(m+1,false)); + dp[0][0]=true; + for(int j=1;j<=m;j++) dp[0][j]=false; + for(int i=1;i<=n;i++){ + bool flag=true; + for(int k=1;k<=i;k++){ + if(p[k-1]!='*'){ + flag=false; + break; + } + } + dp[i][0]=flag; + } + + for(int i=1;i<=n;i++){ + for(int j=1;j<=m;j++){ + if(p[i-1]==s[j-1] || p[i-1]=='?') dp[i][j]=dp[i-1][j-1]; + else if(p[i-1]=='*') dp[i][j]=dp[i-1][j] || dp[i][j-1]; + else dp[i][j]=false; + } + } + return dp[n][m]; + } +}; \ No newline at end of file diff --git a/0044-wildcard-matching/NOTES.md b/0044-wildcard-matching/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0044-wildcard-matching/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0044-wildcard-matching/README.md b/0044-wildcard-matching/README.md new file mode 100644 index 00000000..cc08b89c --- /dev/null +++ b/0044-wildcard-matching/README.md @@ -0,0 +1,40 @@ +

44. Wildcard Matching

Hard


Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

+ +
    +
  • '?' Matches any single character.
  • +
  • '*' Matches any sequence of characters (including the empty sequence).
  • +
+ +

The matching should cover the entire input string (not partial).

+ +

 

+

Example 1:

+ +
Input: s = "aa", p = "a"
+Output: false
+Explanation: "a" does not match the entire string "aa".
+
+ +

Example 2:

+ +
Input: s = "aa", p = "*"
+Output: true
+Explanation: '*' matches any sequence.
+
+ +

Example 3:

+ +
Input: s = "cb", p = "?a"
+Output: false
+Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length, p.length <= 2000
  • +
  • s contains only lowercase English letters.
  • +
  • p contains only lowercase English letters, '?' or '*'.
  • +
+
\ No newline at end of file diff --git a/0046-permutations/0046-permutations.cpp b/0046-permutations/0046-permutations.cpp new file mode 100644 index 00000000..2fd910bd --- /dev/null +++ b/0046-permutations/0046-permutations.cpp @@ -0,0 +1,30 @@ +class Solution { + +private: + void helper(int idx, vector& nums, vector>& ans) + { + if(idx == nums.size()) + { + ans.push_back(nums); + return; + } + + for(int i = idx; i < nums.size(); ++i) + { + swap(nums[idx], nums[i]); + helper(idx+1, nums, ans); + swap(nums[idx], nums[i]); + } + } + +public: + vector> permute(vector& nums) { + + vector> ans; + + helper(0, nums, ans); + + return ans; + + } +}; \ No newline at end of file diff --git a/0046-permutations/NOTES.md b/0046-permutations/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0046-permutations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0046-permutations/README.md b/0046-permutations/README.md new file mode 100644 index 00000000..25218c6e --- /dev/null +++ b/0046-permutations/README.md @@ -0,0 +1,22 @@ +

46. Permutations

Medium


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

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+

Example 2:

+
Input: nums = [0,1]
+Output: [[0,1],[1,0]]
+

Example 3:

+
Input: nums = [1]
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 6
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the integers of nums are unique.
  • +
+
\ No newline at end of file diff --git a/0048-rotate-image/0048-rotate-image.cpp b/0048-rotate-image/0048-rotate-image.cpp new file mode 100644 index 00000000..93b35e47 --- /dev/null +++ b/0048-rotate-image/0048-rotate-image.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + void rotate(vector>& matrix) { + + + int n = matrix.size(); + int m = matrix[0].size(); + + for(int i = 0; i48. Rotate Image

Medium


You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

+ +

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

+ +

 

+

Example 1:

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

Example 2:

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

 

+

Constraints:

+ +
    +
  • n == matrix.length == matrix[i].length
  • +
  • 1 <= n <= 20
  • +
  • -1000 <= matrix[i][j] <= 1000
  • +
+
\ No newline at end of file diff --git a/0049-group-anagrams/0049-group-anagrams.cpp b/0049-group-anagrams/0049-group-anagrams.cpp new file mode 100644 index 00000000..aceab9f2 --- /dev/null +++ b/0049-group-anagrams/0049-group-anagrams.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + + vector > vp; + int n = strs.size(); + vector > ans; + + for(int i = 0; i < n; ++i) + { + string s = strs[i]; + sort(s.begin(),s.end()); + vp.push_back(make_pair(s,i)); + } + + sort(vp.begin(),vp.end()); + + vector v; + + for(int i = 0; i < vp.size(); ++i) + { + if(v.empty() or vp[i-1].first == vp[i].first) + { + v.push_back(strs[vp[i].second]); + } + else + { + ans.push_back(v); + v.clear(); + v.push_back(strs[vp[i].second]); + } + } + + if(!v.empty()) + ans.push_back(v); + + + return ans; + } +}; \ No newline at end of file diff --git a/0049-group-anagrams/NOTES.md b/0049-group-anagrams/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0049-group-anagrams/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0049-group-anagrams/README.md b/0049-group-anagrams/README.md new file mode 100644 index 00000000..3da623eb --- /dev/null +++ b/0049-group-anagrams/README.md @@ -0,0 +1,24 @@ +

49. Group Anagrams

Medium


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

+ +

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

+ +

 

+

Example 1:

+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
+Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
+

Example 2:

+
Input: strs = [""]
+Output: [[""]]
+

Example 3:

+
Input: strs = ["a"]
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 104
  • +
  • 0 <= strs[i].length <= 100
  • +
  • strs[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0050-powx-n/0050-powx-n.cpp b/0050-powx-n/0050-powx-n.cpp new file mode 100644 index 00000000..9c155c85 --- /dev/null +++ b/0050-powx-n/0050-powx-n.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + double myPow(double x, int n) { + + double res = 1.0; + + long long num = n; + + if(num < 0) + { + num *= -1; + } + + while(num > 0) + { + if(num & 1) + res = res * x; + + x = (x * x); + + num >>= 1; + + } + + if(n < 0) + { + res = (double)1.0/(double)res; + } + + return res; + + } +}; \ No newline at end of file diff --git a/0050-powx-n/NOTES.md b/0050-powx-n/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0050-powx-n/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0050-powx-n/README.md b/0050-powx-n/README.md new file mode 100644 index 00000000..7c41e658 --- /dev/null +++ b/0050-powx-n/README.md @@ -0,0 +1,32 @@ +

50. Pow(x, n)

Medium


Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

+ +

 

+

Example 1:

+ +
Input: x = 2.00000, n = 10
+Output: 1024.00000
+
+ +

Example 2:

+ +
Input: x = 2.10000, n = 3
+Output: 9.26100
+
+ +

Example 3:

+ +
Input: x = 2.00000, n = -2
+Output: 0.25000
+Explanation: 2-2 = 1/22 = 1/4 = 0.25
+
+ +

 

+

Constraints:

+ +
    +
  • -100.0 < x < 100.0
  • +
  • -231 <= n <= 231-1
  • +
  • n is an integer.
  • +
  • -104 <= xn <= 104
  • +
+
\ No newline at end of file diff --git a/0053-maximum-subarray/NOTES.md b/0053-maximum-subarray/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0053-maximum-subarray/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0053-maximum-subarray/README.md b/0053-maximum-subarray/README.md new file mode 100644 index 00000000..8c856c7c --- /dev/null +++ b/0053-maximum-subarray/README.md @@ -0,0 +1,35 @@ +

53. Maximum Subarray

Medium


Given an integer array nums, find the subarray with the largest sum, and return its sum.

+ +

 

+

Example 1:

+ +
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
+Output: 6
+Explanation: The subarray [4,-1,2,1] has the largest sum 6.
+
+ +

Example 2:

+ +
Input: nums = [1]
+Output: 1
+Explanation: The subarray [1] has the largest sum 1.
+
+ +

Example 3:

+ +
Input: nums = [5,4,-1,7,8]
+Output: 23
+Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

+
\ No newline at end of file diff --git a/0054-spiral-matrix/0054-spiral-matrix.cpp b/0054-spiral-matrix/0054-spiral-matrix.cpp new file mode 100644 index 00000000..3397eda9 --- /dev/null +++ b/0054-spiral-matrix/0054-spiral-matrix.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + vector spiralOrder(vector>& matrix) { + + int n = matrix.size(); + int m = matrix[0].size(); + + int top = 0, left = 0, right = m-1, bottom = n-1, dir = 0; + vector ans; + + while(top <= bottom and left <= right) + { + if(dir == 0) + { + for(int i = left; i <= right; ++i) + ans.push_back(matrix[top][i]); + ++top; + } + + else if (dir == 1) + { + for(int i = top; i <= bottom; ++i) + ans.push_back(matrix[i][right]); + --right; + } + + else if(dir == 2) + { + for(int i = right; i >= left; --i) + ans.push_back(matrix[bottom][i]); + --bottom; + } + + else if(dir == 3) + { + for(int i = bottom; i >= top; --i) + ans.push_back(matrix[i][left]); + ++left; + } + + dir = (dir + 1) % 4; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0054-spiral-matrix/NOTES.md b/0054-spiral-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0054-spiral-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0054-spiral-matrix/README.md b/0054-spiral-matrix/README.md new file mode 100644 index 00000000..afec7a07 --- /dev/null +++ b/0054-spiral-matrix/README.md @@ -0,0 +1,25 @@ +

54. Spiral Matrix

Medium


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

+ +

 

+

Example 1:

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

Example 2:

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

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/0055-jump-game/0055-jump-game.cpp b/0055-jump-game/0055-jump-game.cpp new file mode 100644 index 00000000..38d10fa1 --- /dev/null +++ b/0055-jump-game/0055-jump-game.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool canJump(vector& nums) { + + int n = nums.size(); + int reachable = 0; + + for(int i =0 ; i& nums) { +int n = nums.size(); +int index = n-1; +for(int i = n-1 ; i >= 0; --i) +{ +if(nums[i] + i >= index) +index = i; +} +return (index == 0) ? 1 : 0; +} +}; \ No newline at end of file diff --git a/0055-jump-game/README.md b/0055-jump-game/README.md new file mode 100644 index 00000000..bfb8968a --- /dev/null +++ b/0055-jump-game/README.md @@ -0,0 +1,27 @@ +

55. Jump Game

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,1,1,4]
+Output: true
+Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0056-merge-intervals/0056-merge-intervals.cpp b/0056-merge-intervals/0056-merge-intervals.cpp new file mode 100644 index 00000000..b4b25962 --- /dev/null +++ b/0056-merge-intervals/0056-merge-intervals.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> merge(vector>& intervals) { + + vector> ans; + + sort(intervals.begin(),intervals.end()); + + for(auto itr : intervals) + { + if(ans.empty() or ans.back()[1] < itr[0]) + ans.push_back({itr[0],itr[1]}); + else + { + ans.back()[1] = max(ans.back()[1],itr[1]); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0056-merge-intervals/README.md b/0056-merge-intervals/README.md new file mode 100644 index 00000000..78870292 --- /dev/null +++ b/0056-merge-intervals/README.md @@ -0,0 +1,26 @@ +

56. Merge Intervals

Medium


Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

+ +

 

+

Example 1:

+ +
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
+Output: [[1,6],[8,10],[15,18]]
+Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
+
+ +

Example 2:

+ +
Input: intervals = [[1,4],[4,5]]
+Output: [[1,5]]
+Explanation: Intervals [1,4] and [4,5] are considered overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti <= endi <= 104
  • +
+
\ No newline at end of file diff --git a/0057-insert-interval/0057-insert-interval.cpp b/0057-insert-interval/0057-insert-interval.cpp new file mode 100644 index 00000000..ea38198c --- /dev/null +++ b/0057-insert-interval/0057-insert-interval.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + + vector>ans; + for(auto itr:intervals) + { + if(itr[1]57. Insert Interval

Medium


You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

+ +

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

+ +

Return intervals after the insertion.

+ +

 

+

Example 1:

+ +
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
+Output: [[1,5],[6,9]]
+
+ +

Example 2:

+ +
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
+Output: [[1,2],[3,10],[12,16]]
+Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti <= endi <= 105
  • +
  • intervals is sorted by starti in ascending order.
  • +
  • newInterval.length == 2
  • +
  • 0 <= start <= end <= 105
  • +
+
\ No newline at end of file diff --git a/0058-length-of-last-word/0058-length-of-last-word.cpp b/0058-length-of-last-word/0058-length-of-last-word.cpp new file mode 100644 index 00000000..16428111 --- /dev/null +++ b/0058-length-of-last-word/0058-length-of-last-word.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int lengthOfLastWord(string s) { + + int i = s.size()-1; + int len = 0; + + while(i >= 0 and s[i] == ' ') + --i; + + while(i >= 0 and s[i] != ' ') + ++len, --i; + + return len; + + } +}; \ No newline at end of file diff --git a/0058-length-of-last-word/NOTES.md b/0058-length-of-last-word/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0058-length-of-last-word/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0058-length-of-last-word/README.md b/0058-length-of-last-word/README.md new file mode 100644 index 00000000..f5d2873a --- /dev/null +++ b/0058-length-of-last-word/README.md @@ -0,0 +1,35 @@ +

58. Length of Last Word

Easy


Given a string s consisting of words and spaces, return the length of the last word in the string.

+ +

A word is a maximal substring consisting of non-space characters only.

+ +

 

+

Example 1:

+ +
Input: s = "Hello World"
+Output: 5
+Explanation: The last word is "World" with length 5.
+
+ +

Example 2:

+ +
Input: s = "   fly me   to   the moon  "
+Output: 4
+Explanation: The last word is "moon" with length 4.
+
+ +

Example 3:

+ +
Input: s = "luffy is still joyboy"
+Output: 6
+Explanation: The last word is "joyboy" with length 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of only English letters and spaces ' '.
  • +
  • There will be at least one word in s.
  • +
+
\ No newline at end of file diff --git a/0062-unique-paths/0062-unique-paths.cpp b/0062-unique-paths/0062-unique-paths.cpp new file mode 100644 index 00000000..5c69fb45 --- /dev/null +++ b/0062-unique-paths/0062-unique-paths.cpp @@ -0,0 +1,29 @@ +class Solution { + +private: + int helper(int i, int j, int n, int m, vector>& dp) + { + if(i == n-1 and j == m-1) + return 1; + + if(dp[i][j] != -1) + return dp[i][j]; + + int down = 0, right = 0; + + if(i+1 < n) + down = helper(i+1, j, n, m, dp); + if(j+1 < m) + right = helper(i, j+1, n, m, dp); + + return dp[i][j] = down + right; + } +public: + int uniquePaths(int m, int n) { + + vector > dp(m+1, vector(n+1, -1)); + + return helper(0, 0, m , n, dp); + + } +}; \ No newline at end of file diff --git a/0062-unique-paths/NOTES.md b/0062-unique-paths/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0062-unique-paths/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0062-unique-paths/README.md b/0062-unique-paths/README.md new file mode 100644 index 00000000..69eab055 --- /dev/null +++ b/0062-unique-paths/README.md @@ -0,0 +1,30 @@ +

62. Unique Paths

Medium


There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

+ +

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

+ +

The test cases are generated so that the answer will be less than or equal to 2 * 109.

+ +

 

+

Example 1:

+ +
Input: m = 3, n = 7
+Output: 28
+
+ +

Example 2:

+ +
Input: m = 3, n = 2
+Output: 3
+Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
+1. Right -> Down -> Down
+2. Down -> Down -> Right
+3. Down -> Right -> Down
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 100
  • +
+
\ No newline at end of file diff --git a/0063-unique-paths-ii/0063-unique-paths-ii.cpp b/0063-unique-paths-ii/0063-unique-paths-ii.cpp new file mode 100644 index 00000000..fc8ce20b --- /dev/null +++ b/0063-unique-paths-ii/0063-unique-paths-ii.cpp @@ -0,0 +1,34 @@ +class Solution { + +private: + int helper(int i, int j, int n, int m, vector>& obstacleGrid, vector>& dp) + { + if(i == n-1 and j == m-1) + { + return obstacleGrid[i][j] == 0; + } + + if(i > n or j > m or i < n and j < m and obstacleGrid[i][j] == 1) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + int right = helper(i, j+1, n, m, obstacleGrid, dp); + + int bottom = helper(i+1, j, n, m, obstacleGrid, dp); + + return dp[i][j] = right + bottom; + } + +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + + int n = obstacleGrid.size(), m = obstacleGrid[0].size(); + + vector> dp(n+1, vector(m+1, -1)); + + return helper(0,0, n, m, obstacleGrid, dp); + + } +}; \ No newline at end of file diff --git a/0063-unique-paths-ii/NOTES.md b/0063-unique-paths-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0063-unique-paths-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0067-add-binary/0067-add-binary.cpp b/0067-add-binary/0067-add-binary.cpp new file mode 100644 index 00000000..e3aa2944 --- /dev/null +++ b/0067-add-binary/0067-add-binary.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + string addBinary(string a, string b) { + + int i = a.size()-1, j = b.size()-1; + + int carry = 0; + string ans; + while(i >= 0 or j >= 0) + { + int sum = carry; + if(i >= 0) + sum += a[i--] - '0'; + if(j >= 0) + sum += b[j--] - '0'; + + carry = (sum > 1) ? 1 : 0; + ans += to_string(sum%2); + } + + if(carry) + ans += to_string(carry); + reverse(ans.begin(),ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/0067-add-binary/NOTES.md b/0067-add-binary/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0067-add-binary/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0067-add-binary/README.md b/0067-add-binary/README.md new file mode 100644 index 00000000..ee3f0c76 --- /dev/null +++ b/0067-add-binary/README.md @@ -0,0 +1,19 @@ +

67. Add Binary

Easy


Given two binary strings a and b, return their sum as a binary string.

+ +

 

+

Example 1:

+
Input: a = "11", b = "1"
+Output: "100"
+

Example 2:

+
Input: a = "1010", b = "1011"
+Output: "10101"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= a.length, b.length <= 104
  • +
  • a and b consist only of '0' or '1' characters.
  • +
  • Each string does not contain leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/0068-text-justification/0068-text-justification.cpp b/0068-text-justification/0068-text-justification.cpp new file mode 100644 index 00000000..18a0c746 --- /dev/null +++ b/0068-text-justification/0068-text-justification.cpp @@ -0,0 +1,83 @@ +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) { + + int n = words.size(); + + vector ans; + + string curr = ""; + + for(int i = 0; i < n; ++i) + { + int j = i+1; + int currCnt = words[i].size(), wordCount = 1; + while(j < n and currCnt + words[j].size() < maxWidth) + { + currCnt += words[j].size(); + + // cout< 1 ? (remSpaces/ (wordCount-1)) : (remSpaces / wordCount)); + + int extra = (wordCount > 1 ? (remSpaces% (wordCount-1)) : (remSpaces % wordCount)); + + // cout< 0) + { + string need(remSpaces, ' '); + curr += need; + } + + + // cout< maxWidth) + // curr.pop_back(); + + ans.push_back(curr); + + curr.clear(); + + i = j-1; + } + return ans; + } +}; \ No newline at end of file diff --git a/0068-text-justification/README.md b/0068-text-justification/README.md new file mode 100644 index 00000000..d04967ee --- /dev/null +++ b/0068-text-justification/README.md @@ -0,0 +1,63 @@ +

68. Text Justification

Hard


Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

+ +

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

+ +

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

+ +

For the last line of text, it should be left-justified, and no extra space is inserted between words.

+ +

Note:

+ +
    +
  • A word is defined as a character sequence consisting of non-space characters only.
  • +
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • +
  • The input array words contains at least one word.
  • +
+ +

 

+

Example 1:

+ +
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
+Output:
+[
+   "This    is    an",
+   "example  of text",
+   "justification.  "
+]
+ +

Example 2:

+ +
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
+Output:
+[
+  "What   must   be",
+  "acknowledgment  ",
+  "shall be        "
+]
+Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
+Note that the second line is also left-justified because it contains only one word.
+ +

Example 3:

+ +
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
+Output:
+[
+  "Science  is  what we",
+  "understand      well",
+  "enough to explain to",
+  "a  computer.  Art is",
+  "everything  else  we",
+  "do                  "
+]
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 300
  • +
  • 1 <= words[i].length <= 20
  • +
  • words[i] consists of only English letters and symbols.
  • +
  • 1 <= maxWidth <= 100
  • +
  • words[i].length <= maxWidth
  • +
+
\ No newline at end of file diff --git a/0069-sqrtx/0069-sqrtx.cpp b/0069-sqrtx/0069-sqrtx.cpp new file mode 100644 index 00000000..e22f88c4 --- /dev/null +++ b/0069-sqrtx/0069-sqrtx.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int mySqrt(int x) { + + long long start = 1, end = x; + + int ans = 0; + + while(start <= end) + { + long long mid = (start + end) >> 1; + + long long val = mid * 1LL * mid; + + if(val <= x) + { + ans = mid; + start = mid+1; + } + else + { + end = mid-1; + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0069-sqrtx/NOTES.md b/0069-sqrtx/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0069-sqrtx/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0069-sqrtx/README.md b/0069-sqrtx/README.md new file mode 100644 index 00000000..3b33c2e0 --- /dev/null +++ b/0069-sqrtx/README.md @@ -0,0 +1,30 @@ +

69. Sqrt(x)

Easy


Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

+ +

You must not use any built-in exponent function or operator.

+ +
    +
  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
  • +
+ +

 

+

Example 1:

+ +
Input: x = 4
+Output: 2
+Explanation: The square root of 4 is 2, so we return 2.
+
+ +

Example 2:

+ +
Input: x = 8
+Output: 2
+Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= x <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0070-climbing-stairs/0070-climbing-stairs.cpp b/0070-climbing-stairs/0070-climbing-stairs.cpp new file mode 100644 index 00000000..fbaea400 --- /dev/null +++ b/0070-climbing-stairs/0070-climbing-stairs.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int climbStairs(int n) { + + if(n == 1) + return 1; + + int prev2 = 1, prev = 1, res = 1; + + for(int i = 2; i <= n; ++i) + { + res = prev2 + prev; + prev = prev2; + prev2 = res; + } + + return res; + } +}; \ No newline at end of file diff --git a/0070-climbing-stairs/README.md b/0070-climbing-stairs/README.md new file mode 100644 index 00000000..c864654b --- /dev/null +++ b/0070-climbing-stairs/README.md @@ -0,0 +1,31 @@ +

70. Climbing Stairs

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 2
+Explanation: There are two ways to climb to the top.
+1. 1 step + 1 step
+2. 2 steps
+
+ +

Example 2:

+ +
Input: n = 3
+Output: 3
+Explanation: There are three ways to climb to the top.
+1. 1 step + 1 step + 1 step
+2. 1 step + 2 steps
+3. 2 steps + 1 step
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 45
  • +
+
\ No newline at end of file diff --git a/0071-simplify-path/0071-simplify-path.cpp b/0071-simplify-path/0071-simplify-path.cpp new file mode 100644 index 00000000..4c357b5b --- /dev/null +++ b/0071-simplify-path/0071-simplify-path.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + string simplifyPath(string path) { + + stack st; + string res; + + for(int i = 0; i71. Simplify Path

Medium


Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

+ +

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

+ +

The canonical path should have the following format:

+ +
    +
  • The path starts with a single slash '/'.
  • +
  • Any two directories are separated by a single slash '/'.
  • +
  • The path does not end with a trailing '/'.
  • +
  • The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
  • +
+ +

Return the simplified canonical path.

+ +

 

+

Example 1:

+ +
Input: path = "/home/"
+Output: "/home"
+Explanation: Note that there is no trailing slash after the last directory name.
+
+ +

Example 2:

+ +
Input: path = "/../"
+Output: "/"
+Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
+
+ +

Example 3:

+ +
Input: path = "/home//foo/"
+Output: "/home/foo"
+Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= path.length <= 3000
  • +
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • +
  • path is a valid absolute Unix path.
  • +
+
\ No newline at end of file diff --git a/0072-edit-distance/0072-edit-distance.cpp b/0072-edit-distance/0072-edit-distance.cpp new file mode 100644 index 00000000..acbdf7db --- /dev/null +++ b/0072-edit-distance/0072-edit-distance.cpp @@ -0,0 +1,35 @@ +#define ll long long +class Solution { +public: + + long long helper(int i, int j,int n, int m, string& word1, string& word2, vector>& dp ) + { + if(j >= m) + return n - i; + if(i >= n) + return m - j; + if(i >= n or j >= m) + return INT_MAX; + + if(dp[i][j] != -1) + return dp[i][j]; + + if(word1[i] == word2[j]) + return dp[i][j] = 0 + helper(i+1, j+1, n, m, word1, word2, dp); + else + { + ll ins = 1 + helper(i,j+1,n,m, word1, word2, dp); + ll del = 1 + helper(i+1, j,n,m, word1, word2, dp); + ll rep = 1 + helper(i+1, j+1,n,m, word1, word2, dp); + + return dp[i][j] = min({ins, del, rep}); + } + } + + int minDistance(string word1, string word2) { + + int n = word1.size(), m = word2.size(); + vector> dp(n+1,vector(m+1,-1)); + return helper(0,0,n,m,word1,word2,dp); + } +}; \ No newline at end of file diff --git a/0072-edit-distance/NOTES.md b/0072-edit-distance/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0072-edit-distance/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0072-edit-distance/README.md b/0072-edit-distance/README.md new file mode 100644 index 00000000..1959a449 --- /dev/null +++ b/0072-edit-distance/README.md @@ -0,0 +1,41 @@ +

72. Edit Distance

Hard


Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

+ +

You have the following three operations permitted on a word:

+ +
    +
  • Insert a character
  • +
  • Delete a character
  • +
  • Replace a character
  • +
+ +

 

+

Example 1:

+ +
Input: word1 = "horse", word2 = "ros"
+Output: 3
+Explanation: 
+horse -> rorse (replace 'h' with 'r')
+rorse -> rose (remove 'r')
+rose -> ros (remove 'e')
+
+ +

Example 2:

+ +
Input: word1 = "intention", word2 = "execution"
+Output: 5
+Explanation: 
+intention -> inention (remove 't')
+inention -> enention (replace 'i' with 'e')
+enention -> exention (replace 'n' with 'x')
+exention -> exection (replace 'n' with 'c')
+exection -> execution (insert 'u')
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= word1.length, word2.length <= 500
  • +
  • word1 and word2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0073-set-matrix-zeroes/0073-set-matrix-zeroes.cpp b/0073-set-matrix-zeroes/0073-set-matrix-zeroes.cpp new file mode 100644 index 00000000..37244de9 --- /dev/null +++ b/0073-set-matrix-zeroes/0073-set-matrix-zeroes.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + void setZeroes(vector>& matrix) { + + int n = matrix.size(), m = matrix[0].size(); + + vector row(n,0), col(m,0); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(matrix[i][j] == 0) + { + row[i] = col[j] = 1; + } + } + } + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(row[i] or col[j]) + matrix[i][j] = 0; + } + } + + } +}; \ No newline at end of file diff --git a/0073-set-matrix-zeroes/NOTES.md b/0073-set-matrix-zeroes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0073-set-matrix-zeroes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0073-set-matrix-zeroes/README.md b/0073-set-matrix-zeroes/README.md new file mode 100644 index 00000000..574d6249 --- /dev/null +++ b/0073-set-matrix-zeroes/README.md @@ -0,0 +1,36 @@ +

73. Set Matrix Zeroes

Medium


Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

+ +

You must do it in place.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
+Output: [[1,0,1],[0,0,0],[1,0,1]]
+
+ +

Example 2:

+ +
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
+Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[0].length
  • +
  • 1 <= m, n <= 200
  • +
  • -231 <= matrix[i][j] <= 231 - 1
  • +
+ +

 

+

Follow up:

+ +
    +
  • A straightforward solution using O(mn) space is probably a bad idea.
  • +
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • +
  • Could you devise a constant space solution?
  • +
+
\ No newline at end of file diff --git a/0074-search-a-2d-matrix/0074-search-a-2d-matrix.cpp b/0074-search-a-2d-matrix/0074-search-a-2d-matrix.cpp new file mode 100644 index 00000000..f82a7a0a --- /dev/null +++ b/0074-search-a-2d-matrix/0074-search-a-2d-matrix.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + int n = matrix.size(), m = matrix[0].size(); + + int start = 0 , end = (n*m)-1; + + while(start <= end) + { + int mid = (start + end) >> 1; + + int val = matrix[mid/m][mid%m]; + + if(val == target) + return true; + else if(val < target) + start = mid + 1; + else + end = mid - 1; + } + + return false; + } +}; \ No newline at end of file diff --git a/0074-search-a-2d-matrix/NOTES.md b/0074-search-a-2d-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0074-search-a-2d-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0074-search-a-2d-matrix/README.md b/0074-search-a-2d-matrix/README.md new file mode 100644 index 00000000..17687093 --- /dev/null +++ b/0074-search-a-2d-matrix/README.md @@ -0,0 +1,34 @@ +

74. Search a 2D Matrix

Medium


You are given an m x n integer matrix matrix with the following two properties:

+ +
    +
  • Each row is sorted in non-decreasing order.
  • +
  • The first integer of each row is greater than the last integer of the previous row.
  • +
+ +

Given an integer target, return true if target is in matrix or false otherwise.

+ +

You must write a solution in O(log(m * n)) time complexity.

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
+Output: true
+
+ +

Example 2:

+ +
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -104 <= matrix[i][j], target <= 104
  • +
+
\ No newline at end of file diff --git a/0075-sort-colors/0075-sort-colors.cpp b/0075-sort-colors/0075-sort-colors.cpp new file mode 100644 index 00000000..96ed566c --- /dev/null +++ b/0075-sort-colors/0075-sort-colors.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + void sortColors(vector& nums) { + + int start = 0, end = nums.size()-1; + + int zero = 0; + + while(start <= end) + { + if(nums[start] == 2) + { + swap(nums[start], nums[end]); + --end; + } + else if(nums[start] == 0) + { + swap(nums[zero++], nums[start++]); + } + else + ++start; + } + } +}; \ No newline at end of file diff --git a/0075-sort-colors/NOTES.md b/0075-sort-colors/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0075-sort-colors/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0075-sort-colors/README.md b/0075-sort-colors/README.md new file mode 100644 index 00000000..19eb0c70 --- /dev/null +++ b/0075-sort-colors/README.md @@ -0,0 +1,31 @@ +

75. Sort Colors

Medium


Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

+ +

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

+ +

You must solve this problem without using the library's sort function.

+ +

 

+

Example 1:

+ +
Input: nums = [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+
+ +

Example 2:

+ +
Input: nums = [2,0,1]
+Output: [0,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • nums[i] is either 0, 1, or 2.
  • +
+ +

 

+

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

+
\ No newline at end of file diff --git a/0076-minimum-window-substring/0076-minimum-window-substring.cpp b/0076-minimum-window-substring/0076-minimum-window-substring.cpp new file mode 100644 index 00000000..c0755a6f --- /dev/null +++ b/0076-minimum-window-substring/0076-minimum-window-substring.cpp @@ -0,0 +1,71 @@ +class Solution { +public: + string minWindow(string s, string t) { + + int n = s.size(); + + map freq, curr; + + for(auto& ele : t) + { + ++freq[ele]; + } + + string ans; + + int i = 0, j = 0; + + while(j < n) + { + ++curr[s[j]]; + + bool ok = true; + + for(auto&[ch, f] : freq) + { + if(curr[ch] < f) + { + ok = false; + break; + } + } + + if(ok) + { + while(true) + { + if(freq.find(s[i]) == freq.end()) + { + --curr[s[i]]; + ++i; + } + else if(curr[s[i]] > freq[s[i]]) + { + --curr[s[i]]; + ++i; + } + else + break; + + } + + if(ans.empty()) + { + ans = s.substr(i, j - i + 1); + } + else{ + string curr = s.substr(i, j - i + 1); + if(curr.size() < ans.size()) + { + ans = curr; + } + } + } + ++j; + } + + + + return ans; + } +}; \ No newline at end of file diff --git a/0076-minimum-window-substring/README.md b/0076-minimum-window-substring/README.md new file mode 100644 index 00000000..0f0823a6 --- /dev/null +++ b/0076-minimum-window-substring/README.md @@ -0,0 +1,40 @@ +

76. Minimum Window Substring

Hard


Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

+ +

The testcases will be generated such that the answer is unique.

+ +

 

+

Example 1:

+ +
Input: s = "ADOBECODEBANC", t = "ABC"
+Output: "BANC"
+Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
+
+ +

Example 2:

+ +
Input: s = "a", t = "a"
+Output: "a"
+Explanation: The entire string s is the minimum window.
+
+ +

Example 3:

+ +
Input: s = "a", t = "aa"
+Output: ""
+Explanation: Both 'a's from t must be included in the window.
+Since the largest window of s only has one 'a', return empty string.
+
+ +

 

+

Constraints:

+ +
    +
  • m == s.length
  • +
  • n == t.length
  • +
  • 1 <= m, n <= 105
  • +
  • s and t consist of uppercase and lowercase English letters.
  • +
+ +

 

+

Follow up: Could you find an algorithm that runs in O(m + n) time?

+
\ No newline at end of file diff --git a/0077-combinations/0077-combinations.cpp b/0077-combinations/0077-combinations.cpp new file mode 100644 index 00000000..0ae513c5 --- /dev/null +++ b/0077-combinations/0077-combinations.cpp @@ -0,0 +1,32 @@ +class Solution { + +private: + void helper(int idx, int n, int k, vector ds, vector>& ans) + { + if(ds.size() == k) + { + ans.push_back(ds); + return; + } + + for(int i = idx; i <= n; ++i) + { + ds.push_back(i); + helper(i+1, n, k, ds, ans); + ds.pop_back(); + } + } + +public: + vector> combine(int n, int k) { + + vector ds; + + vector> ans; + + helper(1, n, k, ds, ans); + + return ans; + + } +}; \ No newline at end of file diff --git a/0077-combinations/NOTES.md b/0077-combinations/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0077-combinations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0078-subsets/0078-subsets.cpp b/0078-subsets/0078-subsets.cpp new file mode 100644 index 00000000..3a971dec --- /dev/null +++ b/0078-subsets/0078-subsets.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + + void helper(int idx, vector& ds, vector& nums, vector>& res) + { + if(idx == nums.size()) + { + res.push_back(ds); + return; + } + + ds.push_back(nums[idx]); + helper(idx+1, ds, nums, res); + ds.pop_back(); + helper(idx+1, ds, nums, res); + } + + vector> subsets(vector& nums) { + + vector> res; + vector ds; + + helper(0, ds, nums, res); + + return res; + } +}; \ No newline at end of file diff --git a/0078-subsets/NOTES.md b/0078-subsets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0078-subsets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0078-subsets/README.md b/0078-subsets/README.md new file mode 100644 index 00000000..226b26bb --- /dev/null +++ b/0078-subsets/README.md @@ -0,0 +1,26 @@ +

78. Subsets

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
+
+ +

Example 2:

+ +
Input: nums = [0]
+Output: [[],[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the numbers of nums are unique.
  • +
+
\ No newline at end of file diff --git a/0079-word-search/0079-word-search.cpp b/0079-word-search/0079-word-search.cpp new file mode 100644 index 00000000..158257fc --- /dev/null +++ b/0079-word-search/0079-word-search.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + + bool helper(int i, int j, int n, int m , int idx, vector >& board, string& word) + { + + if(idx == word.size()) + return true; + if(i <0 or j < 0 or i >= n or j >= m or board[i][j] == '!' or board[i][j] != word[idx]) + return false; + char ch = board[i][j]; + board[i][j] = '!'; + + int top = helper(i-1,j,n,m,idx+1,board,word); + int bottom = helper(i+1,j,n,m,idx+1, board, word); + int left = helper(i,j-1,n,m,idx+1,board,word); + int right = helper(i,j+1,n,m,idx+1,board,word); + + board[i][j] = ch; + + return top or bottom or left or right; + + + } + + bool exist(vector>& board, string word) { + + int n = board.size(); + int m = board[0].size(); + + for(int i = 0; i79. Word Search

Medium


Given an m x n grid of characters board and a string word, return true if word exists in the grid.

+ +

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

+ +

 

+

Example 1:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
+Output: true
+
+ +

Example 2:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
+Output: true
+
+ +

Example 3:

+ +
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n = board[i].length
  • +
  • 1 <= m, n <= 6
  • +
  • 1 <= word.length <= 15
  • +
  • board and word consists of only lowercase and uppercase English letters.
  • +
+ +

 

+

Follow up: Could you use search pruning to make your solution faster with a larger board?

+
\ No newline at end of file diff --git a/0081-search-in-rotated-sorted-array-ii/0081-search-in-rotated-sorted-array-ii.cpp b/0081-search-in-rotated-sorted-array-ii/0081-search-in-rotated-sorted-array-ii.cpp new file mode 100644 index 00000000..b23a54b1 --- /dev/null +++ b/0081-search-in-rotated-sorted-array-ii/0081-search-in-rotated-sorted-array-ii.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + bool search(vector& nums, int target) { + + int start = 0, end = nums.size()-1; + + while(start <= end) + { + int mid = (start + end) >> 1; + + if(nums[mid] == target) + return true; + + + if(nums[mid] == nums[start] and nums[mid] == nums[end]) + ++start, --end; + else if(nums[mid] >= nums[start]) + { + if(target >= nums[start] and target <= nums[mid]) + { + end = mid - 1; + } + else + { + start = mid + 1; + } + } + else + { + if(target >= nums[mid] and target <= nums[end]) + { + start = mid+1; + } + else + { + end = mid - 1; + } + } + } + + return false; + + } +}; \ No newline at end of file diff --git a/0081-search-in-rotated-sorted-array-ii/NOTES.md b/0081-search-in-rotated-sorted-array-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0081-search-in-rotated-sorted-array-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0084-largest-rectangle-in-histogram/0084-largest-rectangle-in-histogram.cpp b/0084-largest-rectangle-in-histogram/0084-largest-rectangle-in-histogram.cpp new file mode 100644 index 00000000..c3a3f135 --- /dev/null +++ b/0084-largest-rectangle-in-histogram/0084-largest-rectangle-in-histogram.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int largestRectangleArea(vector& heights) { + + int n = heights.size(); + stack st; + int ans = 0; + + for(int i = 0; i<=n; ++i) + { + while(!st.empty() and (i == n or heights[st.top()] >= heights[i])) + { + int height = heights[st.top()]; + st.pop(); + + int width; + if(st.empty()) + width = i; + else + width = i - st.top() - 1; + + ans = max(ans, height * width); + } + st.push(i); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0084-largest-rectangle-in-histogram/NOTES.md b/0084-largest-rectangle-in-histogram/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0084-largest-rectangle-in-histogram/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0084-largest-rectangle-in-histogram/README.md b/0084-largest-rectangle-in-histogram/README.md new file mode 100644 index 00000000..8d5fb02f --- /dev/null +++ b/0084-largest-rectangle-in-histogram/README.md @@ -0,0 +1,25 @@ +

84. Largest Rectangle in Histogram

Hard


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

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: heights = [2,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 105
  • +
  • 0 <= heights[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0085-maximal-rectangle/0085-maximal-rectangle.cpp b/0085-maximal-rectangle/0085-maximal-rectangle.cpp new file mode 100644 index 00000000..7d380ae0 --- /dev/null +++ b/0085-maximal-rectangle/0085-maximal-rectangle.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + + int largestRectangleInHistogram(vector& heights) + { + int n = heights.size(); + stack st; + int ans = 0; + + for(int i = 0; i<=n; ++i) + { + while(!st.empty() and (i == n or heights[st.top()] >= heights[i])) + { + int height = heights[st.top()]; + st.pop(); + + int width; + if(st.empty()) + width = i; + else + width = i - st.top() - 1; + + ans = max(ans, height * width); + } + st.push(i); + } + + return ans; + } + + int maximalRectangle(vector>& matrix) { + + int n = matrix.size(), m = matrix[0].size(); + vector dp(m,0); + int maxArea = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(matrix[i][j] == '1') + dp[j] += 1; + else + dp[j] = 0; + } + + int area = largestRectangleInHistogram(dp); + maxArea = max(area,maxArea); + } + return maxArea; + } +}; \ No newline at end of file diff --git a/0085-maximal-rectangle/NOTES.md b/0085-maximal-rectangle/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0085-maximal-rectangle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0085-maximal-rectangle/README.md b/0085-maximal-rectangle/README.md new file mode 100644 index 00000000..3dcfdf06 --- /dev/null +++ b/0085-maximal-rectangle/README.md @@ -0,0 +1,32 @@ +

85. Maximal Rectangle

Hard


Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 6
+Explanation: The maximal rectangle is shown in the above picture.
+
+ +

Example 2:

+ +
Input: matrix = [["0"]]
+Output: 0
+
+ +

Example 3:

+ +
Input: matrix = [["1"]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • rows == matrix.length
  • +
  • cols == matrix[i].length
  • +
  • 1 <= row, cols <= 200
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/0086-partition-list/0086-partition-list.cpp b/0086-partition-list/0086-partition-list.cpp new file mode 100644 index 00000000..b8f5f9ac --- /dev/null +++ b/0086-partition-list/0086-partition-list.cpp @@ -0,0 +1,42 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + + ListNode* leftHead = new ListNode(0); + ListNode* rightHead = new ListNode(0); + + ListNode* dummy = head, *left = leftHead, *right = rightHead; + + while(dummy) + { + if(dummy->val < x) + { + left->next = dummy; + left = left->next; + } + else + { + right->next = dummy; + right = right->next; + } + + dummy = dummy->next; + } + + right->next = nullptr; + + left->next = rightHead->next; + + return leftHead->next; + } +}; \ No newline at end of file diff --git a/0086-partition-list/NOTES.md b/0086-partition-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0086-partition-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0086-partition-list/README.md b/0086-partition-list/README.md new file mode 100644 index 00000000..372a542c --- /dev/null +++ b/0086-partition-list/README.md @@ -0,0 +1,26 @@ +

86. Partition List

Medium


Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

+ +

You should preserve the original relative order of the nodes in each of the two partitions.

+ +

 

+

Example 1:

+ +
Input: head = [1,4,3,2,5,2], x = 3
+Output: [1,2,2,4,3,5]
+
+ +

Example 2:

+ +
Input: head = [2,1], x = 2
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 200].
  • +
  • -100 <= Node.val <= 100
  • +
  • -200 <= x <= 200
  • +
+
\ No newline at end of file diff --git a/0087-scramble-string/0087-scramble-string.cpp b/0087-scramble-string/0087-scramble-string.cpp new file mode 100644 index 00000000..1b4bacbf --- /dev/null +++ b/0087-scramble-string/0087-scramble-string.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + + bool helper(string s1, string s2, unordered_map& mp) + { + int n = s1.size(); + + if(s1 == s2) + { + mp.insert({s1+s2, true}); + return true; + } + + if(mp.find(s1 + s2) != mp.end()) + return mp[s1+s2]; + + for(int i = 1; i < n; ++i) + { + if(helper(s1.substr(0,i), s2.substr(n-i), mp) and helper(s1.substr(i),s2.substr(0,n-i), mp)) + { + mp.insert({s1+s2,true}); + return true; + } + if(helper(s1.substr(0,i), s2.substr(0,i), mp) and helper(s1.substr(i), s2.substr(i),mp)) + { + mp.insert({s1+s2,true}); + return true; + } + } + + mp.insert({s1+s2,false}); + return false; + } + + bool isScramble(string s1, string s2) { + + unordered_map mp; + return helper(s1, s2, mp); + + } +}; \ No newline at end of file diff --git a/0087-scramble-string/NOTES.md b/0087-scramble-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0087-scramble-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0087-scramble-string/README.md b/0087-scramble-string/README.md new file mode 100644 index 00000000..b641e0ac --- /dev/null +++ b/0087-scramble-string/README.md @@ -0,0 +1,52 @@ +

87. Scramble String

Hard


We can scramble a string s to get a string t using the following algorithm:

+ +
    +
  1. If the length of the string is 1, stop.
  2. +
  3. If the length of the string is > 1, do the following: +
      +
    • Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.
    • +
    • Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
    • +
    • Apply step 1 recursively on each of the two substrings x and y.
    • +
    +
  4. +
+ +

Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: s1 = "great", s2 = "rgeat"
+Output: true
+Explanation: One possible scenario applied on s1 is:
+"great" --> "gr/eat" // divide at random index.
+"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
+"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.
+"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
+"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
+"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
+The algorithm stops now, and the result string is "rgeat" which is s2.
+As one possible scenario led s1 to be scrambled to s2, we return true.
+
+ +

Example 2:

+ +
Input: s1 = "abcde", s2 = "caebd"
+Output: false
+
+ +

Example 3:

+ +
Input: s1 = "a", s2 = "a"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • s1.length == s2.length
  • +
  • 1 <= s1.length <= 30
  • +
  • s1 and s2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0088-merge-sorted-array/0088-merge-sorted-array.cpp b/0088-merge-sorted-array/0088-merge-sorted-array.cpp new file mode 100644 index 00000000..f5bd7797 --- /dev/null +++ b/0088-merge-sorted-array/0088-merge-sorted-array.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + + int i = m-1, j = n-1, k = n+m-1; + + while(i >= 0 and j >= 0) + { + if(nums1[i] > nums2[j]) + nums1[k--] = nums1[i--]; + else + nums1[k--] = nums2[j--]; + } + + while(i >= 0) + nums1[k--] = nums1[i--]; + while(j >= 0) + nums1[k--] = nums2[j--]; + + } +}; \ No newline at end of file diff --git a/0088-merge-sorted-array/NOTES.md b/0088-merge-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0088-merge-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0088-merge-sorted-array/README.md b/0088-merge-sorted-array/README.md new file mode 100644 index 00000000..edd52f0d --- /dev/null +++ b/0088-merge-sorted-array/README.md @@ -0,0 +1,46 @@ +

88. Merge Sorted Array

Easy


You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

+ +

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

+ +

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
+Output: [1,2,2,3,5,6]
+Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
+The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
+
+ +

Example 2:

+ +
Input: nums1 = [1], m = 1, nums2 = [], n = 0
+Output: [1]
+Explanation: The arrays we are merging are [1] and [].
+The result of the merge is [1].
+
+ +

Example 3:

+ +
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
+Output: [1]
+Explanation: The arrays we are merging are [] and [1].
+The result of the merge is [1].
+Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m + n
  • +
  • nums2.length == n
  • +
  • 0 <= m, n <= 200
  • +
  • 1 <= m + n <= 200
  • +
  • -109 <= nums1[i], nums2[j] <= 109
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

+
\ No newline at end of file diff --git a/0090-subsets-ii/0090-subsets-ii.cpp b/0090-subsets-ii/0090-subsets-ii.cpp new file mode 100644 index 00000000..f2522e66 --- /dev/null +++ b/0090-subsets-ii/0090-subsets-ii.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + void helper(int idx, vector ds, vector& nums, vector>& res) + { + res.push_back(ds); + + for(int i = idx; i < nums.size(); ++i) + { + if(i > idx and nums[i] == nums[i-1]) + continue; + ds.push_back(nums[i]); + helper(i+1, ds, nums, res); + ds.pop_back(); + } + } + + + vector> subsetsWithDup(vector& nums) { + + sort(nums.begin(), nums.end()); + + vector> res; + vector ds; + + helper(0, ds, nums, res); + + return res; + + } +}; \ No newline at end of file diff --git a/0090-subsets-ii/NOTES.md b/0090-subsets-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0090-subsets-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0090-subsets-ii/README.md b/0090-subsets-ii/README.md new file mode 100644 index 00000000..49bedbe0 --- /dev/null +++ b/0090-subsets-ii/README.md @@ -0,0 +1,20 @@ +

90. Subsets II

Medium


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [1,2,2]
+Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
+

Example 2:

+
Input: nums = [0]
+Output: [[],[0]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
+
\ No newline at end of file diff --git a/0091-decode-ways/0091-decode-ways.cpp b/0091-decode-ways/0091-decode-ways.cpp new file mode 100644 index 00000000..ce5333e9 --- /dev/null +++ b/0091-decode-ways/0091-decode-ways.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + + int helper(int idx, int n, string& s, vector& dp) + { + if(idx == n) + return 1; + + if(s[idx] == '0') + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int first = 0, second = 0; + + if(idx + 2 <= n) + { + string curr = s.substr(idx, 2); + + if(stoi(curr) >= 1 and stoi(curr) <= 26) + { + first = helper(idx + 2, n, s, dp); + } + } + + int ch = s[idx] - '0'; + + if(ch >= 1 and ch <= 26) + second = helper(idx + 1,n, s, dp); + + return dp[idx] = first + second; + } + + int numDecodings(string s) { + + int n = s.size(); + + vector dp(n+1, -1); + + return helper(0, n, s, dp); + + } +}; \ No newline at end of file diff --git a/0091-decode-ways/NOTES.md b/0091-decode-ways/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0091-decode-ways/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0091-decode-ways/README.md b/0091-decode-ways/README.md new file mode 100644 index 00000000..84e177d9 --- /dev/null +++ b/0091-decode-ways/README.md @@ -0,0 +1,51 @@ +

91. Decode Ways

Medium


A message containing letters from A-Z can be encoded into numbers using the following mapping:

+ +
'A' -> "1"
+'B' -> "2"
+...
+'Z' -> "26"
+
+ +

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

+ +
    +
  • "AAJF" with the grouping (1 1 10 6)
  • +
  • "KJF" with the grouping (11 10 6)
  • +
+ +

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

+ +

Given a string s containing only digits, return the number of ways to decode it.

+ +

The test cases are generated so that the answer fits in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: s = "12"
+Output: 2
+Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
+
+ +

Example 2:

+ +
Input: s = "226"
+Output: 3
+Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
+
+ +

Example 3:

+ +
Input: s = "06"
+Output: 0
+Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only digits and may contain leading zero(s).
  • +
+
\ No newline at end of file diff --git a/0092-reverse-linked-list-ii/0092-reverse-linked-list-ii.cpp b/0092-reverse-linked-list-ii/0092-reverse-linked-list-ii.cpp new file mode 100644 index 00000000..0ad361ae --- /dev/null +++ b/0092-reverse-linked-list-ii/0092-reverse-linked-list-ii.cpp @@ -0,0 +1,82 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { + +private: + ListNode* reverse(ListNode* head) + { + ListNode* curr = head, *prev = nullptr; + + while(curr) + { + ListNode* nextNode = curr->next; + curr->next = prev; + prev = curr; + curr = nextNode; + } + + return prev; + } +public: + ListNode* reverseBetween(ListNode* head, int left, int right) { + + if(left == right) + return head; + + ListNode* leftNode = nullptr, *rightNode = nullptr; + + ListNode* prevLeftNode = nullptr, *nextRightNode = nullptr; + + ListNode* curr= head; + + int counter = 0; + + if(left == 1) + { + prevLeftNode = nullptr; + leftNode = curr; + } + + + while(curr) + { + ++counter; + + if(counter == left-1) + { + prevLeftNode = curr; + leftNode = curr->next; + } + + if(counter == right) + { + rightNode = curr; + nextRightNode = curr->next; + } + + curr = curr->next; + } + + if(rightNode) + rightNode->next = nullptr; + + ListNode* rev = reverse(leftNode); + + if(prevLeftNode) + prevLeftNode->next = rev; + if(nextRightNode) + leftNode->next = nextRightNode; + + if(prevLeftNode) + return head; + return rev; + } +}; \ No newline at end of file diff --git a/0092-reverse-linked-list-ii/README.md b/0092-reverse-linked-list-ii/README.md new file mode 100644 index 00000000..8c76add5 --- /dev/null +++ b/0092-reverse-linked-list-ii/README.md @@ -0,0 +1,27 @@ +

92. Reverse Linked List II

Medium


Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], left = 2, right = 4
+Output: [1,4,3,2,5]
+
+ +

Example 2:

+ +
Input: head = [5], left = 1, right = 1
+Output: [5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= n <= 500
  • +
  • -500 <= Node.val <= 500
  • +
  • 1 <= left <= right <= n
  • +
+ +

 

+Follow up: Could you do it in one pass?
\ No newline at end of file diff --git a/0093-restore-ip-addresses/0093-restore-ip-addresses.cpp b/0093-restore-ip-addresses/0093-restore-ip-addresses.cpp new file mode 100644 index 00000000..023ba55b --- /dev/null +++ b/0093-restore-ip-addresses/0093-restore-ip-addresses.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + + bool isValid(string str) + { + if(str[0] == '0') + return false; + + int num = stoi(str); + + return num <= 255; + } + + void helper(int idx, string& s, int part, string ans, vector& res) + { + if(idx == s.size() or part == 4) + { + if(idx == s.size() and part == 4) + { + res.push_back(ans.substr(0,ans.size()-1)); + } + return; + } + + helper(idx + 1, s, part + 1, ans + s[idx] + "." , res); + if(idx + 2 <= s.size() and isValid(s.substr(idx,2))) + helper(idx + 2, s, part + 1, ans + s.substr(idx,2) + "." , res); + if(idx + 3 <= s.size() and isValid(s.substr(idx,3))) + helper(idx + 3, s, part + 1, ans + s.substr(idx,3) +"." , res); + } + + vector restoreIpAddresses(string s) { + + vector res; + + helper(0, s, 0, "" , res); + + return res; + + } +}; \ No newline at end of file diff --git a/0093-restore-ip-addresses/NOTES.md b/0093-restore-ip-addresses/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0093-restore-ip-addresses/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0093-restore-ip-addresses/README.md b/0093-restore-ip-addresses/README.md new file mode 100644 index 00000000..6456cfc0 --- /dev/null +++ b/0093-restore-ip-addresses/README.md @@ -0,0 +1,35 @@ +

93. Restore IP Addresses

Medium


A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

+ +
    +
  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.
  • +
+ +

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

+ +

 

+

Example 1:

+ +
Input: s = "25525511135"
+Output: ["255.255.11.135","255.255.111.35"]
+
+ +

Example 2:

+ +
Input: s = "0000"
+Output: ["0.0.0.0"]
+
+ +

Example 3:

+ +
Input: s = "101023"
+Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 20
  • +
  • s consists of digits only.
  • +
+
\ No newline at end of file diff --git a/0094-binary-tree-inorder-traversal/0094-binary-tree-inorder-traversal.cpp b/0094-binary-tree-inorder-traversal/0094-binary-tree-inorder-traversal.cpp new file mode 100644 index 00000000..e114d0a2 --- /dev/null +++ b/0094-binary-tree-inorder-traversal/0094-binary-tree-inorder-traversal.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + + vector inorder; + TreeNode * curr = root; + + while(curr) + { + if(!curr->left) + { + inorder.push_back(curr->val); + curr = curr->right; + } + else + { + TreeNode *prev = curr->left; + while(prev->right and prev->right != curr) + prev = prev->right; + + if(!prev->right) + { + prev->right = curr; + curr = curr->left; + } + else + { + prev->right = nullptr; + inorder.push_back(curr->val); + curr = curr->right; + } + } + } + return inorder; + } +}; \ No newline at end of file diff --git a/0094-binary-tree-inorder-traversal/NOTES.md b/0094-binary-tree-inorder-traversal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0094-binary-tree-inorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0094-binary-tree-inorder-traversal/README.md b/0094-binary-tree-inorder-traversal/README.md new file mode 100644 index 00000000..ad2de4dc --- /dev/null +++ b/0094-binary-tree-inorder-traversal/README.md @@ -0,0 +1,31 @@ +

94. Binary Tree Inorder Traversal

Easy


Given the root of a binary tree, return the inorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively?
\ No newline at end of file diff --git a/0095-unique-binary-search-trees-ii/0095-unique-binary-search-trees-ii.cpp b/0095-unique-binary-search-trees-ii/0095-unique-binary-search-trees-ii.cpp new file mode 100644 index 00000000..68d2715e --- /dev/null +++ b/0095-unique-binary-search-trees-ii/0095-unique-binary-search-trees-ii.cpp @@ -0,0 +1,58 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + +private: + vector helper(int start, int end) + { + vector ans; + + if(start > end) + { + ans.push_back(nullptr); + return ans; + } + + if(start == end) + { + ans.push_back(new TreeNode(start)); + return ans; + } + + for(int i = start; i <= end; ++i) + { + vector leftPossibleSubtrees = helper(start, i-1); + vector rightPossibleSubtrees = helper(i+1, end); + + + for(auto rLeft : leftPossibleSubtrees) + { + for(auto rRight : rightPossibleSubtrees) + { + TreeNode* root = new TreeNode(i); + root->left = rLeft; + root->right = rRight; + ans.push_back(root); + } + } + } + + return ans; + } + +public: + vector generateTrees(int n) { + + return helper(1, n); + + } +}; \ No newline at end of file diff --git a/0095-unique-binary-search-trees-ii/NOTES.md b/0095-unique-binary-search-trees-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0095-unique-binary-search-trees-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0096-unique-binary-search-trees/0096-unique-binary-search-trees.cpp b/0096-unique-binary-search-trees/0096-unique-binary-search-trees.cpp new file mode 100644 index 00000000..9260f8ab --- /dev/null +++ b/0096-unique-binary-search-trees/0096-unique-binary-search-trees.cpp @@ -0,0 +1,27 @@ +class Solution { + +private: + int helper(int n) + { + if(n <= 1) + return 1; + + int ans = 0; + + for(int i = 1; i <= n; ++i) + { + int leftPossibleSubtrees = helper(i-1); + int rightPossibleSubtrees = helper(n-i); + + ans += (leftPossibleSubtrees * rightPossibleSubtrees); + } + return ans; + } + +public: + int numTrees(int n) { + + return helper(n); + + } +}; \ No newline at end of file diff --git a/0096-unique-binary-search-trees/NOTES.md b/0096-unique-binary-search-trees/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0096-unique-binary-search-trees/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0096-unique-binary-search-trees/README.md b/0096-unique-binary-search-trees/README.md new file mode 100644 index 00000000..92b6a309 --- /dev/null +++ b/0096-unique-binary-search-trees/README.md @@ -0,0 +1,22 @@ +

96. Unique Binary Search Trees

Medium


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

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 5
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 19
  • +
+
\ No newline at end of file diff --git a/0097-interleaving-string/0097-interleaving-string.cpp b/0097-interleaving-string/0097-interleaving-string.cpp new file mode 100644 index 00000000..f785361c --- /dev/null +++ b/0097-interleaving-string/0097-interleaving-string.cpp @@ -0,0 +1,36 @@ +class Solution { + +private: + bool helper(int i , int j, int n, int m, int M, string& s1, string& s2, string& s3, vector >& dp) + { + if(i == n and j == m and i+j == M) + return true; + + bool result = false; + + if(dp[i][j] != -1) + return dp[i][j]; + + if(s1[i] == s3[i+j]) + result |= helper(i+1, j, n, m, M, s1, s2, s3, dp); + + if(s2[j] == s3[i+j]) + result |= helper(i, j+1, n, m, M, s1, s2, s3, dp); + + return dp[i][j] = result; + } + +public: + bool isInterleave(string s1, string s2, string s3) { + + int n = s1.size(), m = s2.size(), M = s3.size(); + + if(n + m != M) + return false; + + vector > dp(n+1, vector(m+1, -1)); + + return helper(0, 0, n, m, M, s1, s2, s3, dp); + + } +}; \ No newline at end of file diff --git a/0097-interleaving-string/NOTES.md b/0097-interleaving-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0097-interleaving-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0097-interleaving-string/README.md b/0097-interleaving-string/README.md new file mode 100644 index 00000000..0d3ffd22 --- /dev/null +++ b/0097-interleaving-string/README.md @@ -0,0 +1,49 @@ +

97. Interleaving String

Medium


Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

+ +

An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that:

+ +
    +
  • s = s1 + s2 + ... + sn
  • +
  • t = t1 + t2 + ... + tm
  • +
  • |n - m| <= 1
  • +
  • The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...
  • +
+ +

Note: a + b is the concatenation of strings a and b.

+ +

 

+

Example 1:

+ +
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
+Output: true
+Explanation: One way to obtain s3 is:
+Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a".
+Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac".
+Since s3 can be obtained by interleaving s1 and s2, we return true.
+
+ +

Example 2:

+ +
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
+Output: false
+Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.
+
+ +

Example 3:

+ +
Input: s1 = "", s2 = "", s3 = ""
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s1.length, s2.length <= 100
  • +
  • 0 <= s3.length <= 200
  • +
  • s1, s2, and s3 consist of lowercase English letters.
  • +
+ +

 

+

Follow up: Could you solve it using only O(s2.length) additional memory space?

+
\ No newline at end of file diff --git a/0098. Validate Binary Search Tree.cpp b/0098. Validate Binary Search Tree.cpp new file mode 100644 index 00000000..861586eb --- /dev/null +++ b/0098. Validate Binary Search Tree.cpp @@ -0,0 +1,21 @@ +// 98.✅ Validate Binary Search Tree + +class Solution +{ +public: + bool helper(TreeNode *root, long mn, long mx) + { + if (!root) + return true; + + if (root->val <= mn || root->val >= mx) + return false; + + return helper(root->left, mn, root->val) && helper(root->right, root->val, mx); + } + + bool isValidBST(TreeNode *root) + { + return helper(root, LONG_MIN, LONG_MAX); + } +}; diff --git a/0100-same-tree/0100-same-tree.cpp b/0100-same-tree/0100-same-tree.cpp new file mode 100644 index 00000000..fd41f371 --- /dev/null +++ b/0100-same-tree/0100-same-tree.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + bool helper(TreeNode* p, TreeNode* q) + { + if(!p and !q) + return true; + if(!p and q or p and !q or p->val != q->val) + return false; + return helper(p->left,q->left) and helper(p->right,q->right); + } + + bool isSameTree(TreeNode* p, TreeNode* q) { + return helper(p,q); + } +}; \ No newline at end of file diff --git a/0100-same-tree/NOTES.md b/0100-same-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0100-same-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0100-same-tree/README.md b/0100-same-tree/README.md new file mode 100644 index 00000000..ac214aa8 --- /dev/null +++ b/0100-same-tree/README.md @@ -0,0 +1,31 @@ +

100. Same Tree

Easy


Given the roots of two binary trees p and q, write a function to check if they are the same or not.

+ +

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

+ +

 

+

Example 1:

+ +
Input: p = [1,2,3], q = [1,2,3]
+Output: true
+
+ +

Example 2:

+ +
Input: p = [1,2], q = [1,null,2]
+Output: false
+
+ +

Example 3:

+ +
Input: p = [1,2,1], q = [1,1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 100].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/0101-symmetric-tree/0101-symmetric-tree.cpp b/0101-symmetric-tree/0101-symmetric-tree.cpp new file mode 100644 index 00000000..a623ddc8 --- /dev/null +++ b/0101-symmetric-tree/0101-symmetric-tree.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if(root == nullptr) + return true; + queue q1, q2; + q1.push(root->left); + q2.push(root->right); + + while(!q1.empty() and !q2.empty()) + { + TreeNode*curr1 = q1.front(); + TreeNode*curr2 = q2.front(); + q1.pop(); + q2.pop(); + + if(!curr1 and !curr2) + continue; + if(!curr1 or !curr2) + return false; + if(curr1->val != curr2->val) + return false; + + q1.push(curr1->left); + q1.push(curr1->right); + q2.push(curr2->right); + q2.push(curr2->left); + } + return true; + } +}; \ No newline at end of file diff --git a/0101-symmetric-tree/NOTES.md b/0101-symmetric-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0101-symmetric-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0101-symmetric-tree/README.md b/0101-symmetric-tree/README.md new file mode 100644 index 00000000..a4b74c2d --- /dev/null +++ b/0101-symmetric-tree/README.md @@ -0,0 +1,25 @@ +

101. Symmetric Tree

Easy


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

+ +

 

+

Example 1:

+ +
Input: root = [1,2,2,3,4,4,3]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,2,null,3,null,3]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Could you solve it both recursively and iteratively?
\ No newline at end of file diff --git a/0103-binary-tree-zigzag-level-order-traversal/0103-binary-tree-zigzag-level-order-traversal.cpp b/0103-binary-tree-zigzag-level-order-traversal/0103-binary-tree-zigzag-level-order-traversal.cpp new file mode 100644 index 00000000..8a1f20bd --- /dev/null +++ b/0103-binary-tree-zigzag-level-order-traversal/0103-binary-tree-zigzag-level-order-traversal.cpp @@ -0,0 +1,55 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + + vector> ans; + + if(!root) + return ans; + + queue q; + q.push(root); + + bool flag = 0; + while(!q.empty()) + { + int size = q.size(); + + vector v; + for(int i = 0; ileft) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + + v.push_back(curr->val); + } + + + if(flag & 1) + reverse(v.begin(),v.end()); + + ans.push_back(v); + + flag ^= 1; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0103-binary-tree-zigzag-level-order-traversal/README.md b/0103-binary-tree-zigzag-level-order-traversal/README.md new file mode 100644 index 00000000..001e9e36 --- /dev/null +++ b/0103-binary-tree-zigzag-level-order-traversal/README.md @@ -0,0 +1,29 @@ +

103. Binary Tree Zigzag Level Order Traversal

Medium


Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[20,9],[15,7]]
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.cpp b/0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.cpp new file mode 100644 index 00000000..a5e75f91 --- /dev/null +++ b/0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.cpp @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int height(TreeNode* root) + { + if(!root) + return 0; + int left = 1 + height(root->left); + int right = 1 + height(root->right); + + return max(left,right); + } + + int maxDepth(TreeNode* root) { + return height(root); + } +}; \ No newline at end of file diff --git a/0104-maximum-depth-of-binary-tree/NOTES.md b/0104-maximum-depth-of-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0104-maximum-depth-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0104-maximum-depth-of-binary-tree/README.md b/0104-maximum-depth-of-binary-tree/README.md new file mode 100644 index 00000000..60a62249 --- /dev/null +++ b/0104-maximum-depth-of-binary-tree/README.md @@ -0,0 +1,25 @@ +

104. Maximum Depth of Binary Tree

Easy


Given the root of a binary tree, return its maximum depth.

+ +

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 3
+
+ +

Example 2:

+ +
Input: root = [1,null,2]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0105-construct-binary-tree-from-preorder-and-inorder-traversal/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp b/0105-construct-binary-tree-from-preorder-and-inorder-traversal/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp new file mode 100644 index 00000000..10e7322d --- /dev/null +++ b/0105-construct-binary-tree-from-preorder-and-inorder-traversal/0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + TreeNode* build(int inStart, int preStart,int inEnd, int preEnd, vector& inorder, vector& preorder, unordered_map& mp) + { + if(inStart > inEnd or preStart > preEnd) + return nullptr; + + TreeNode* root = new TreeNode(preorder[preStart]); + + int idx = mp[root->val]; + int inLeft = idx - inStart; + + root->left = build(inStart, preStart+1, idx - 1, preStart + inLeft,inorder, preorder, mp); + root->right = build(idx+1,preStart + inLeft + 1,inEnd, preEnd, inorder, preorder, mp); + + return root; + } + + + TreeNode* buildTree(vector& preorder, vector& inorder) { + + unordered_map mp; + int n = inorder.size(),m = preorder.size(); + + for(int i = 0; i < n; ++i) + mp.insert({inorder[i],i}); + + TreeNode* root = build(0,0,n-1,m-1,inorder,preorder,mp); + + return root; + + } +}; \ No newline at end of file diff --git a/0105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md b/0105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md new file mode 100644 index 00000000..c8bfae48 --- /dev/null +++ b/0105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md @@ -0,0 +1,28 @@ +

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium


Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
Input: preorder = [-1], inorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 3000
  • +
  • inorder.length == preorder.length
  • +
  • -3000 <= preorder[i], inorder[i] <= 3000
  • +
  • preorder and inorder consist of unique values.
  • +
  • Each value of inorder also appears in preorder.
  • +
  • preorder is guaranteed to be the preorder traversal of the tree.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
+
\ No newline at end of file diff --git a/0106-construct-binary-tree-from-inorder-and-postorder-traversal/README.md b/0106-construct-binary-tree-from-inorder-and-postorder-traversal/README.md new file mode 100644 index 00000000..962949b0 --- /dev/null +++ b/0106-construct-binary-tree-from-inorder-and-postorder-traversal/README.md @@ -0,0 +1,28 @@ +

106. Construct Binary Tree from Inorder and Postorder Traversal

Medium


Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
Input: inorder = [-1], postorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= inorder.length <= 3000
  • +
  • postorder.length == inorder.length
  • +
  • -3000 <= inorder[i], postorder[i] <= 3000
  • +
  • inorder and postorder consist of unique values.
  • +
  • Each value of postorder also appears in inorder.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
  • postorder is guaranteed to be the postorder traversal of the tree.
  • +
+
\ No newline at end of file diff --git a/0109-convert-sorted-list-to-binary-search-tree/0109-convert-sorted-list-to-binary-search-tree.cpp b/0109-convert-sorted-list-to-binary-search-tree/0109-convert-sorted-list-to-binary-search-tree.cpp new file mode 100644 index 00000000..63279058 --- /dev/null +++ b/0109-convert-sorted-list-to-binary-search-tree/0109-convert-sorted-list-to-binary-search-tree.cpp @@ -0,0 +1,50 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedListToBST(ListNode* head) { + if(head == NULL) + return NULL; + if(head -> next == NULL) + { + TreeNode *root = new TreeNode(head->val); + return root; + } + + ListNode *slow = head, *fast = head->next; + + while(fast -> next != NULL && fast->next->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + } + + ListNode *mid = slow->next; + slow ->next = NULL; + + TreeNode *root = new TreeNode(mid->val); + root->left = sortedListToBST(head); + root->right = sortedListToBST(mid->next); + + return root; + } +}; \ No newline at end of file diff --git a/0109-convert-sorted-list-to-binary-search-tree/README.md b/0109-convert-sorted-list-to-binary-search-tree/README.md new file mode 100644 index 00000000..1e21899b --- /dev/null +++ b/0109-convert-sorted-list-to-binary-search-tree/README.md @@ -0,0 +1,24 @@ +

109. Convert Sorted List to Binary Search Tree

Medium


Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.

+ +

 

+

Example 1:

+ +
Input: head = [-10,-3,0,5,9]
+Output: [0,-3,9,-10,null,5]
+Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
+
+ +

Example 2:

+ +
Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in head is in the range [0, 2 * 104].
  • +
  • -105 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/0110-balanced-binary-tree/0110-balanced-binary-tree.cpp b/0110-balanced-binary-tree/0110-balanced-binary-tree.cpp new file mode 100644 index 00000000..a8599a87 --- /dev/null +++ b/0110-balanced-binary-tree/0110-balanced-binary-tree.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int helper(TreeNode* root) + { + if(!root) + return 0; + int left = helper(root->left); + int right = helper(root->right); + + if(abs(left - right) > 1 or left == -1 or right == -1) + return -1; + + return 1 + max(left,right); + } + + + bool isBalanced(TreeNode* root) { + if(helper(root) == -1) + return false; + return true; + } +}; \ No newline at end of file diff --git a/0110-balanced-binary-tree/NOTES.md b/0110-balanced-binary-tree/NOTES.md new file mode 100644 index 00000000..9824a60c --- /dev/null +++ b/0110-balanced-binary-tree/NOTES.md @@ -0,0 +1,16 @@ +class Solution { +public: +int height(TreeNode* root) +{ +if(!root) +return 0; +return 1 + max(height(root->left),height(root->right)); +} +bool isBalanced(TreeNode* root) { +if(!root) +return true; +int left = height(root->left); +int right = height(root->right); +return abs(left - right) <= 1 and isBalanced(root->left) && isBalanced(root->right); +} +}; \ No newline at end of file diff --git a/0110-balanced-binary-tree/README.md b/0110-balanced-binary-tree/README.md new file mode 100644 index 00000000..60949b6e --- /dev/null +++ b/0110-balanced-binary-tree/README.md @@ -0,0 +1,29 @@ +

110. Balanced Binary Tree

Easy


Given a binary tree, determine if it is height-balanced.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: true
+
+ +

Example 2:

+ +
Input: root = [1,2,2,3,3,null,null,4,4]
+Output: false
+
+ +

Example 3:

+ +
Input: root = []
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -104 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/0112-path-sum/0112-path-sum.cpp b/0112-path-sum/0112-path-sum.cpp new file mode 100644 index 00000000..2e8485fe --- /dev/null +++ b/0112-path-sum/0112-path-sum.cpp @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + bool helper(TreeNode* root, int currSum, int targetSum) + { + if(!root) + { + return false; + } + if(!root->left and !root->right) + return currSum+root->val == targetSum; + + bool one = helper(root->left,currSum + root->val, targetSum); + bool two = helper(root->right,currSum + root->val, targetSum); + + return one or two; + } + + bool hasPathSum(TreeNode* root, int targetSum) { + + if(!root) + return false; + return helper(root,0,targetSum); + } +}; \ No newline at end of file diff --git a/0112-path-sum/NOTES.md b/0112-path-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0112-path-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0112-path-sum/README.md b/0112-path-sum/README.md new file mode 100644 index 00000000..6939ed6b --- /dev/null +++ b/0112-path-sum/README.md @@ -0,0 +1,38 @@ +

112. Path Sum

Easy


Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
+Output: true
+Explanation: The root-to-leaf path with the target sum is shown.
+
+ +

Example 2:

+ +
Input: root = [1,2,3], targetSum = 5
+Output: false
+Explanation: There two root-to-leaf paths in the tree:
+(1 --> 2): The sum is 3.
+(1 --> 3): The sum is 4.
+There is no root-to-leaf path with sum = 5.
+
+ +

Example 3:

+ +
Input: root = [], targetSum = 0
+Output: false
+Explanation: Since the tree is empty, there are no root-to-leaf paths.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+
\ No newline at end of file diff --git a/0113-path-sum-ii/0113-path-sum-ii.cpp b/0113-path-sum-ii/0113-path-sum-ii.cpp new file mode 100644 index 00000000..cee5e478 --- /dev/null +++ b/0113-path-sum-ii/0113-path-sum-ii.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, vector v, vector>& res, int targetSum) + { + if(!root) + return; + + if(!root->left and !root->right) + { + if(targetSum - root->val == 0) + { + v.push_back(root->val); + res.push_back(v); + return ; + } + return ; + } + + v.push_back(root->val); + helper(root->left,v,res,targetSum - root->val); + helper(root->right,v,res,targetSum - root->val); + v.pop_back(); + } + + vector> pathSum(TreeNode* root, int targetSum) { + + vector v; + vector> res; + + helper(root,v,res,targetSum); + + return res; + + } +}; \ No newline at end of file diff --git a/0113-path-sum-ii/README.md b/0113-path-sum-ii/README.md new file mode 100644 index 00000000..e07242b1 --- /dev/null +++ b/0113-path-sum-ii/README.md @@ -0,0 +1,35 @@ +

113. Path Sum II

Medium


Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

+ +

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
+Output: [[5,4,11,2],[5,8,4,5]]
+Explanation: There are two paths whose sum equals targetSum:
+5 + 4 + 11 + 2 = 22
+5 + 8 + 4 + 5 = 22
+
+ +

Example 2:

+ +
Input: root = [1,2,3], targetSum = 5
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1,2], targetSum = 0
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+
\ No newline at end of file diff --git a/0115-distinct-subsequences/0115-distinct-subsequences.cpp b/0115-distinct-subsequences/0115-distinct-subsequences.cpp new file mode 100644 index 00000000..c448881f --- /dev/null +++ b/0115-distinct-subsequences/0115-distinct-subsequences.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + + int numDistinct(string s, string t) { + + int n = s.size(), m = t.size(); + vector prev(m+1,0); + + for(int i = 0; i<=n; ++i) + prev[0] = 1; + + for(int i= 1; i<=n; ++i) + { + for(int j= m; j>=1; --j) + { + if(s[i-1] == t[j-1]) + prev[j] = prev[j-1] + prev[j]; + else + prev[j] = prev[j]; + } + } + return (int)prev[m]; + } +}; \ No newline at end of file diff --git a/0115-distinct-subsequences/NOTES.md b/0115-distinct-subsequences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0115-distinct-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0115-distinct-subsequences/README.md b/0115-distinct-subsequences/README.md new file mode 100644 index 00000000..9f536311 --- /dev/null +++ b/0115-distinct-subsequences/README.md @@ -0,0 +1,36 @@ +

115. Distinct Subsequences

Hard


Given two strings s and t, return the number of distinct subsequences of s which equals t.

+ +

The test cases are generated so that the answer fits on a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: s = "rabbbit", t = "rabbit"
+Output: 3
+Explanation:
+As shown below, there are 3 ways you can generate "rabbit" from s.
+rabbbit
+rabbbit
+rabbbit
+
+ +

Example 2:

+ +
Input: s = "babgbag", t = "bag"
+Output: 5
+Explanation:
+As shown below, there are 5 ways you can generate "bag" from s.
+babgbag
+babgbag
+babgbag
+babgbag
+babgbag
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 1000
  • +
  • s and t consist of English letters.
  • +
+
\ No newline at end of file diff --git a/0118-pascals-triangle/0118-pascals-triangle.cpp b/0118-pascals-triangle/0118-pascals-triangle.cpp new file mode 100644 index 00000000..e8518d00 --- /dev/null +++ b/0118-pascals-triangle/0118-pascals-triangle.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector> generate(int numRows) { + + vector> ans; + + for(int i = 1; i <= numRows; ++i) + { + if(i == 1) + { + ans.push_back({1}); + } + else if(i == 2) + { + ans.push_back({1,1}); + } + else + { + vector pref = ans.back(); + vector curr; + + curr.push_back(1); + + for(int j = 1; j < i-1; ++j) + { + curr.push_back(pref[j] + pref[j-1]); + } + + curr.push_back(1); + + ans.push_back(curr); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0118-pascals-triangle/NOTES.md b/0118-pascals-triangle/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0118-pascals-triangle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0118-pascals-triangle/README.md b/0118-pascals-triangle/README.md new file mode 100644 index 00000000..37f8fc62 --- /dev/null +++ b/0118-pascals-triangle/README.md @@ -0,0 +1,19 @@ +

118. Pascal's Triangle

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: numRows = 5
+Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
+

Example 2:

+
Input: numRows = 1
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= numRows <= 30
  • +
+
\ No newline at end of file diff --git a/0119-pascals-triangle-ii/0119-pascals-triangle-ii.cpp b/0119-pascals-triangle-ii/0119-pascals-triangle-ii.cpp new file mode 100644 index 00000000..e4855cf8 --- /dev/null +++ b/0119-pascals-triangle-ii/0119-pascals-triangle-ii.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector getRow(int rowIndex) { + + vector> v(rowIndex); + + if(rowIndex == 0) + return {1}; + else if(rowIndex == 1) + return {1, 1}; + else + { + v.push_back({1}); + v.push_back({1, 1}); + + for(int i = 2; i <= rowIndex; ++i) + { + vector curr; + curr.push_back(1); + + for(int j =1; j < v.back().size(); ++j) + { + curr.push_back(v.back()[j] + v.back()[j-1]); + } + + curr.push_back(1); + + v.push_back(curr); + } + return v.back(); + } + + } +}; \ No newline at end of file diff --git a/0119-pascals-triangle-ii/NOTES.md b/0119-pascals-triangle-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0119-pascals-triangle-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0119-pascals-triangle-ii/README.md b/0119-pascals-triangle-ii/README.md new file mode 100644 index 00000000..2c0ffdfb --- /dev/null +++ b/0119-pascals-triangle-ii/README.md @@ -0,0 +1,25 @@ +

119. Pascal's Triangle II

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: rowIndex = 3
+Output: [1,3,3,1]
+

Example 2:

+
Input: rowIndex = 0
+Output: [1]
+

Example 3:

+
Input: rowIndex = 1
+Output: [1,1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= rowIndex <= 33
  • +
+ +

 

+

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

+
\ No newline at end of file diff --git a/0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp b/0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 00000000..b0b77e4f --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(vector& prices) { + + int minPrice = INT_MAX, n = prices.size(); + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + minPrice = min(minPrice, prices[i]); + ans = max(ans, prices[i] - minPrice); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0121-best-time-to-buy-and-sell-stock/NOTES.md b/0121-best-time-to-buy-and-sell-stock/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0121-best-time-to-buy-and-sell-stock/README.md b/0121-best-time-to-buy-and-sell-stock/README.md new file mode 100644 index 00000000..9453c7e0 --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock/README.md @@ -0,0 +1,30 @@ +

121. Best Time to Buy and Sell Stock

Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

+ +

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+
+ +

Example 2:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0122-best-time-to-buy-and-sell-stock-ii/0122-best-time-to-buy-and-sell-stock-ii.cpp b/0122-best-time-to-buy-and-sell-stock-ii/0122-best-time-to-buy-and-sell-stock-ii.cpp new file mode 100644 index 00000000..c40923dc --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-ii/0122-best-time-to-buy-and-sell-stock-ii.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxProfit(vector& prices) { + + int n = prices.size(); + + int currBuy, currNotBuy, aheadBuy = 0, aheadNotBuy = 0; + + for(int i = n-1; i >=0 ; --i) + { + currBuy = max(-prices[i] + aheadNotBuy, aheadBuy); + currNotBuy = max(prices[i] + aheadBuy, aheadNotBuy); + + aheadBuy = currBuy; + aheadNotBuy = currNotBuy; + } + + return aheadBuy; + + } +}; \ No newline at end of file diff --git a/0122-best-time-to-buy-and-sell-stock-ii/NOTES.md b/0122-best-time-to-buy-and-sell-stock-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0122-best-time-to-buy-and-sell-stock-ii/README.md b/0122-best-time-to-buy-and-sell-stock-ii/README.md new file mode 100644 index 00000000..0cf1818e --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-ii/README.md @@ -0,0 +1,39 @@ +

122. Best Time to Buy and Sell Stock II

Medium


You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

+ +

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

+ +

Find and return the maximum profit you can achieve.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 7
+Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
+Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
+Total profit is 4 + 3 = 7.
+
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Total profit is 4.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 3 * 104
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0123-best-time-to-buy-and-sell-stock-iii/0123-best-time-to-buy-and-sell-stock-iii.cpp b/0123-best-time-to-buy-and-sell-stock-iii/0123-best-time-to-buy-and-sell-stock-iii.cpp new file mode 100644 index 00000000..a7297d11 --- /dev/null +++ b/0123-best-time-to-buy-and-sell-stock-iii/0123-best-time-to-buy-and-sell-stock-iii.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + + int helper(int index, vector& prices,int ok, int n, vector>& dp) + { + if(index == n or ok == 4) + return 0; + if(dp[index][ok] != -1) + return dp[index][ok]; + if(ok % 2 == 0) + return dp[index][ok] = max(-prices[index] + helper(index+1, prices,ok+1, n, dp) ,helper(index+1,prices,ok, n, dp)); + return dp[index][ok] = max(prices[index] + helper(index+1, prices,ok+1, n, dp), helper(index+1, prices,ok, n, dp)); + + } + + int maxProfit(vector& prices) { + + int n = prices.size(); + vector> dp(n+1,vector(5,0)); + + for(int i = n - 1; i >= 0; --i) + { + for(int ok = 3; ok >= 0; --ok) + { + if(ok % 2 == 0) + dp[i][ok] = max(-prices[i] + dp[i+1][ok+1], dp[i+1][ok]); + else + dp[i][ok] = max(prices[i] + dp[i+1][ok+1], dp[i+1][ok]); + } + } + + return dp[0][0]; + } +}; \ No newline at end of file diff --git a/0123-best-time-to-buy-and-sell-stock-iii/NOTES.md b/0123-best-time-to-buy-and-sell-stock-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0123-best-time-to-buy-and-sell-stock-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0123-best-time-to-buy-and-sell-stock-iii/README.md b/0123-best-time-to-buy-and-sell-stock-iii/README.md new file mode 100644 index 00000000..ecc42d25 --- /dev/null +++ b/0123-best-time-to-buy-and-sell-stock-iii/README.md @@ -0,0 +1,37 @@ +

123. Best Time to Buy and Sell Stock III

Hard


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete at most two transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [3,3,5,0,0,3,1,4]
+Output: 6
+Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
+ +

Example 2:

+ +
Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e. max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.cpp b/0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.cpp new file mode 100644 index 00000000..d3c8220d --- /dev/null +++ b/0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int ans = INT_MIN; + + int helper(TreeNode* root) + { + if(!root) + return 0; + int left = helper(root->left); + int right = helper(root->right); + + ans = max(ans,left + right + root->val); + return max({root->val + left, root->val + right, 0}); + + } + + int maxPathSum(TreeNode* root) { + + helper(root); + return ans; + + } +}; \ No newline at end of file diff --git a/0124-binary-tree-maximum-path-sum/NOTES.md b/0124-binary-tree-maximum-path-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0124-binary-tree-maximum-path-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0126-word-ladder-ii/0126-word-ladder-ii.cpp b/0126-word-ladder-ii/0126-word-ladder-ii.cpp new file mode 100644 index 00000000..22500a2c --- /dev/null +++ b/0126-word-ladder-ii/0126-word-ladder-ii.cpp @@ -0,0 +1,108 @@ +class Solution { + +private: + + void dfs(string word, vector& seq) + { + if(word == start) + { + reverse(seq.begin(), seq.end()); + + ans.push_back(seq); + + reverse(seq.begin(), seq.end()); + + return; + } + + int steps = mp[word]; + + for(int i = 0; i < word.size(); ++i) + { + char orignal = word[i]; + + for(char ch = 'a'; ch <= 'z'; ++ch) + { + word[i] = ch; + + if(mp.find(word) != mp.end() and mp[word] + 1 == steps) + { + seq.push_back(word); + + dfs(word, seq); + + seq.pop_back(); + } + } + + word[i] = orignal; + } + } + + +public: + + unordered_map mp; + vector> ans; + string start; + + vector> findLadders(string beginWord, string endWord, vector& wordList) { + + start = beginWord; + + unordered_set s(wordList.begin(), wordList.end()); + + queue q; + + q.push({beginWord}); + + mp[beginWord] = 1; + + s.erase(beginWord); + + while(!q.empty()) + { + string curr = q.front(); + + int steps = mp[curr]; + + q.pop(); + + if(curr == endWord) + break; + + for(int i = 0; i < curr.size(); ++i) + { + char orignal = curr[i]; + + for(char ch = 'a'; ch <= 'z'; ++ch) + { + curr[i] = ch; + + if(s.count(curr)) + { + q.push(curr); + + s.erase(curr); + + mp[curr] = steps + 1; + } + } + + curr[i] = orignal; + } + } + + if(mp.find(endWord) != mp.end()) + { + vector seq; + + seq.push_back(endWord); + + dfs(endWord, seq); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0126-word-ladder-ii/README.md b/0126-word-ladder-ii/README.md new file mode 100644 index 00000000..35e3785c --- /dev/null +++ b/0126-word-ladder-ii/README.md @@ -0,0 +1,41 @@ +

126. Word Ladder II

Hard


A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

+ +

 

+

Example 1:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
+Explanation: There are 2 shortest transformation sequences:
+"hit" -> "hot" -> "dot" -> "dog" -> "cog"
+"hit" -> "hot" -> "lot" -> "log" -> "cog"
+
+ +

Example 2:

+ +
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: []
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 5
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 500
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
  • The sum of all shortest transformation sequences does not exceed 105.
  • +
+
\ No newline at end of file diff --git a/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.cpp b/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.cpp new file mode 100644 index 00000000..92f0a4e5 --- /dev/null +++ b/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + + unordered_set st(nums.begin(),nums.end()); + + int ans = 0, n = nums.size(); + + for(int i = 0; i < n; ++i) + { + if(!st.count(nums[i] - 1)) + { + int curr = 1; + int var = nums[i]; + while(st.count(var+1)) + { + ++var; + ++curr; + } + ans = max(ans,curr); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0128-longest-consecutive-sequence/NOTES.md b/0128-longest-consecutive-sequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0128-longest-consecutive-sequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0128-longest-consecutive-sequence/README.md b/0128-longest-consecutive-sequence/README.md new file mode 100644 index 00000000..2938c99d --- /dev/null +++ b/0128-longest-consecutive-sequence/README.md @@ -0,0 +1,26 @@ +

128. Longest Consecutive Sequence

Medium


Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

+ +

You must write an algorithm that runs in O(n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [100,4,200,1,3,2]
+Output: 4
+Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
+
+ +

Example 2:

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

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0129-sum-root-to-leaf-numbers/0129-sum-root-to-leaf-numbers.cpp b/0129-sum-root-to-leaf-numbers/0129-sum-root-to-leaf-numbers.cpp new file mode 100644 index 00000000..9e2a5664 --- /dev/null +++ b/0129-sum-root-to-leaf-numbers/0129-sum-root-to-leaf-numbers.cpp @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + + void sumToLeaf(TreeNode* root, int val, int&res) + { + if(!root) + return; + int curr = val * 10 + root->val; + + if(!root->left and !root->right) + res += curr; + + sumToLeaf(root->left,curr, res); + sumToLeaf(root->right,curr,res); + } + + int sumNumbers(TreeNode* root) { + + if(!root) + return 0; + + int res = 0; + + sumToLeaf(root,0,res); + + return res; + + } +}; \ No newline at end of file diff --git a/0129-sum-root-to-leaf-numbers/NOTES.md b/0129-sum-root-to-leaf-numbers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0129-sum-root-to-leaf-numbers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0129-sum-root-to-leaf-numbers/README.md b/0129-sum-root-to-leaf-numbers/README.md new file mode 100644 index 00000000..abefe7fb --- /dev/null +++ b/0129-sum-root-to-leaf-numbers/README.md @@ -0,0 +1,43 @@ +

129. Sum Root to Leaf Numbers

Medium


You are given the root of a binary tree containing digits from 0 to 9 only.

+ +

Each root-to-leaf path in the tree represents a number.

+ +
    +
  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
  • +
+ +

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

+ +

A leaf node is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3]
+Output: 25
+Explanation:
+The root-to-leaf path 1->2 represents the number 12.
+The root-to-leaf path 1->3 represents the number 13.
+Therefore, sum = 12 + 13 = 25.
+
+ +

Example 2:

+ +
Input: root = [4,9,0,5,1]
+Output: 1026
+Explanation:
+The root-to-leaf path 4->9->5 represents the number 495.
+The root-to-leaf path 4->9->1 represents the number 491.
+The root-to-leaf path 4->0 represents the number 40.
+Therefore, sum = 495 + 491 + 40 = 1026.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 9
  • +
  • The depth of the tree will not exceed 10.
  • +
+
\ No newline at end of file diff --git a/0130-surrounded-regions/0130-surrounded-regions.cpp b/0130-surrounded-regions/0130-surrounded-regions.cpp new file mode 100644 index 00000000..6a28517b --- /dev/null +++ b/0130-surrounded-regions/0130-surrounded-regions.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + + void dfs(int x , int y, int n, int m, vector>& visited, vector>& board, vector& dx, vector& dy) + { + visited[x][y] = true; + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and !visited[newx][newy] and board[newx][newy] == 'O') + dfs(newx, newy, n, m, visited, board, dx, dy); + } + } + + + void solve(vector>& board) { + + int n = board.size(); + int m = board[0].size(); + + vector> visited(n, vector(m, false)); + + vector dx = {-1,0,0,+1}; + vector dy = {0,-1,+1,0}; + + for(int i = 0; i < n; ++i) + { + if(!visited[i][0] and board[i][0] == 'O') + dfs(i, 0, n, m, visited, board, dx, dy); + + if(!visited[i][m-1] and board[i][m-1] == 'O') + dfs(i, m-1, n, m, visited, board, dx, dy); + } + + for(int j = 0; j < m; ++j) + { + if(!visited[0][j] and board[0][j] == 'O') + dfs(0, j, n, m , visited, board, dx, dy); + if(!visited[n-1][j] and board[n-1][j] == 'O') + dfs(n-1, j, n, m, visited, board, dx, dy); + } + + for(int i = 0 ; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(!visited[i][j] and board[i][j] == 'O') + board[i][j] = 'X'; + } + } + + } +}; \ No newline at end of file diff --git a/0130-surrounded-regions/README.md b/0130-surrounded-regions/README.md new file mode 100644 index 00000000..335f1f77 --- /dev/null +++ b/0130-surrounded-regions/README.md @@ -0,0 +1,32 @@ +

130. Surrounded Regions

Medium


Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

+ +

A region is captured by flipping all 'O's into 'X's in that surrounded region.

+ +

 

+

Example 1:

+ +
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
+Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
+Explanation: Notice that an 'O' should not be flipped if:
+- It is on the border, or
+- It is adjacent to an 'O' that should not be flipped.
+The bottom 'O' is on the border, so it is not flipped.
+The other three 'O' form a surrounded region, so they are flipped.
+
+ +

Example 2:

+ +
Input: board = [["X"]]
+Output: [["X"]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • board[i][j] is 'X' or 'O'.
  • +
+
\ No newline at end of file diff --git a/0131-palindrome-partitioning/0131-palindrome-partitioning.cpp b/0131-palindrome-partitioning/0131-palindrome-partitioning.cpp new file mode 100644 index 00000000..1087d98c --- /dev/null +++ b/0131-palindrome-partitioning/0131-palindrome-partitioning.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + + + bool isPalindrome(int start, int end, string& str) + { + while(start <= end) + { + if(str[start] != str[end]) + return false; + ++start,--end; + } + return true; + } + + void helper(int idx, vector ds, vector>& res, string& s) + { + if(idx == s.size()) + { + res.push_back(ds); + return; + } + + for(int i = idx; i < s.size(); ++i) + { + if(isPalindrome(idx,i,s)){ + // cout<> partition(string s) { + + vector ds; + vector> res; + + helper(0,ds,res,s); + + return res; + + } +}; \ No newline at end of file diff --git a/0131-palindrome-partitioning/NOTES.md b/0131-palindrome-partitioning/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0131-palindrome-partitioning/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0131-palindrome-partitioning/README.md b/0131-palindrome-partitioning/README.md new file mode 100644 index 00000000..93474224 --- /dev/null +++ b/0131-palindrome-partitioning/README.md @@ -0,0 +1,18 @@ +

131. Palindrome Partitioning

Medium


Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

+ +

 

+

Example 1:

+
Input: s = "aab"
+Output: [["a","a","b"],["aa","b"]]
+

Example 2:

+
Input: s = "a"
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 16
  • +
  • s contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0132-palindrome-partitioning-ii/0132-palindrome-partitioning-ii.cpp b/0132-palindrome-partitioning-ii/0132-palindrome-partitioning-ii.cpp new file mode 100644 index 00000000..49eea343 --- /dev/null +++ b/0132-palindrome-partitioning-ii/0132-palindrome-partitioning-ii.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + + bool isPalindrome(int start, int end, string& s) + { + while(start <= end) + { + if(s[start] != s[end]) + return false; + ++start, --end; + } + return true; + } + + int helper(int idx, string& s,vector& dp) + { + if(idx == s.size()) + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int ans = INT_MAX; + for(int i =idx ; i < s.size(); ++i) + { + if(isPalindrome(idx, i, s)) + { + int cost = 1 + helper(i+1,s,dp); + ans = min(ans,cost); + } + } + return dp[idx] = ans; + } + + int minCut(string s) { + + int n = s.size(); + + // vector dp(n+1,-1); + + // return helper(0,s,dp) - 1; + + vector dp(n+1,0); + + for(int idx = n-1; idx>=0 ; --idx) + { + int ans = INT_MAX; + for(int i =idx ; i < n; ++i) + { + if(isPalindrome(idx, i, s)) + { + int cost = 1 + dp[i+1]; + ans = min(ans,cost); + } + } + dp[idx] = ans; + } + + return dp[0] - 1; + } +}; \ No newline at end of file diff --git a/0132-palindrome-partitioning-ii/NOTES.md b/0132-palindrome-partitioning-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0132-palindrome-partitioning-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0132-palindrome-partitioning-ii/README.md b/0132-palindrome-partitioning-ii/README.md new file mode 100644 index 00000000..9bdf229a --- /dev/null +++ b/0132-palindrome-partitioning-ii/README.md @@ -0,0 +1,32 @@ +

132. Palindrome Partitioning II

Hard


Given a string s, partition s such that every substring of the partition is a palindrome.

+ +

Return the minimum cuts needed for a palindrome partitioning of s.

+ +

 

+

Example 1:

+ +
Input: s = "aab"
+Output: 1
+Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
+
+ +

Example 2:

+ +
Input: s = "a"
+Output: 0
+
+ +

Example 3:

+ +
Input: s = "ab"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2000
  • +
  • s consists of lowercase English letters only.
  • +
+
\ No newline at end of file diff --git a/0133-clone-graph/0133-clone-graph.cpp b/0133-clone-graph/0133-clone-graph.cpp new file mode 100644 index 00000000..17422d11 --- /dev/null +++ b/0133-clone-graph/0133-clone-graph.cpp @@ -0,0 +1,57 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; +*/ + +class Solution { + +private: + Node* clone(Node* node, unordered_map& mp) + { + Node* newNode = new Node(node->val); + mp.insert({node->val, newNode}); + + for(auto& itr : node->neighbors) + { + if(mp.find(itr->val) == mp.end()) + { + Node* cloneNode = clone(itr, mp); + newNode->neighbors.push_back(cloneNode); + } + else + { + newNode->neighbors.push_back(mp[itr->val]); + } + } + + return newNode; + } + +public: + Node* cloneGraph(Node* node) { + + if(!node) + return nullptr; + + unordered_map mp; + + return clone(node, mp); + + } +}; \ No newline at end of file diff --git a/0133-clone-graph/NOTES.md b/0133-clone-graph/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0133-clone-graph/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0133-clone-graph/README.md b/0133-clone-graph/README.md new file mode 100644 index 00000000..8bfc4689 --- /dev/null +++ b/0133-clone-graph/README.md @@ -0,0 +1,59 @@ +

133. Clone Graph

Medium


Given a reference of a node in a connected undirected graph.

+ +

Return a deep copy (clone) of the graph.

+ +

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

+ +
class Node {
+    public int val;
+    public List<Node> neighbors;
+}
+
+ +

 

+ +

Test case format:

+ +

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

+ +

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

+ +

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

+ +

 

+

Example 1:

+ +
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
+Output: [[2,4],[1,3],[2,4],[1,3]]
+Explanation: There are 4 nodes in the graph.
+1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+
+ +

Example 2:

+ +
Input: adjList = [[]]
+Output: [[]]
+Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
+
+ +

Example 3:

+ +
Input: adjList = []
+Output: []
+Explanation: This an empty graph, it does not have any nodes.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the graph is in the range [0, 100].
  • +
  • 1 <= Node.val <= 100
  • +
  • Node.val is unique for each node.
  • +
  • There are no repeated edges and no self-loops in the graph.
  • +
  • The Graph is connected and all nodes can be visited starting from the given node.
  • +
+
\ No newline at end of file diff --git a/0134-gas-station/0134-gas-station.cpp b/0134-gas-station/0134-gas-station.cpp new file mode 100644 index 00000000..7c9cd4f4 --- /dev/null +++ b/0134-gas-station/0134-gas-station.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + + int n = gas.size(); + int total_surplus = 0; + int surplus = 0; + int start = 0; + + for(int i = 0; i < n; i++){ + total_surplus += gas[i] - cost[i]; + surplus += gas[i] - cost[i]; + if(surplus < 0){ + surplus = 0; + start = i + 1; + } + } + return (total_surplus < 0) ? -1 : start; + + } +}; \ No newline at end of file diff --git a/0134-gas-station/README.md b/0134-gas-station/README.md new file mode 100644 index 00000000..24e2f2e5 --- /dev/null +++ b/0134-gas-station/README.md @@ -0,0 +1,43 @@ +

134. Gas Station

Medium


There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

+ +

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

+ +

Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

+ +

 

+

Example 1:

+ +
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
+Output: 3
+Explanation:
+Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 4. Your tank = 4 - 1 + 5 = 8
+Travel to station 0. Your tank = 8 - 2 + 1 = 7
+Travel to station 1. Your tank = 7 - 3 + 2 = 6
+Travel to station 2. Your tank = 6 - 4 + 3 = 5
+Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
+Therefore, return 3 as the starting index.
+
+ +

Example 2:

+ +
Input: gas = [2,3,4], cost = [3,4,3]
+Output: -1
+Explanation:
+You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
+Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 0. Your tank = 4 - 3 + 2 = 3
+Travel to station 1. Your tank = 3 - 3 + 3 = 3
+You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
+Therefore, you can't travel around the circuit once no matter where you start.
+
+ +

 

+

Constraints:

+ +
    +
  • n == gas.length == cost.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= gas[i], cost[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0135-candy/0135-candy.cpp b/0135-candy/0135-candy.cpp new file mode 100644 index 00000000..941d332d --- /dev/null +++ b/0135-candy/0135-candy.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int candy(vector& ratings) { + + int n = ratings.size(); + + int candies = n; + + int i = 1; + + while(i < n) + { + if(ratings[i] == ratings[i-1]) + { + ++i; + continue; + } + + int peak = 0; + + while(ratings[i] > ratings[i-1]) + { + + ++peak; + candies += peak; + + ++i; + + if(i == n) + return candies; + } + + int dip = 0; + + while(i < n and ratings[i] < ratings[i-1]) + { + ++dip; + candies += dip; + + ++i; + } + + candies -= min(peak, dip); + } + + return candies; + } +}; \ No newline at end of file diff --git a/0135-candy/NOTES.md b/0135-candy/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0135-candy/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0135-candy/README.md b/0135-candy/README.md new file mode 100644 index 00000000..71c49dd1 --- /dev/null +++ b/0135-candy/README.md @@ -0,0 +1,36 @@ +

135. Candy

Hard


There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

+ +

You are giving candies to these children subjected to the following requirements:

+ +
    +
  • Each child must have at least one candy.
  • +
  • Children with a higher rating get more candies than their neighbors.
  • +
+ +

Return the minimum number of candies you need to have to distribute the candies to the children.

+ +

 

+

Example 1:

+ +
Input: ratings = [1,0,2]
+Output: 5
+Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
+
+ +

Example 2:

+ +
Input: ratings = [1,2,2]
+Output: 4
+Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
+The third child gets 1 candy because it satisfies the above two conditions.
+
+ +

 

+

Constraints:

+ +
    +
  • n == ratings.length
  • +
  • 1 <= n <= 2 * 104
  • +
  • 0 <= ratings[i] <= 2 * 104
  • +
+
\ No newline at end of file diff --git a/0137-single-number-ii/0137-single-number-ii.cpp b/0137-single-number-ii/0137-single-number-ii.cpp new file mode 100644 index 00000000..a173bb54 --- /dev/null +++ b/0137-single-number-ii/0137-single-number-ii.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int singleNumber(vector& nums) { + + int ones = 0, twos = 0; + + for(auto itr : nums) + { + ones = (ones ^ itr) & (~twos); + twos = (twos ^ itr) & (~ones); + } + + return ones; + + } +}; \ No newline at end of file diff --git a/0137-single-number-ii/NOTES.md b/0137-single-number-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0137-single-number-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0137-single-number-ii/README.md b/0137-single-number-ii/README.md new file mode 100644 index 00000000..72a3e4fe --- /dev/null +++ b/0137-single-number-ii/README.md @@ -0,0 +1,21 @@ +

137. Single Number II

Medium


Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [2,2,3,2]
+Output: 3
+

Example 2:

+
Input: nums = [0,1,0,1,0,1,99]
+Output: 99
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • Each element in nums appears exactly three times except for one element which appears once.
  • +
+
\ No newline at end of file diff --git a/0138-copy-list-with-random-pointer/0138-copy-list-with-random-pointer.cpp b/0138-copy-list-with-random-pointer/0138-copy-list-with-random-pointer.cpp new file mode 100644 index 00000000..74aadc20 --- /dev/null +++ b/0138-copy-list-with-random-pointer/0138-copy-list-with-random-pointer.cpp @@ -0,0 +1,57 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + + if(!head) + return nullptr; + + Node*temp = head; + + while(temp) + { + Node* newNode = new Node(temp->val); + newNode->next = temp->next; + temp->next = newNode; + temp = newNode->next; + } + + temp = head; + + while(temp) + { + temp->next->random = (temp->random ? temp->random->next : nullptr); + temp = temp->next->next; + } + + temp = head; + Node* ans = temp->next, *ptr = temp->next; + + while(temp) + { + temp->next = ptr->next; + temp = temp->next; + if(!temp) + break; + ptr->next = temp->next; + ptr = ptr->next; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0138-copy-list-with-random-pointer/NOTES.md b/0138-copy-list-with-random-pointer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0138-copy-list-with-random-pointer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0138-copy-list-with-random-pointer/README.md b/0138-copy-list-with-random-pointer/README.md new file mode 100644 index 00000000..687b9dab --- /dev/null +++ b/0138-copy-list-with-random-pointer/README.md @@ -0,0 +1,47 @@ +

138. Copy List with Random Pointer

Medium


A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

+ +

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

+ +

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

+ +

Return the head of the copied linked list.

+ +

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

+ +
    +
  • val: an integer representing Node.val
  • +
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
  • +
+ +

Your code will only be given the head of the original linked list.

+ +

 

+

Example 1:

+ +
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
+Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
+
+ +

Example 2:

+ +
Input: head = [[1,1],[2,1]]
+Output: [[1,1],[2,1]]
+
+ +

Example 3:

+ +

+ +
Input: head = [[3,null],[3,0],[3,null]]
+Output: [[3,null],[3,0],[3,null]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 1000
  • +
  • -104 <= Node.val <= 104
  • +
  • Node.random is null or is pointing to some node in the linked list.
  • +
+
\ No newline at end of file diff --git a/0139-word-break/0139-word-break.cpp b/0139-word-break/0139-word-break.cpp new file mode 100644 index 00000000..acc5ffee --- /dev/null +++ b/0139-word-break/0139-word-break.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + + unordered_set used(wordDict.begin(), wordDict.end()); + + int n = s.size(); + + vector dp(n+1, 0); + + for(int i = 0; i < n; ++i) + { + string temp; + for(int j = i; j < n; ++j) + { + temp += s[j]; + + if(used.find(temp) != used.end()) + { + if(i > 0) + { + if(dp[i-1]) + dp[j] = 1; + } + else + dp[j] = 1; + } + } + } + + return dp[n-1]; + } +}; \ No newline at end of file diff --git a/0139-word-break/NOTES.md b/0139-word-break/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0139-word-break/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0139-word-break/README.md b/0139-word-break/README.md new file mode 100644 index 00000000..2b78319b --- /dev/null +++ b/0139-word-break/README.md @@ -0,0 +1,37 @@ +

139. Word Break

Medium


Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

+ +

Note that the same word in the dictionary may be reused multiple times in the segmentation.

+ +

 

+

Example 1:

+ +
Input: s = "leetcode", wordDict = ["leet","code"]
+Output: true
+Explanation: Return true because "leetcode" can be segmented as "leet code".
+
+ +

Example 2:

+ +
Input: s = "applepenapple", wordDict = ["apple","pen"]
+Output: true
+Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
+Note that you are allowed to reuse a dictionary word.
+
+ +

Example 3:

+ +
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 300
  • +
  • 1 <= wordDict.length <= 1000
  • +
  • 1 <= wordDict[i].length <= 20
  • +
  • s and wordDict[i] consist of only lowercase English letters.
  • +
  • All the strings of wordDict are unique.
  • +
+
\ No newline at end of file diff --git a/0141-linked-list-cycle/0141-linked-list-cycle.cpp b/0141-linked-list-cycle/0141-linked-list-cycle.cpp new file mode 100644 index 00000000..3518a123 --- /dev/null +++ b/0141-linked-list-cycle/0141-linked-list-cycle.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + + ListNode* slow = head, *fast = head; + + while(fast and fast->next) + { + slow = slow->next; + fast = fast->next->next; + if(fast == slow) + return true; + } + + return false; + + } +}; \ No newline at end of file diff --git a/0141-linked-list-cycle/NOTES.md b/0141-linked-list-cycle/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0141-linked-list-cycle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0141-linked-list-cycle/README.md b/0141-linked-list-cycle/README.md new file mode 100644 index 00000000..2621bdae --- /dev/null +++ b/0141-linked-list-cycle/README.md @@ -0,0 +1,40 @@ +

141. Linked List Cycle

Easy


Given head, the head of a linked list, determine if the linked list has a cycle in it.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

+ +

Return true if there is a cycle in the linked list. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: false
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.cpp b/0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.cpp new file mode 100644 index 00000000..bedac9a0 --- /dev/null +++ b/0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.cpp @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + if(head == NULL || head -> next == NULL) + return NULL; + ListNode *slow = head,*fast = head, *temp = head; + + while(fast != NULL && fast -> next != NULL) + { + slow = slow -> next; + fast = fast -> next -> next; + + if(fast == slow) //cycle || loop + { + while(slow != temp) + { + slow = slow -> next; + temp = temp -> next; + } + return temp ; + } + + } + + + return NULL; + } +}; \ No newline at end of file diff --git a/0142-linked-list-cycle-ii/NOTES.md b/0142-linked-list-cycle-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0142-linked-list-cycle-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0142-linked-list-cycle-ii/README.md b/0142-linked-list-cycle-ii/README.md new file mode 100644 index 00000000..50b0fd7c --- /dev/null +++ b/0142-linked-list-cycle-ii/README.md @@ -0,0 +1,40 @@ +

142. Linked List Cycle II

Medium


Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

+ +

Do not modify the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [3,2,0,-4], pos = 1
+Output: tail connects to node index 1
+Explanation: There is a cycle in the linked list, where tail connects to the second node.
+
+ +

Example 2:

+ +
Input: head = [1,2], pos = 0
+Output: tail connects to node index 0
+Explanation: There is a cycle in the linked list, where tail connects to the first node.
+
+ +

Example 3:

+ +
Input: head = [1], pos = -1
+Output: no cycle
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+
\ No newline at end of file diff --git a/0143-reorder-list/0143-reorder-list.cpp b/0143-reorder-list/0143-reorder-list.cpp new file mode 100644 index 00000000..1795ab34 --- /dev/null +++ b/0143-reorder-list/0143-reorder-list.cpp @@ -0,0 +1,50 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + + if(!head or !head->next) + return; + + ListNode* slow = head, *fast = head, *first = nullptr; + + while(fast and fast->next) + { + first = slow; + slow = slow->next; + fast = fast->next->next; + } + + first->next = nullptr; + + ListNode* prev = nullptr; + + while(slow) + { + ListNode* nex = slow->next; + slow->next = prev; + prev = slow; + slow = nex; + } + + while(head) + { + ListNode* nex = head->next; + head->next = prev; + ListNode* nex2 = prev->next; + if(nex) + prev->next = nex; + head = nex; + prev = nex2; + } + } +}; \ No newline at end of file diff --git a/0143-reorder-list/README.md b/0143-reorder-list/README.md new file mode 100644 index 00000000..fa1bf802 --- /dev/null +++ b/0143-reorder-list/README.md @@ -0,0 +1,33 @@ +

143. Reorder List

Medium


You are given the head of a singly linked-list. The list can be represented as:

+ +
L0 → L1 → … → Ln - 1 → Ln
+
+ +

Reorder the list to be on the following form:

+ +
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
+
+ +

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4]
+Output: [1,4,2,3]
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5]
+Output: [1,5,2,4,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5 * 104].
  • +
  • 1 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.cpp b/0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.cpp new file mode 100644 index 00000000..1ecc542d --- /dev/null +++ b/0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + + vector ans; + stack st; + + while(root or !st.empty()) + { + if(root) + { + ans.push_back(root->val); + if(root->right) + { + st.push(root->right); + } + + root = root->left; + } + else + { + root = st.top(); + st.pop(); + } + } + return ans; + } +}; diff --git a/0144-binary-tree-preorder-traversal/NOTES.md b/0144-binary-tree-preorder-traversal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0144-binary-tree-preorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0144-binary-tree-preorder-traversal/README.md b/0144-binary-tree-preorder-traversal/README.md new file mode 100644 index 00000000..320ded4b --- /dev/null +++ b/0144-binary-tree-preorder-traversal/README.md @@ -0,0 +1,32 @@ +

144. Binary Tree Preorder Traversal

Easy


Given the root of a binary tree, return the preorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,2,3]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+
\ No newline at end of file diff --git a/0145-binary-tree-postorder-traversal/0145-binary-tree-postorder-traversal.cpp b/0145-binary-tree-postorder-traversal/0145-binary-tree-postorder-traversal.cpp new file mode 100644 index 00000000..e4ed9970 --- /dev/null +++ b/0145-binary-tree-postorder-traversal/0145-binary-tree-postorder-traversal.cpp @@ -0,0 +1,60 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + + vector ans; + + if(!root) + return ans; + + stack st; + + TreeNode* prev = root; + + while(prev != nullptr or !st.empty()) + { + if(prev) + { + st.push(prev); + prev = prev->left; + } + else + { + TreeNode* temp = st.top()->right; + + if(temp == nullptr) + { + temp = st.top(); + + st.pop(); + + ans.push_back(temp->val); + + while(!st.empty() and st.top()->right == temp) + { + temp = st.top(); + + st.pop(); + + ans.push_back(temp->val); + } + } + else + prev = temp; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0145-binary-tree-postorder-traversal/NOTES.md b/0145-binary-tree-postorder-traversal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0145-binary-tree-postorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0145-binary-tree-postorder-traversal/README.md b/0145-binary-tree-postorder-traversal/README.md new file mode 100644 index 00000000..ed52ab88 --- /dev/null +++ b/0145-binary-tree-postorder-traversal/README.md @@ -0,0 +1,31 @@ +

145. Binary Tree Postorder Traversal

Easy


Given the root of a binary tree, return the postorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [3,2,1]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively?
\ No newline at end of file diff --git a/0146-lru-cache/0146-lru-cache.cpp b/0146-lru-cache/0146-lru-cache.cpp new file mode 100644 index 00000000..714960b4 --- /dev/null +++ b/0146-lru-cache/0146-lru-cache.cpp @@ -0,0 +1,93 @@ +class LRUCache { +public: + + class Node{ + public: + int key, val; + Node *prev, *next; + + Node(int k, int v) + { + this->key = k; + this->val = v; + } + }; + + int cap; + Node* head = new Node(-1,-1); + Node* tail = new Node(-1,-1); + + unordered_map mp; + + void addNode(Node* ptr) + { + Node* temp = head->next; + head->next = ptr; + ptr->next = temp; + ptr->prev = head; + temp->prev = ptr; + } + + void deleteNode(Node* ptr) + { + Node *ptrPrev = ptr->prev; + Node *ptrNext = ptr->next; + + ptrNext->prev = ptrPrev; + ptrPrev->next = ptrNext; + + delete(ptr); + } + + LRUCache(int capacity) { + cap = capacity; + head->next = tail; + tail->prev = head; + } + + int get(int key) { + + if(mp.find(key) != mp.end()) + { + Node* existing = mp[key]; + int value = existing->val; + mp.erase(key); + deleteNode(existing); + addNode(new Node(key, value)); + mp[key] = head->next; + return value; + } + + return -1; + + } + + void put(int key, int value) { + + if(mp.find(key) != mp.end()) + { + Node* existing = mp[key]; + mp.erase(key); + deleteNode(existing); + } + + if(cap == mp.size()) + { + Node* existing = tail->prev; + mp.erase(existing->key); + deleteNode(existing); + } + + addNode(new Node(key, value)); + + mp[key] = head->next; + + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ \ No newline at end of file diff --git a/0146-lru-cache/NOTES.md b/0146-lru-cache/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0146-lru-cache/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0146-lru-cache/README.md b/0146-lru-cache/README.md new file mode 100644 index 00000000..ae892bc0 --- /dev/null +++ b/0146-lru-cache/README.md @@ -0,0 +1,44 @@ +

146. LRU Cache

Medium


Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

+ +

Implement the LRUCache class:

+ +
    +
  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • +
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • +
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
  • +
+ +

The functions get and put must each run in O(1) average time complexity.

+ +

 

+

Example 1:

+ +
Input
+["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
+[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
+Output
+[null, null, null, 1, null, -1, null, -1, 3, 4]
+
+Explanation
+LRUCache lRUCache = new LRUCache(2);
+lRUCache.put(1, 1); // cache is {1=1}
+lRUCache.put(2, 2); // cache is {1=1, 2=2}
+lRUCache.get(1);    // return 1
+lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
+lRUCache.get(2);    // returns -1 (not found)
+lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
+lRUCache.get(1);    // return -1 (not found)
+lRUCache.get(3);    // return 3
+lRUCache.get(4);    // return 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= capacity <= 3000
  • +
  • 0 <= key <= 104
  • +
  • 0 <= value <= 105
  • +
  • At most 2 * 105 calls will be made to get and put.
  • +
+
\ No newline at end of file diff --git a/0148-sort-list/0148-sort-list.cpp b/0148-sort-list/0148-sort-list.cpp new file mode 100644 index 00000000..65a81cfc --- /dev/null +++ b/0148-sort-list/0148-sort-list.cpp @@ -0,0 +1,55 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + ListNode* merge(ListNode* l1, ListNode* l2) + { + if(!l1) + return l2; + + if(!l2) + return l1; + + if(l1->val < l2->val) + { + l1->next = merge(l1->next, l2); + return l1; + } + else + { + l2->next = merge(l1, l2->next); + return l2; + } + } + + ListNode* sortList(ListNode* head) { + + if(!head or !head->next) + return head; + + ListNode* slow = head, *fast = head, *prev = nullptr; + + while(fast and fast->next) + { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + prev->next = nullptr; + + ListNode* l1 = sortList(head); + ListNode* l2 = sortList(slow); + + return merge(l1, l2); + } +}; \ No newline at end of file diff --git a/0148-sort-list/README.md b/0148-sort-list/README.md new file mode 100644 index 00000000..e56bc9c9 --- /dev/null +++ b/0148-sort-list/README.md @@ -0,0 +1,32 @@ +

148. Sort List

Medium


Given the head of a linked list, return the list after sorting it in ascending order.

+ +

 

+

Example 1:

+ +
Input: head = [4,2,1,3]
+Output: [1,2,3,4]
+
+ +

Example 2:

+ +
Input: head = [-1,5,3,4,0]
+Output: [-1,0,3,4,5]
+
+ +

Example 3:

+ +
Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 5 * 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ +

 

+

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

+
\ No newline at end of file diff --git a/0149-max-points-on-a-line/0149-max-points-on-a-line.cpp b/0149-max-points-on-a-line/0149-max-points-on-a-line.cpp new file mode 100644 index 00000000..e7eb68dc --- /dev/null +++ b/0149-max-points-on-a-line/0149-max-points-on-a-line.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int maxPoints(vector>& points) { + + int n = points.size(); + + int ans = 1; + + for(int i = 0; i mp; + for(int j = i + 1; j149. Max Points on a Line

Hard


Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

+ +

 

+

Example 1:

+ +
Input: points = [[1,1],[2,2],[3,3]]
+Output: 3
+
+ +

Example 2:

+ +
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= points.length <= 300
  • +
  • points[i].length == 2
  • +
  • -104 <= xi, yi <= 104
  • +
  • All the points are unique.
  • +
+
\ No newline at end of file diff --git a/0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.cpp b/0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.cpp new file mode 100644 index 00000000..3f8839b1 --- /dev/null +++ b/0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int evalRPN(vector& tokens) { + stack st; + for(auto itr : tokens) + { + if(itr == "+" or itr == "-" or itr == "*" or itr == "/") + { + int a = st.top(); + st.pop(); + int b = st.top(); + st.pop(); + if(itr == "+") + a = b + a; + if(itr == "-") + a = b - a; + if(itr == "*") + a = (long long)b * a; + if(itr == "/") + a = b / a; + st.push(a); + } + else + st.push(stoi(itr)); + } + return st.top(); + } +}; + + diff --git a/0150-evaluate-reverse-polish-notation/NOTES.md b/0150-evaluate-reverse-polish-notation/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0150-evaluate-reverse-polish-notation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0150-evaluate-reverse-polish-notation/README.md b/0150-evaluate-reverse-polish-notation/README.md new file mode 100644 index 00000000..1cde875c --- /dev/null +++ b/0150-evaluate-reverse-polish-notation/README.md @@ -0,0 +1,44 @@ +

150. Evaluate Reverse Polish Notation

Medium


Evaluate the value of an arithmetic expression in Reverse Polish Notation.

+ +

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

+ +

Note that division between two integers should truncate toward zero.

+ +

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

+ +

 

+

Example 1:

+ +
Input: tokens = ["2","1","+","3","*"]
+Output: 9
+Explanation: ((2 + 1) * 3) = 9
+
+ +

Example 2:

+ +
Input: tokens = ["4","13","5","/","+"]
+Output: 6
+Explanation: (4 + (13 / 5)) = 6
+
+ +

Example 3:

+ +
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
+Output: 22
+Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
+= ((10 * (6 / (12 * -11))) + 17) + 5
+= ((10 * (6 / -132)) + 17) + 5
+= ((10 * 0) + 17) + 5
+= (0 + 17) + 5
+= 17 + 5
+= 22
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tokens.length <= 104
  • +
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
  • +
+
\ No newline at end of file diff --git a/0152-maximum-product-subarray/0152-maximum-product-subarray.cpp b/0152-maximum-product-subarray/0152-maximum-product-subarray.cpp new file mode 100644 index 00000000..5833f4c2 --- /dev/null +++ b/0152-maximum-product-subarray/0152-maximum-product-subarray.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxProduct(vector& nums) { + + int n = nums.size(); + + int overall_max = INT_MIN; + + int pref = 1, suff = 1; + + for(int i = 0; i < n; ++i) + { + if(pref == 0) + pref = 1; + if(suff == 0) + suff = 1; + + pref *= nums[i]; + suff *= nums[n-i-1]; + + overall_max = max({overall_max, pref, suff}); + } + + return overall_max; + } +}; \ No newline at end of file diff --git a/0152-maximum-product-subarray/NOTES.md b/0152-maximum-product-subarray/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0152-maximum-product-subarray/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0152-maximum-product-subarray/README.md b/0152-maximum-product-subarray/README.md new file mode 100644 index 00000000..4742c655 --- /dev/null +++ b/0152-maximum-product-subarray/README.md @@ -0,0 +1,28 @@ +

152. Maximum Product Subarray

Medium


Given an integer array nums, find a subarray that has the largest product, and return the product.

+ +

The test cases are generated so that the answer will fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,-2,4]
+Output: 6
+Explanation: [2,3] has the largest product 6.
+
+ +

Example 2:

+ +
Input: nums = [-2,0,-1]
+Output: 0
+Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -10 <= nums[i] <= 10
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/0160-intersection-of-two-linked-lists/README.md b/0160-intersection-of-two-linked-lists/README.md new file mode 100644 index 00000000..bf03bc16 --- /dev/null +++ b/0160-intersection-of-two-linked-lists/README.md @@ -0,0 +1,64 @@ +

160. Intersection of Two Linked Lists

Easy


Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

+ +

For example, the following two linked lists begin to intersect at node c1:

+ +

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

+ +

Note that the linked lists must retain their original structure after the function returns.

+ +

Custom Judge:

+ +

The inputs to the judge are given as follows (your program is not given these inputs):

+ +
    +
  • intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
  • +
  • listA - The first linked list.
  • +
  • listB - The second linked list.
  • +
  • skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
  • +
  • skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
  • +
+ +

The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
+Output: Intersected at '8'
+Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
+- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
+
+ +

Example 2:

+ +
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
+Output: Intersected at '2'
+Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
+
+ +

Example 3:

+ +
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
+Output: No intersection
+Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
+Explanation: The two lists do not intersect, so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes of listA is in the m.
  • +
  • The number of nodes of listB is in the n.
  • +
  • 1 <= m, n <= 3 * 104
  • +
  • 1 <= Node.val <= 105
  • +
  • 0 <= skipA < m
  • +
  • 0 <= skipB < n
  • +
  • intersectVal is 0 if listA and listB do not intersect.
  • +
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
  • +
+ +

 

+Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?
\ No newline at end of file diff --git a/0162-find-peak-element/0162-find-peak-element.cpp b/0162-find-peak-element/0162-find-peak-element.cpp new file mode 100644 index 00000000..b9badb4f --- /dev/null +++ b/0162-find-peak-element/0162-find-peak-element.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int findPeakElement(vector& arr) { + + int n = arr.size(); + + if(n == 1) + return 0; + if(arr[0] > arr[1]) + return 0; + if(arr[n-1] > arr[n-2]) + return n-1; + + int low = 1, high = n-2; + + while(low <= high) + { + int mid = low + (high - low) / 2; + + if(arr[mid] > arr[mid+1] and arr[mid] > arr[mid-1]) + return mid; + else if(arr[mid] > arr[mid-1]) + low = mid+1; + else + high = mid-1; + } + + return -1; + } +}; \ No newline at end of file diff --git a/0162-find-peak-element/NOTES.md b/0162-find-peak-element/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0162-find-peak-element/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0162-find-peak-element/README.md b/0162-find-peak-element/README.md new file mode 100644 index 00000000..96c32bd2 --- /dev/null +++ b/0162-find-peak-element/README.md @@ -0,0 +1,30 @@ +

162. Find Peak Element

Medium


A peak element is an element that is strictly greater than its neighbors.

+ +

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

+ +

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

+ +

You must write an algorithm that runs in O(log n) time.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1]
+Output: 2
+Explanation: 3 is a peak element and your function should return the index number 2.
+ +

Example 2:

+ +
Input: nums = [1,2,1,3,5,6,4]
+Output: 5
+Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • nums[i] != nums[i + 1] for all valid i.
  • +
+
\ No newline at end of file diff --git a/0165-compare-version-numbers/0165-compare-version-numbers.cpp b/0165-compare-version-numbers/0165-compare-version-numbers.cpp new file mode 100644 index 00000000..14ab26a7 --- /dev/null +++ b/0165-compare-version-numbers/0165-compare-version-numbers.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int compareVersion(string version1, string version2) { + + int i = 0, j= 0, n1 = version1.length(), n2 = version2.length(), num1 = 0, num2 = 0; + + while(i < n1 || j < n2) + { + while(i < n1 && version1[i] != '.') + { + num1 = num1*10 + (version1[i] - '0'); + ++i; + } + while(j < n2 && version2[j] != '.') + { + num2 = num2 * 10 + (version2[j] - '0'); + ++j; + } + + + if(num1 > num2) + return 1; + + if(num1 < num2) + return -1; + + ++i, ++j; + + num1 = 0, num2 = 0; + + } + return 0; + + } +}; \ No newline at end of file diff --git a/0165-compare-version-numbers/README.md b/0165-compare-version-numbers/README.md new file mode 100644 index 00000000..2e07f72d --- /dev/null +++ b/0165-compare-version-numbers/README.md @@ -0,0 +1,49 @@ +

165. Compare Version Numbers

Medium


Given two version numbers, version1 and version2, compare them.

+ +
    +
+ +

Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

+ +

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

+ +

Return the following:

+ +
    +
  • If version1 < version2, return -1.
  • +
  • If version1 > version2, return 1.
  • +
  • Otherwise, return 0.
  • +
+ +

 

+

Example 1:

+ +
Input: version1 = "1.01", version2 = "1.001"
+Output: 0
+Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
+
+ +

Example 2:

+ +
Input: version1 = "1.0", version2 = "1.0.0"
+Output: 0
+Explanation: version1 does not specify revision 2, which means it is treated as "0".
+
+ +

Example 3:

+ +
Input: version1 = "0.1", version2 = "1.1"
+Output: -1
+Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= version1.length, version2.length <= 500
  • +
  • version1 and version2 only contain digits and '.'.
  • +
  • version1 and version2 are valid version numbers.
  • +
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.
  • +
+
\ No newline at end of file diff --git a/0168-excel-sheet-column-title/0168-excel-sheet-column-title.cpp b/0168-excel-sheet-column-title/0168-excel-sheet-column-title.cpp new file mode 100644 index 00000000..513b5d7b --- /dev/null +++ b/0168-excel-sheet-column-title/0168-excel-sheet-column-title.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string convertToTitle(int columnNumber) { + + string str; + + while(columnNumber > 0) + { + char last = 'A' + (columnNumber - 1) % 26; + + str = last + str; + + columnNumber = (columnNumber - 1) / 26; + } + + return str; + + } +}; \ No newline at end of file diff --git a/0168-excel-sheet-column-title/NOTES.md b/0168-excel-sheet-column-title/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0168-excel-sheet-column-title/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0168-excel-sheet-column-title/README.md b/0168-excel-sheet-column-title/README.md new file mode 100644 index 00000000..bc366e52 --- /dev/null +++ b/0168-excel-sheet-column-title/README.md @@ -0,0 +1,40 @@ +

168. Excel Sheet Column Title

Easy


Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

+ +

For example:

+ +
A -> 1
+B -> 2
+C -> 3
+...
+Z -> 26
+AA -> 27
+AB -> 28 
+...
+
+ +

 

+

Example 1:

+ +
Input: columnNumber = 1
+Output: "A"
+
+ +

Example 2:

+ +
Input: columnNumber = 28
+Output: "AB"
+
+ +

Example 3:

+ +
Input: columnNumber = 701
+Output: "ZY"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= columnNumber <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0169-majority-element/0169-majority-element.cpp b/0169-majority-element/0169-majority-element.cpp new file mode 100644 index 00000000..b2296cda --- /dev/null +++ b/0169-majority-element/0169-majority-element.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int majorityElement(vector& nums) { + + int cnt = 1, num1 = nums[0], n = nums.size(); + + for(int i = 1; i < n; ++i) + { + if(num1 != nums[i]) + --cnt; + else + ++cnt; + + if(cnt == 0) + { + cnt = 1; + num1 = nums[i]; + } + } + + return num1; + } +}; \ No newline at end of file diff --git a/0169-majority-element/NOTES.md b/0169-majority-element/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0169-majority-element/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0169-majority-element/README.md b/0169-majority-element/README.md new file mode 100644 index 00000000..0159f3e8 --- /dev/null +++ b/0169-majority-element/README.md @@ -0,0 +1,23 @@ +

169. Majority Element

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [3,2,3]
+Output: 3
+

Example 2:

+
Input: nums = [2,2,1,1,1,2,2]
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ +

 

+Follow-up: Could you solve the problem in linear time and in O(1) space?
\ No newline at end of file diff --git a/0189-rotate-array/0189-rotate-array.cpp b/0189-rotate-array/0189-rotate-array.cpp new file mode 100644 index 00000000..3795c8f9 --- /dev/null +++ b/0189-rotate-array/0189-rotate-array.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + void rotate(vector& nums, int k) { + + int n = nums.size(); + + k %= n; + + reverse(nums.begin(), nums.begin() + (n - k)); + + reverse(nums.begin() + (n-k), nums.end()); + + reverse(nums.begin(), nums.end()); + + } +}; \ No newline at end of file diff --git a/0189-rotate-array/NOTES.md b/0189-rotate-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0189-rotate-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0198-house-robber/0198-house-robber.cpp b/0198-house-robber/0198-house-robber.cpp new file mode 100644 index 00000000..4f8504fb --- /dev/null +++ b/0198-house-robber/0198-house-robber.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + + int helper(int index, int n, vector& nums, vector& dp) + { + if(index >= n) + return 0; + if(dp[index] != -1) + return dp[index]; + int take = nums[index] + helper(index + 2, n,nums,dp); + int notTake = helper(index+1,n, nums , dp); + + return dp[index] = max(take, notTake); + } + + int rob(vector& nums) { + + int n = nums.size(); + vector dp(n+1,0); + + dp[n-1] = nums[n-1]; + for(int i = n-2; i>=0; --i) + { + int take = 0; + if(i+1 < n) + take = nums[i] + dp[i+2]; + int notTake = dp[i+1]; + + dp[i] = max(take, notTake); + } + + return dp[0]; + } +}; \ No newline at end of file diff --git a/0198-house-robber/NOTES.md b/0198-house-robber/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0198-house-robber/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0198-house-robber/README.md b/0198-house-robber/README.md new file mode 100644 index 00000000..4784d722 --- /dev/null +++ b/0198-house-robber/README.md @@ -0,0 +1,29 @@ +

198. House Robber

Medium


You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

+ +

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1]
+Output: 4
+Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
+Total amount you can rob = 1 + 3 = 4.
+
+ +

Example 2:

+ +
Input: nums = [2,7,9,3,1]
+Output: 12
+Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
+Total amount you can rob = 2 + 9 + 1 = 12.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 400
  • +
+
\ No newline at end of file diff --git a/0200-number-of-islands/0200-number-of-islands.cpp b/0200-number-of-islands/0200-number-of-islands.cpp new file mode 100644 index 00000000..29d1a177 --- /dev/null +++ b/0200-number-of-islands/0200-number-of-islands.cpp @@ -0,0 +1,99 @@ +class DSU{ + public: + int N; + vector parent, size; + + DSU(int n) + { + N = n; + parent.resize(N); + size.resize(N, 1); + for(int i = 0; i < N; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + return u; + return parent[u] = findParent(parent[u]); + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + int numIslands(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1 ,0}; + + DSU dsu(n*m + 1); + + set ls; + + int island = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == '1') + { + ls.insert((i*m) + j); + for(int k = 0; k < 4; ++k) + { + int cx = dx[k] + i; + int cy = dy[k] + j; + + if(cx >= 0 and cy >= 0 and cx < n and cy < m and grid[cx][cy] == '1') + { + int node = (i * m) + j; + int adjNode = (cx * m) + cy; + + if(!dsu.isSame(node, adjNode)) + { + dsu.unionBySize(node, adjNode); + } + } + } + } + } + } + + for(auto& node : ls) + { + if(dsu.findParent(node) == node) + ++island; + } + + return island; + + } +}; \ No newline at end of file diff --git a/0200-number-of-islands/NOTES.md b/0200-number-of-islands/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0200-number-of-islands/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0200-number-of-islands/README.md b/0200-number-of-islands/README.md new file mode 100644 index 00000000..f0398d0f --- /dev/null +++ b/0200-number-of-islands/README.md @@ -0,0 +1,37 @@ +

200. Number of Islands

Medium


Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

+ +

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

+ +

 

+

Example 1:

+ +
Input: grid = [
+  ["1","1","1","1","0"],
+  ["1","1","0","1","0"],
+  ["1","1","0","0","0"],
+  ["0","0","0","0","0"]
+]
+Output: 1
+
+ +

Example 2:

+ +
Input: grid = [
+  ["1","1","0","0","0"],
+  ["1","1","0","0","0"],
+  ["0","0","1","0","0"],
+  ["0","0","0","1","1"]
+]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • grid[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/0201-bitwise-and-of-numbers-range/0201-bitwise-and-of-numbers-range.cpp b/0201-bitwise-and-of-numbers-range/0201-bitwise-and-of-numbers-range.cpp new file mode 100644 index 00000000..b92b413c --- /dev/null +++ b/0201-bitwise-and-of-numbers-range/0201-bitwise-and-of-numbers-range.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int rangeBitwiseAnd(int left, int right) { + + int rightShift = 0; + + while(right != left) + { + left >>= 1; + right >>= 1; + ++rightShift; + } + + return right << rightShift; + + } +}; \ No newline at end of file diff --git a/0201-bitwise-and-of-numbers-range/NOTES.md b/0201-bitwise-and-of-numbers-range/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0201-bitwise-and-of-numbers-range/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0201-bitwise-and-of-numbers-range/README.md b/0201-bitwise-and-of-numbers-range/README.md new file mode 100644 index 00000000..5a34dffc --- /dev/null +++ b/0201-bitwise-and-of-numbers-range/README.md @@ -0,0 +1,28 @@ +

201. Bitwise AND of Numbers Range

Medium


Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

+ +

 

+

Example 1:

+ +
Input: left = 5, right = 7
+Output: 4
+
+ +

Example 2:

+ +
Input: left = 0, right = 0
+Output: 0
+
+ +

Example 3:

+ +
Input: left = 1, right = 2147483647
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= left <= right <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0205-isomorphic-strings/0205-isomorphic-strings.cpp b/0205-isomorphic-strings/0205-isomorphic-strings.cpp new file mode 100644 index 00000000..cea37444 --- /dev/null +++ b/0205-isomorphic-strings/0205-isomorphic-strings.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + + bool helper(string s, string t) + { + map mp; + int n = s.size(); + + for(int i =0 ; i < n; ++i) + { + if(mp.find(s[i]) != mp.end()) + { + if(mp[s[i]] != t[i]) + return false; + } + else + mp[s[i]] = t[i]; + } + + return true; + } + + bool isIsomorphic(string s, string t) { + + return helper(s,t) and helper(t,s); + + } +}; \ No newline at end of file diff --git a/0205-isomorphic-strings/NOTES.md b/0205-isomorphic-strings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0205-isomorphic-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0205-isomorphic-strings/README.md b/0205-isomorphic-strings/README.md new file mode 100644 index 00000000..c7d544ca --- /dev/null +++ b/0205-isomorphic-strings/README.md @@ -0,0 +1,26 @@ +

205. Isomorphic Strings

Easy


Given two strings s and t, determine if they are isomorphic.

+ +

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

+ +

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

+ +

 

+

Example 1:

+
Input: s = "egg", t = "add"
+Output: true
+

Example 2:

+
Input: s = "foo", t = "bar"
+Output: false
+

Example 3:

+
Input: s = "paper", t = "title"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • t.length == s.length
  • +
  • s and t consist of any valid ascii character.
  • +
+
\ No newline at end of file diff --git a/0206-reverse-linked-list/0206-reverse-linked-list.cpp b/0206-reverse-linked-list/0206-reverse-linked-list.cpp new file mode 100644 index 00000000..2418f3bc --- /dev/null +++ b/0206-reverse-linked-list/0206-reverse-linked-list.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + + ListNode* prev = nullptr; + + while(head) + { + ListNode* nex = head->next; + head->next = prev; + prev = head; + head = nex; + } + + return prev; + } +}; \ No newline at end of file diff --git a/0206-reverse-linked-list/NOTES.md b/0206-reverse-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0206-reverse-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0207-course-schedule/0207-course-schedule.cpp b/0207-course-schedule/0207-course-schedule.cpp new file mode 100644 index 00000000..e3c97222 --- /dev/null +++ b/0207-course-schedule/0207-course-schedule.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + + bool canFinish(int numCourses, vector>& prerequisites) { + + int n = numCourses; + + vector adj[n+1]; + + for(auto itr : prerequisites) + adj[itr[1]].push_back(itr[0]); + + vector indegree(n+1, 0); + + for(int i = 0; i < n; ++i) + { + for(auto itr : adj[i]) + ++indegree[itr]; + } + + queue q; + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + if(indegree[i] == 0) + q.push(i); + } + + while(!q.empty()) + { + int curr = q.front(); + q.pop(); + + ++cnt; + + for(auto itr : adj[curr]) + { + --indegree[itr]; + if(indegree[itr] == 0) + q.push(itr); + } + } + + return cnt == n; + } +}; \ No newline at end of file diff --git a/0207-course-schedule/NOTES.md b/0207-course-schedule/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0207-course-schedule/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0207-course-schedule/README.md b/0207-course-schedule/README.md new file mode 100644 index 00000000..c9f7b97e --- /dev/null +++ b/0207-course-schedule/README.md @@ -0,0 +1,36 @@ +

207. Course Schedule

Medium


There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

+ +
    +
  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
  • +
+ +

Return true if you can finish all courses. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: numCourses = 2, prerequisites = [[1,0]]
+Output: true
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0. So it is possible.
+
+ +

Example 2:

+ +
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
+Output: false
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 2000
  • +
  • 0 <= prerequisites.length <= 5000
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • All the pairs prerequisites[i] are unique.
  • +
+
\ No newline at end of file diff --git a/0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.cpp b/0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.cpp new file mode 100644 index 00000000..474e9385 --- /dev/null +++ b/0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.cpp @@ -0,0 +1,118 @@ +class Node +{ + +public: + Node *child[26] = {nullptr}; + bool isWord = false; + int cntEndWith = 0; + int cntPrefix = 0; + + bool containsKey(char ch) + { + return (child[ch - 'a'] != nullptr); + } + + void put(char ch, Node *node) + { + child[ch - 'a'] = node; + } + + Node *get(char ch) + { + return child[ch - 'a']; + } + + void setEnd() + { + isWord = true; + } + + bool isEnd() + { + return isWord; + } + + void increaseEnd() + { + ++cntEndWith; + } + + void increasePrefix() + { + ++cntPrefix; + } + + void deleteEnd() + { + --cntEndWith; + } + + void reducePrefix() + { + --cntPrefix; + } + + int getEnd() + { + return cntEndWith; + } + + int getPrefix() + { + return cntPrefix; + } +}; + + +class Trie { +public: + private: + Node* root; + public: + Trie() { + root = new Node(); + } + + void insert(string word) { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (!temp->containsKey(word[i])) + temp->put(word[i], new Node()); + temp = temp->get(word[i]); + temp->increasePrefix(); + } + temp->increaseEnd(); + temp->setEnd(); + } + + bool search(string word) { + Node *temp = root; + for(int i = 0; icontainsKey(word[i])) + return false; + temp = temp->get(word[i]); + } + return temp->isEnd(); + } + + bool startsWith(string prefix) { + Node *temp = root; + for(int i = 0; icontainsKey(prefix[i])) + return false; + temp = temp->get(prefix[i]); + } + return true; + } +}; + +/** + * Your Trie object will be instantiated and called as such: + * Trie* obj = new Trie(); + * obj->insert(word); + * bool param_2 = obj->search(word); + * bool param_3 = obj->startsWith(prefix); + */ \ No newline at end of file diff --git a/0208-implement-trie-prefix-tree/NOTES.md b/0208-implement-trie-prefix-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0208-implement-trie-prefix-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0208-implement-trie-prefix-tree/README.md b/0208-implement-trie-prefix-tree/README.md new file mode 100644 index 00000000..fb35aa46 --- /dev/null +++ b/0208-implement-trie-prefix-tree/README.md @@ -0,0 +1,39 @@ +

208. Implement Trie (Prefix Tree)

Medium


A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

+ +

Implement the Trie class:

+ +
    +
  • Trie() Initializes the trie object.
  • +
  • void insert(String word) Inserts the string word into the trie.
  • +
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • +
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
+[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
+Output
+[null, null, true, false, true, null, true]
+
+Explanation
+Trie trie = new Trie();
+trie.insert("apple");
+trie.search("apple");   // return True
+trie.search("app");     // return False
+trie.startsWith("app"); // return True
+trie.insert("app");
+trie.search("app");     // return True
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length, prefix.length <= 2000
  • +
  • word and prefix consist only of lowercase English letters.
  • +
  • At most 3 * 104 calls in total will be made to insert, search, and startsWith.
  • +
+
\ No newline at end of file diff --git a/0209-minimum-size-subarray-sum/0209-minimum-size-subarray-sum.cpp b/0209-minimum-size-subarray-sum/0209-minimum-size-subarray-sum.cpp new file mode 100644 index 00000000..4950b0fa --- /dev/null +++ b/0209-minimum-size-subarray-sum/0209-minimum-size-subarray-sum.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + + int i = 0, j = 0, n = nums.size(); + + int sum = 0, ans = INT_MAX; + + while(j < n) + { + sum += nums[j]; + + while(sum >= target) + { + ans = min(ans, j - i + 1); + + sum -= nums[i++]; + } + + ++j; + } + + return (ans == INT_MAX ? 0 : ans); + + } +}; \ No newline at end of file diff --git a/0209-minimum-size-subarray-sum/NOTES.md b/0209-minimum-size-subarray-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0209-minimum-size-subarray-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0209-minimum-size-subarray-sum/README.md b/0209-minimum-size-subarray-sum/README.md new file mode 100644 index 00000000..a87e5a79 --- /dev/null +++ b/0209-minimum-size-subarray-sum/README.md @@ -0,0 +1,33 @@ +

209. Minimum Size Subarray Sum

Medium


Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

+ +

 

+

Example 1:

+ +
Input: target = 7, nums = [2,3,1,2,4,3]
+Output: 2
+Explanation: The subarray [4,3] has the minimal length under the problem constraint.
+
+ +

Example 2:

+ +
Input: target = 4, nums = [1,4,4]
+Output: 1
+
+ +

Example 3:

+ +
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target <= 109
  • +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 104
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).
\ No newline at end of file diff --git a/0210-course-schedule-ii/0210-course-schedule-ii.cpp b/0210-course-schedule-ii/0210-course-schedule-ii.cpp new file mode 100644 index 00000000..7d885a02 --- /dev/null +++ b/0210-course-schedule-ii/0210-course-schedule-ii.cpp @@ -0,0 +1,51 @@ +class Solution { + +public: + vector findOrder(int numCourses, vector>& prerequisites) { + + int n = numCourses; + + vector adj[n+1]; + + for(auto itr : prerequisites) + { + adj[itr[1]].push_back(itr[0]); + } + + vector indegree(n, 0), topo; + + for(int i = 0; i < n; ++i) + { + for(auto itr : adj[i]) + ++indegree[itr]; + } + + queue q; + + for(int i = 0; i < n; ++i) + { + if(indegree[i] == 0) + q.push(i); + } + + while(!q.empty()) + { + int curr = q.front(); + q.pop(); + + topo.push_back(curr); + + for(auto itr : adj[curr]) + { + --indegree[itr]; + if(indegree[itr] == 0) + q.push(itr); + } + } + + if(topo.size() < n) + return {}; + + return topo; + } +}; \ No newline at end of file diff --git a/0210-course-schedule-ii/NOTES.md b/0210-course-schedule-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0210-course-schedule-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0210-course-schedule-ii/README.md b/0210-course-schedule-ii/README.md new file mode 100644 index 00000000..84a22833 --- /dev/null +++ b/0210-course-schedule-ii/README.md @@ -0,0 +1,42 @@ +

210. Course Schedule II

Medium


There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

+ +
    +
  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
  • +
+ +

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

+ +

 

+

Example 1:

+ +
Input: numCourses = 2, prerequisites = [[1,0]]
+Output: [0,1]
+Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
+
+ +

Example 2:

+ +
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
+Output: [0,2,1,3]
+Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
+So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
+
+ +

Example 3:

+ +
Input: numCourses = 1, prerequisites = []
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 2000
  • +
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • ai != bi
  • +
  • All the pairs [ai, bi] are distinct.
  • +
+
\ No newline at end of file diff --git a/0211-design-add-and-search-words-data-structure/0211-design-add-and-search-words-data-structure.cpp b/0211-design-add-and-search-words-data-structure/0211-design-add-and-search-words-data-structure.cpp new file mode 100644 index 00000000..a10276bc --- /dev/null +++ b/0211-design-add-and-search-words-data-structure/0211-design-add-and-search-words-data-structure.cpp @@ -0,0 +1,90 @@ +class Node{ + public: + Node* child[26] = {nullptr}; + bool isWord = false; + public: + bool containsKey(char ch) + { + return child[ch-'a'] != nullptr; + } + + void put(char ch, Node* node){ + child[ch-'a'] = node; + } + + Node* get(char ch) + { + return child[ch - 'a']; + } + + void setEnd() + { + isWord = true; + } +}; + +class WordDictionary { + + private : + Node* root; + +public: + WordDictionary() { + root = new Node(); + } + + void addWord(string word) { + Node* temp = root; + for(auto ch : word) + { + if(!temp->containsKey(ch)) + temp->put(ch,new Node()); + temp = temp->get(ch); + } + temp->setEnd(); + } + + bool search(string word) { + Node* temp = root; + return helper(word, temp); + } + + bool helper(string word, Node* node){ + Node*temp = node; + for(int i = 0; icontainsKey(ch)) + return false; + temp = temp->get(ch); + } + else + { + bool found = false; + int j = 0; + for(;j<26; ++j) + { + if(temp->child[j]) + found |= helper(word.substr(i+1),temp->child[j]); + if(found) + return true; + } + if(j == 26) + return false; + + } + + } + return temp->isWord; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ \ No newline at end of file diff --git a/0211-design-add-and-search-words-data-structure/README.md b/0211-design-add-and-search-words-data-structure/README.md new file mode 100644 index 00000000..0a1f4b12 --- /dev/null +++ b/0211-design-add-and-search-words-data-structure/README.md @@ -0,0 +1,41 @@ +

211. Design Add and Search Words Data Structure

Medium


Design a data structure that supports adding new words and finding if a string matches any previously added string.

+ +

Implement the WordDictionary class:

+ +
    +
  • WordDictionary() Initializes the object.
  • +
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • +
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
  • +
+ +

 

+

Example:

+ +
Input
+["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
+[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
+Output
+[null,null,null,null,false,true,true,true]
+
+Explanation
+WordDictionary wordDictionary = new WordDictionary();
+wordDictionary.addWord("bad");
+wordDictionary.addWord("dad");
+wordDictionary.addWord("mad");
+wordDictionary.search("pad"); // return False
+wordDictionary.search("bad"); // return True
+wordDictionary.search(".ad"); // return True
+wordDictionary.search("b.."); // return True
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 25
  • +
  • word in addWord consists of lowercase English letters.
  • +
  • word in search consist of '.' or lowercase English letters.
  • +
  • There will be at most 3 dots in word for search queries.
  • +
  • At most 104 calls will be made to addWord and search.
  • +
+
\ No newline at end of file diff --git a/0214-shortest-palindrome/0214-shortest-palindrome.cpp b/0214-shortest-palindrome/0214-shortest-palindrome.cpp new file mode 100644 index 00000000..96fd9852 --- /dev/null +++ b/0214-shortest-palindrome/0214-shortest-palindrome.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + string shortestPalindrome(string s) { + + string rev = s; + int n = s.size(); + + reverse(rev.begin(), rev.end()); + + string str = s + '#' + rev; + + int size = str.size(); + + vector lps(size,0); + + for(int i = 1; i < size; ++i) + { + int j = lps[i-1]; + + while(j > 0 and str[i] != str[j]) + j = lps[j-1]; + + if(str[i] == str[j]) + ++j; + + lps[i] = j; + } + + string ans = rev.substr(0, n - lps[size - 1]) + s; + + return ans; + } +}; \ No newline at end of file diff --git a/0214-shortest-palindrome/NOTES.md b/0214-shortest-palindrome/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0214-shortest-palindrome/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0215-kth-largest-element-in-an-array/0215-kth-largest-element-in-an-array.cpp b/0215-kth-largest-element-in-an-array/0215-kth-largest-element-in-an-array.cpp new file mode 100644 index 00000000..e7e13534 --- /dev/null +++ b/0215-kth-largest-element-in-an-array/0215-kth-largest-element-in-an-array.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findKthLargest(vector& nums, int k) { + + priority_queue pq(nums.begin(),nums.end()); + + while(k-- > 1) + { + pq.pop(); + } + + return pq.top(); + + } +}; \ No newline at end of file diff --git a/0215-kth-largest-element-in-an-array/NOTES.md b/0215-kth-largest-element-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0215-kth-largest-element-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0215-kth-largest-element-in-an-array/README.md b/0215-kth-largest-element-in-an-array/README.md new file mode 100644 index 00000000..1735cc58 --- /dev/null +++ b/0215-kth-largest-element-in-an-array/README.md @@ -0,0 +1,22 @@ +

215. Kth Largest Element in an Array

Medium


Given an integer array nums and an integer k, return the kth largest element in the array.

+ +

Note that it is the kth largest element in the sorted order, not the kth distinct element.

+ +

Can you solve it without sorting?

+ +

 

+

Example 1:

+
Input: nums = [3,2,1,5,6,4], k = 2
+Output: 5
+

Example 2:

+
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
+Output: 4
+
+

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0221-maximal-square/0221-maximal-square.cpp b/0221-maximal-square/0221-maximal-square.cpp new file mode 100644 index 00000000..81286ea2 --- /dev/null +++ b/0221-maximal-square/0221-maximal-square.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int maximalSquare(vector>& matrix) { + + int n = matrix.size(), m = matrix[0].size(); + + vector curr(m, 0), prev(m , 0); + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(i == 0 or j == 0) + curr[j] = matrix[i][j] - 48; + + if(i > 0 and j > 0 and matrix[i][j] != '0') + { + int leftDiagonal = prev[j-1]; + int bottomLeft = curr[j-1]; + int topRight = prev[j]; + + curr[j] = min({leftDiagonal, bottomLeft, topRight}) + 1; + } + ans = max(ans,curr[j]); + } + fill(prev.begin(),prev.end(),0); + swap(prev,curr); + } + + return ans * ans; + + } +}; \ No newline at end of file diff --git a/0221-maximal-square/NOTES.md b/0221-maximal-square/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0221-maximal-square/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0221-maximal-square/README.md b/0221-maximal-square/README.md new file mode 100644 index 00000000..433a2f97 --- /dev/null +++ b/0221-maximal-square/README.md @@ -0,0 +1,31 @@ +

221. Maximal Square

Medium


Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 4
+
+ +

Example 2:

+ +
Input: matrix = [["0","1"],["1","0"]]
+Output: 1
+
+ +

Example 3:

+ +
Input: matrix = [["0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/0225-implement-stack-using-queues/0225-implement-stack-using-queues.cpp b/0225-implement-stack-using-queues/0225-implement-stack-using-queues.cpp new file mode 100644 index 00000000..b2b7c970 --- /dev/null +++ b/0225-implement-stack-using-queues/0225-implement-stack-using-queues.cpp @@ -0,0 +1,43 @@ +class MyStack { +public: + + queue q; + + MyStack() { + + } + + void push(int x) { + + q.push(x); + + for(int i = 0; i < q.size()-1; ++i) + { + q.push(q.front()); + q.pop(); + } + } + + int pop() { + int x = q.front(); + q.pop(); + return x; + } + + int top() { + return q.front(); + } + + bool empty() { + return q.empty(); + } +}; + +/** + * Your MyStack object will be instantiated and called as such: + * MyStack* obj = new MyStack(); + * obj->push(x); + * int param_2 = obj->pop(); + * int param_3 = obj->top(); + * bool param_4 = obj->empty(); + */ \ No newline at end of file diff --git a/0225-implement-stack-using-queues/NOTES.md b/0225-implement-stack-using-queues/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0225-implement-stack-using-queues/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0225-implement-stack-using-queues/README.md b/0225-implement-stack-using-queues/README.md new file mode 100644 index 00000000..271ce450 --- /dev/null +++ b/0225-implement-stack-using-queues/README.md @@ -0,0 +1,48 @@ +

225. Implement Stack using Queues

Easy


Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

+ +

Implement the MyStack class:

+ +
    +
  • void push(int x) Pushes element x to the top of the stack.
  • +
  • int pop() Removes the element on the top of the stack and returns it.
  • +
  • int top() Returns the element on the top of the stack.
  • +
  • boolean empty() Returns true if the stack is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • +
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyStack", "push", "push", "top", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 2, 2, false]
+
+Explanation
+MyStack myStack = new MyStack();
+myStack.push(1);
+myStack.push(2);
+myStack.top(); // return 2
+myStack.pop(); // return 2
+myStack.empty(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, top, and empty.
  • +
  • All the calls to pop and top are valid.
  • +
+ +

 

+

Follow-up: Can you implement the stack using only one queue?

+
\ No newline at end of file diff --git a/0226-invert-binary-tree/0226-invert-binary-tree.cpp b/0226-invert-binary-tree/0226-invert-binary-tree.cpp new file mode 100644 index 00000000..de9099a8 --- /dev/null +++ b/0226-invert-binary-tree/0226-invert-binary-tree.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + TreeNode* invertTree(TreeNode* root) { + + if(!root) + return nullptr; + + TreeNode* temp = root->left; + root->left = root->right; + root->right = temp; + + invertTree(root->left); + invertTree(root->right); + + return root; + } +}; \ No newline at end of file diff --git a/0226-invert-binary-tree/NOTES.md b/0226-invert-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0226-invert-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0226-invert-binary-tree/README.md b/0226-invert-binary-tree/README.md new file mode 100644 index 00000000..253f28a2 --- /dev/null +++ b/0226-invert-binary-tree/README.md @@ -0,0 +1,29 @@ +

226. Invert Binary Tree

Easy


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

+ +

 

+

Example 1:

+ +
Input: root = [4,2,7,1,3,6,9]
+Output: [4,7,2,9,6,3,1]
+
+ +

Example 2:

+ +
Input: root = [2,1,3]
+Output: [2,3,1]
+
+ +

Example 3:

+ +
Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0228-summary-ranges/0228-summary-ranges.cpp b/0228-summary-ranges/0228-summary-ranges.cpp new file mode 100644 index 00000000..f7704360 --- /dev/null +++ b/0228-summary-ranges/0228-summary-ranges.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + vector summaryRanges(vector& nums) { + + int n = nums.size(); + + vector ans; + + if(n == 0) + return ans; + + int curr = nums[0], track = nums[0], prev = nums[0]; + + for(int i = 1; i < n; ++i) + { + if(nums[i] == track + 1) + { + ++track; + } + else + { + if(curr == prev) + ans.push_back(to_string(curr)); + else + { + string str = to_string(curr); + + str += "->" + to_string(prev); + + ans.push_back(str); + } + + curr = nums[i]; + + track = nums[i]; + + + } + + prev = nums[i]; + } + + if(curr == prev) + ans.push_back(to_string(curr)); + else + { + string str = to_string(curr); + + str += "->" + to_string(prev); + + ans.push_back(str); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0228-summary-ranges/NOTES.md b/0228-summary-ranges/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0228-summary-ranges/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0228-summary-ranges/README.md b/0228-summary-ranges/README.md new file mode 100644 index 00000000..4200ad9f --- /dev/null +++ b/0228-summary-ranges/README.md @@ -0,0 +1,45 @@ +

228. Summary Ranges

Easy


You are given a sorted unique integer array nums.

+ +

A range [a,b] is the set of all integers from a to b (inclusive).

+ +

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

+ +

Each range [a,b] in the list should be output as:

+ +
    +
  • "a->b" if a != b
  • +
  • "a" if a == b
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [0,1,2,4,5,7]
+Output: ["0->2","4->5","7"]
+Explanation: The ranges are:
+[0,2] --> "0->2"
+[4,5] --> "4->5"
+[7,7] --> "7"
+
+ +

Example 2:

+ +
Input: nums = [0,2,3,4,6,8,9]
+Output: ["0","2->4","6","8->9"]
+Explanation: The ranges are:
+[0,0] --> "0"
+[2,4] --> "2->4"
+[6,6] --> "6"
+[8,9] --> "8->9"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 20
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • All the values of nums are unique.
  • +
  • nums is sorted in ascending order.
  • +
+
\ No newline at end of file diff --git a/0231-power-of-two/0231-power-of-two.cpp b/0231-power-of-two/0231-power-of-two.cpp new file mode 100644 index 00000000..183a7700 --- /dev/null +++ b/0231-power-of-two/0231-power-of-two.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n == 1) + return true; + if(n & 1 or n == 0) + return false; + return isPowerOfTwo(n/2); + } +}; \ No newline at end of file diff --git a/0231-power-of-two/NOTES.md b/0231-power-of-two/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0231-power-of-two/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0231-power-of-two/README.md b/0231-power-of-two/README.md new file mode 100644 index 00000000..b6b0cad9 --- /dev/null +++ b/0231-power-of-two/README.md @@ -0,0 +1,34 @@ +

231. Power of Two

Easy


Given an integer n, return true if it is a power of two. Otherwise, return false.

+ +

An integer n is a power of two, if there exists an integer x such that n == 2x.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: true
+Explanation: 20 = 1
+
+ +

Example 2:

+ +
Input: n = 16
+Output: true
+Explanation: 24 = 16
+
+ +

Example 3:

+ +
Input: n = 3
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.cpp b/0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.cpp new file mode 100644 index 00000000..607eed35 --- /dev/null +++ b/0232-implement-queue-using-stacks/0232-implement-queue-using-stacks.cpp @@ -0,0 +1,50 @@ +class MyQueue { +public: + + stack s; + MyQueue() { + + } + + void push(int x) { + pushHelper(x); + } + + void pushHelper(int x) + { + if(s.size() == 0) + { + s.push(x); + return; + } + + int data = s.top(); + s.pop(); + pushHelper(x); + s.push(data); + return; + } + + int pop() { + int a = s.top(); + s.pop(); + return a; + } + + int peek() { + return s.top(); + } + + bool empty() { + return s.empty(); + } +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue* obj = new MyQueue(); + * obj->push(x); + * int param_2 = obj->pop(); + * int param_3 = obj->peek(); + * bool param_4 = obj->empty(); + */ \ No newline at end of file diff --git a/0232-implement-queue-using-stacks/NOTES.md b/0232-implement-queue-using-stacks/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0232-implement-queue-using-stacks/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0232-implement-queue-using-stacks/README.md b/0232-implement-queue-using-stacks/README.md new file mode 100644 index 00000000..044efecc --- /dev/null +++ b/0232-implement-queue-using-stacks/README.md @@ -0,0 +1,48 @@ +

232. Implement Queue using Stacks

Easy


Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

+ +

Implement the MyQueue class:

+ +
    +
  • void push(int x) Pushes element x to the back of the queue.
  • +
  • int pop() Removes the element from the front of the queue and returns it.
  • +
  • int peek() Returns the element at the front of the queue.
  • +
  • boolean empty() Returns true if the queue is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • +
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyQueue", "push", "push", "peek", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 1, 1, false]
+
+Explanation
+MyQueue myQueue = new MyQueue();
+myQueue.push(1); // queue is: [1]
+myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
+myQueue.peek(); // return 1
+myQueue.pop(); // return 1, queue is [2]
+myQueue.empty(); // return false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, peek, and empty.
  • +
  • All the calls to pop and peek are valid.
  • +
+ +

 

+

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

+
\ No newline at end of file diff --git a/0234-palindrome-linked-list/0234-palindrome-linked-list.cpp b/0234-palindrome-linked-list/0234-palindrome-linked-list.cpp new file mode 100644 index 00000000..a1d444cd --- /dev/null +++ b/0234-palindrome-linked-list/0234-palindrome-linked-list.cpp @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + bool isPalindrome(ListNode* head) { + + ListNode* fast = head, *slow = head; + + while(fast and fast->next) + { + fast = fast->next->next; + slow = slow->next; + } + + ListNode* nexHalf = slow; + + ListNode* prev = nullptr; + + while(nexHalf) + { + ListNode* nex = nexHalf->next; + nexHalf->next = prev; + prev = nexHalf; + nexHalf = nex; + } + + while(head != slow) + { + if(head->val != prev->val) + return false; + head = head->next; + prev = prev->next; + } + + return true; + + } +}; \ No newline at end of file diff --git a/0234-palindrome-linked-list/README.md b/0234-palindrome-linked-list/README.md new file mode 100644 index 00000000..d71facb1 --- /dev/null +++ b/0234-palindrome-linked-list/README.md @@ -0,0 +1,25 @@ +

234. Palindrome Linked List

Easy


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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,2,1]
+Output: true
+
+ +

Example 2:

+ +
Input: head = [1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 105].
  • +
  • 0 <= Node.val <= 9
  • +
+ +

 

+Follow up: Could you do it in O(n) time and O(1) space?
\ No newline at end of file diff --git a/0236-lowest-common-ancestor-of-a-binary-tree/0236-lowest-common-ancestor-of-a-binary-tree.cpp b/0236-lowest-common-ancestor-of-a-binary-tree/0236-lowest-common-ancestor-of-a-binary-tree.cpp new file mode 100644 index 00000000..75cb67eb --- /dev/null +++ b/0236-lowest-common-ancestor-of-a-binary-tree/0236-lowest-common-ancestor-of-a-binary-tree.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + + if(!root or root == p or root == q) + return root; + + TreeNode *left = lowestCommonAncestor(root->left,p,q); + TreeNode *right = lowestCommonAncestor(root->right,p,q); + + if(!left) + return right; + if(!right) + return left; + + return root; + } +}; \ No newline at end of file diff --git a/0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md b/0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0236-lowest-common-ancestor-of-a-binary-tree/README.md b/0236-lowest-common-ancestor-of-a-binary-tree/README.md new file mode 100644 index 00000000..33fa84b0 --- /dev/null +++ b/0236-lowest-common-ancestor-of-a-binary-tree/README.md @@ -0,0 +1,36 @@ +

236. Lowest Common Ancestor of a Binary Tree

Medium


Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
+Output: 3
+Explanation: The LCA of nodes 5 and 1 is 3.
+
+ +

Example 2:

+ +
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
+Output: 5
+Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
Input: root = [1,2], p = 1, q = 2
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the tree.
  • +
+
\ No newline at end of file diff --git a/0237-delete-node-in-a-linked-list/0237-delete-node-in-a-linked-list.cpp b/0237-delete-node-in-a-linked-list/0237-delete-node-in-a-linked-list.cpp new file mode 100644 index 00000000..9a3c0cf0 --- /dev/null +++ b/0237-delete-node-in-a-linked-list/0237-delete-node-in-a-linked-list.cpp @@ -0,0 +1,16 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + + node->val = node->next->val; + node->next = node->next->next; + } +}; \ No newline at end of file diff --git a/0237-delete-node-in-a-linked-list/NOTES.md b/0237-delete-node-in-a-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0237-delete-node-in-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0237-delete-node-in-a-linked-list/README.md b/0237-delete-node-in-a-linked-list/README.md new file mode 100644 index 00000000..3fc46f11 --- /dev/null +++ b/0237-delete-node-in-a-linked-list/README.md @@ -0,0 +1,48 @@ +

237. Delete Node in a Linked List

Medium


There is a singly-linked list head and we want to delete a node node in it.

+ +

You are given the node to be deleted node. You will not be given access to the first node of head.

+ +

All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.

+ +

Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:

+ +
    +
  • The value of the given node should not exist in the linked list.
  • +
  • The number of nodes in the linked list should decrease by one.
  • +
  • All the values before node should be in the same order.
  • +
  • All the values after node should be in the same order.
  • +
+ +

Custom testing:

+ +
    +
  • For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
  • +
  • We will build the linked list and pass the node to your function.
  • +
  • The output will be the entire list after calling your function.
  • +
+ +

 

+

Example 1:

+ +
Input: head = [4,5,1,9], node = 5
+Output: [4,1,9]
+Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
+
+ +

Example 2:

+ +
Input: head = [4,5,1,9], node = 1
+Output: [4,5,9]
+Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [2, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • The value of each node in the list is unique.
  • +
  • The node to be deleted is in the list and is not a tail node.
  • +
+
\ No newline at end of file diff --git a/0238-product-of-array-except-self/0238-product-of-array-except-self.cpp b/0238-product-of-array-except-self/0238-product-of-array-except-self.cpp new file mode 100644 index 00000000..5dae18ab --- /dev/null +++ b/0238-product-of-array-except-self/0238-product-of-array-except-self.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector productExceptSelf(vector& nums) { + + int n = nums.size(); + vector ans(n, 1); + + int pref = 1, suff = 1; + + for(int i = 0; i < n; ++i) + { + ans[i] *= pref; + pref *= nums[i]; + } + + for(int i = n-1; i >= 0; --i) + { + ans[i] *= suff; + suff *= nums[i]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0238-product-of-array-except-self/README.md b/0238-product-of-array-except-self/README.md new file mode 100644 index 00000000..494c527b --- /dev/null +++ b/0238-product-of-array-except-self/README.md @@ -0,0 +1,26 @@ +

238. Product of Array Except Self

Medium


Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

+ +

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

+ +

You must write an algorithm that runs in O(n) time and without using the division operation.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3,4]
+Output: [24,12,8,6]
+

Example 2:

+
Input: nums = [-1,1,0,-3,3]
+Output: [0,0,9,0,0]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -30 <= nums[i] <= 30
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+ +

 

+

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

+
\ No newline at end of file diff --git a/0239-sliding-window-maximum/0239-sliding-window-maximum.cpp b/0239-sliding-window-maximum/0239-sliding-window-maximum.cpp new file mode 100644 index 00000000..f0c6f117 --- /dev/null +++ b/0239-sliding-window-maximum/0239-sliding-window-maximum.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + + int n = nums.size(); + + int i = 0, j = 0; + + list l; + + vector ans; + + while(j < n) + { + while(!l.empty() and nums[l.back()] <= nums[j]) + l.pop_back(); + + l.push_back(j); + + if(j - i + 1 == k) + { + ans.push_back(nums[l.front()]); + + if(l.front() == i) + l.pop_front(); + + ++i; + } + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0239-sliding-window-maximum/NOTES.md b/0239-sliding-window-maximum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0239-sliding-window-maximum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0239-sliding-window-maximum/README.md b/0239-sliding-window-maximum/README.md new file mode 100644 index 00000000..e987f895 --- /dev/null +++ b/0239-sliding-window-maximum/README.md @@ -0,0 +1,35 @@ +

239. Sliding Window Maximum

Hard


You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

+ +

Return the max sliding window.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
+Output: [3,3,5,5,6,7]
+Explanation: 
+Window position                Max
+---------------               -----
+[1  3  -1] -3  5  3  6  7       3
+ 1 [3  -1  -3] 5  3  6  7       3
+ 1  3 [-1  -3  5] 3  6  7       5
+ 1  3  -1 [-3  5  3] 6  7       5
+ 1  3  -1  -3 [5  3  6] 7       6
+ 1  3  -1  -3  5 [3  6  7]      7
+
+ +

Example 2:

+ +
Input: nums = [1], k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
  • 1 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/0242-valid-anagram/0242-valid-anagram.cpp b/0242-valid-anagram/0242-valid-anagram.cpp new file mode 100644 index 00000000..e0ced785 --- /dev/null +++ b/0242-valid-anagram/0242-valid-anagram.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool isAnagram(string s, string t) { + + vector freq(26, 0); + + for(auto& ch : s) + ++freq[ch - 'a']; + + for(auto& ch : t) + --freq[ch - 'a']; + + for(int i = 0; i< 26; ++i) + { + if(freq[i] != 0) return false; + } + + return true; + } +}; \ No newline at end of file diff --git a/0242-valid-anagram/NOTES.md b/0242-valid-anagram/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0242-valid-anagram/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0242-valid-anagram/README.md b/0242-valid-anagram/README.md new file mode 100644 index 00000000..c06723c0 --- /dev/null +++ b/0242-valid-anagram/README.md @@ -0,0 +1,23 @@ +

242. Valid Anagram

Easy


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

+ +

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

+ +

 

+

Example 1:

+
Input: s = "anagram", t = "nagaram"
+Output: true
+

Example 2:

+
Input: s = "rat", t = "car"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 5 * 104
  • +
  • s and t consist of lowercase English letters.
  • +
+ +

 

+

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

+
\ No newline at end of file diff --git a/0258-add-digits/0258-add-digits.cpp b/0258-add-digits/0258-add-digits.cpp new file mode 100644 index 00000000..4c0f7eee --- /dev/null +++ b/0258-add-digits/0258-add-digits.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int addDigits(int num) { + + string str = to_string(num); + + while(true) + { + string curr; + int sum = 0; + + for(auto itr : str) + { + sum += itr-'0'; + } + + curr = to_string(sum); + + if(curr.size() == 1) + return stoi(curr); + + str = curr; + } + + return 0; + } +}; \ No newline at end of file diff --git a/0258-add-digits/NOTES.md b/0258-add-digits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0258-add-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0258-add-digits/README.md b/0258-add-digits/README.md new file mode 100644 index 00000000..cc5f53bd --- /dev/null +++ b/0258-add-digits/README.md @@ -0,0 +1,29 @@ +

258. Add Digits

Easy


Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

+ +

 

+

Example 1:

+ +
Input: num = 38
+Output: 2
+Explanation: The process is
+38 --> 3 + 8 --> 11
+11 --> 1 + 1 --> 2 
+Since 2 has only one digit, return it.
+
+ +

Example 2:

+ +
Input: num = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+ +

 

+

Follow up: Could you do it without any loop/recursion in O(1) runtime?

+
\ No newline at end of file diff --git a/0260-single-number-iii/0260-single-number-iii.cpp b/0260-single-number-iii/0260-single-number-iii.cpp new file mode 100644 index 00000000..8adcc2c8 --- /dev/null +++ b/0260-single-number-iii/0260-single-number-iii.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector singleNumber(vector& nums) { + + int b1 = 0, b2 = 0; + + long long xorr = 0; + + for(auto& ele : nums) + xorr ^= ele; + + long long rightMost = (xorr&(xorr-1)) ^ xorr; + + for(auto& ele : nums) + { + if(ele & rightMost) + b1 ^= ele; + else + b2 ^= ele; + } + + return {b1, b2}; + } +}; \ No newline at end of file diff --git a/0260-single-number-iii/README.md b/0260-single-number-iii/README.md new file mode 100644 index 00000000..203cd5d7 --- /dev/null +++ b/0260-single-number-iii/README.md @@ -0,0 +1,33 @@ +

260. Single Number III

Medium


Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

+ +

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1,3,2,5]
+Output: [3,5]
+Explanation:  [5, 3] is also a valid answer.
+
+ +

Example 2:

+ +
Input: nums = [-1,0]
+Output: [-1,0]
+
+ +

Example 3:

+ +
Input: nums = [0,1]
+Output: [1,0]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 3 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • Each integer in nums will appear twice, only two integers will appear once.
  • +
+
\ No newline at end of file diff --git a/0264-ugly-number-ii/0264-ugly-number-ii.cpp b/0264-ugly-number-ii/0264-ugly-number-ii.cpp new file mode 100644 index 00000000..27655d96 --- /dev/null +++ b/0264-ugly-number-ii/0264-ugly-number-ii.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int nthUglyNumber(int n) { + + vector v(n+1, 1); + + int i2 = 1, i3 = 1, i5 = 1; + + for(int i = 2; i <= n; ++i) + { + int ithUgly = min({v[i2] * 2, v[i3] * 3, v[i5] * 5}); + + v[i] = ithUgly; + + if(v[i] == v[i2] * 2) ++i2; + if(v[i] == v[i3] * 3) ++i3; + if(v[i] == v[i5] * 5) ++i5; + } + + return v[n]; + + } +}; \ No newline at end of file diff --git a/0264-ugly-number-ii/README.md b/0264-ugly-number-ii/README.md new file mode 100644 index 00000000..296532e1 --- /dev/null +++ b/0264-ugly-number-ii/README.md @@ -0,0 +1,26 @@ +

264. Ugly Number II

Medium


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

+ +

Given an integer n, return the nth ugly number.

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: n = 1
+Output: 1
+Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1690
  • +
+
\ No newline at end of file diff --git a/0268-missing-number/0268-missing-number.cpp b/0268-missing-number/0268-missing-number.cpp new file mode 100644 index 00000000..dacbf752 --- /dev/null +++ b/0268-missing-number/0268-missing-number.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int missingNumber(vector& nums) { + + int n = nums.size(); + + int sum = 0; + + for(auto& ele : nums) + sum += ele; + + int totSum = (n * (n+1)) / 2; + + return totSum - sum; + + } +}; \ No newline at end of file diff --git a/0268-missing-number/NOTES.md b/0268-missing-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0268-missing-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0268-missing-number/README.md b/0268-missing-number/README.md new file mode 100644 index 00000000..f88e56a1 --- /dev/null +++ b/0268-missing-number/README.md @@ -0,0 +1,37 @@ +

268. Missing Number

Easy


Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

+ +

 

+

Example 1:

+ +
Input: nums = [3,0,1]
+Output: 2
+Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 2:

+ +
Input: nums = [0,1]
+Output: 2
+Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 3:

+ +
Input: nums = [9,6,4,2,3,5,7,0,1]
+Output: 8
+Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 104
  • +
  • 0 <= nums[i] <= n
  • +
  • All the numbers of nums are unique.
  • +
+ +

 

+

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

+
\ No newline at end of file diff --git a/0273-integer-to-english-words/0273-integer-to-english-words.cpp b/0273-integer-to-english-words/0273-integer-to-english-words.cpp new file mode 100644 index 00000000..f6db280d --- /dev/null +++ b/0273-integer-to-english-words/0273-integer-to-english-words.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector> nums ={{1000000000, "Billion"}, {1000000, "Million"}, + {1000, "Thousand"}, {100, "Hundred"}, {90, "Ninety"}, {80, "Eighty"}, {70, "Seventy"}, + {60, "Sixty"}, {50, "Fifty"}, {40, "Forty"}, {30, "Thirty"}, {20, "Twenty"}, {19, "Nineteen"}, + {18, "Eighteen"}, {17, "Seventeen"}, {16, "Sixteen"}, {15, "Fifteen"}, {14, "Fourteen"}, + {13, "Thirteen"}, {12, "Twelve"}, {11, "Eleven"}, {10, "Ten"}, {9, "Nine"}, {8, "Eight"}, + {7, "Seven"}, {6, "Six"}, {5, "Five"}, {4, "Four"}, {3, "Three"}, {2, "Two"}, {1, "One"}}; + + string numberToWords(int num) { + if(num == 0) return "Zero"; + + for(auto it: nums) + if(num >= it.first) + return (num >= 100 ? numberToWords(num/it.first)+" " : "") + it.second + (num%it.first == 0 ? "" : " "+numberToWords(num%it.first)); + + return ""; + } +}; \ No newline at end of file diff --git a/0273-integer-to-english-words/README.md b/0273-integer-to-english-words/README.md new file mode 100644 index 00000000..708515e3 --- /dev/null +++ b/0273-integer-to-english-words/README.md @@ -0,0 +1,28 @@ +

273. Integer to English Words

Hard


Convert a non-negative integer num to its English words representation.

+ +

 

+

Example 1:

+ +
Input: num = 123
+Output: "One Hundred Twenty Three"
+
+ +

Example 2:

+ +
Input: num = 12345
+Output: "Twelve Thousand Three Hundred Forty Five"
+
+ +

Example 3:

+ +
Input: num = 1234567
+Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0279-perfect-squares/0279-perfect-squares.cpp b/0279-perfect-squares/0279-perfect-squares.cpp new file mode 100644 index 00000000..3760af3c --- /dev/null +++ b/0279-perfect-squares/0279-perfect-squares.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int numSquares(int n) { + + if(ceil(sqrt(n)) == floor(sqrt(n))) + return 1; + + while(n%4 == 0) + n /= 4; + + if(n%8 == 7) + return 4; + + for(int i = 1; i*i <= n; ++i){ + int base = sqrt(n - (i*i)); + if((base * base) == (n - (i*i))) + return 2; + } + + return 3; + + } +}; \ No newline at end of file diff --git a/0279-perfect-squares/NOTES.md b/0279-perfect-squares/NOTES.md new file mode 100644 index 00000000..a4bb801a --- /dev/null +++ b/0279-perfect-squares/NOTES.md @@ -0,0 +1,28 @@ +int sq = j*j; +dp[i] = min(dp[i], 1 + dp[i-sq]); +} +} +return dp[n]; +} +}; +​ +Legendres's Theorem +​ +class Solution { +public: +int numSquares(int n) { +if(ceil(sqrt(n)) == floor(sqrt(n))) +return 1; +while(n%4 == 0) +n /= 4; +if(n%8 == 7) +return 4; +for(int i = 1; i*i <= n; ++i){ +int base = sqrt(n - (i*i)); +if((base * base) == (n - (i*i))) +return 2; +} +return 3; +} +}; +``` \ No newline at end of file diff --git a/0279-perfect-squares/README.md b/0279-perfect-squares/README.md new file mode 100644 index 00000000..cfd0d433 --- /dev/null +++ b/0279-perfect-squares/README.md @@ -0,0 +1,26 @@ +

279. Perfect Squares

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: n = 12
+Output: 3
+Explanation: 12 = 4 + 4 + 4.
+
+ +

Example 2:

+ +
Input: n = 13
+Output: 2
+Explanation: 13 = 4 + 9.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
+
\ No newline at end of file diff --git a/0283-move-zeroes/0283-move-zeroes.cpp b/0283-move-zeroes/0283-move-zeroes.cpp new file mode 100644 index 00000000..6f52d9f3 --- /dev/null +++ b/0283-move-zeroes/0283-move-zeroes.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + + int n = nums.size(); + + int start = 0; + + for(int i = 0; i < n; ++i) + { + if(nums[i] != 0) + { + swap(nums[i], nums[start++]); + } + } + + } +}; \ No newline at end of file diff --git a/0283-move-zeroes/NOTES.md b/0283-move-zeroes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0283-move-zeroes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0283-move-zeroes/README.md b/0283-move-zeroes/README.md new file mode 100644 index 00000000..4867dc0c --- /dev/null +++ b/0283-move-zeroes/README.md @@ -0,0 +1,22 @@ +

283. Move Zeroes

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [0,1,0,3,12]
+Output: [1,3,12,0,0]
+

Example 2:

+
Input: nums = [0]
+Output: [0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you minimize the total number of operations done?
\ No newline at end of file diff --git a/0287-find-the-duplicate-number/0287-find-the-duplicate-number.cpp b/0287-find-the-duplicate-number/0287-find-the-duplicate-number.cpp new file mode 100644 index 00000000..7876c293 --- /dev/null +++ b/0287-find-the-duplicate-number/0287-find-the-duplicate-number.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + + int fast = nums[0]; + int slow = nums[0]; + + do{ + fast = nums[nums[fast]]; + slow = nums[slow]; + } while(fast != slow); + + fast = nums[0]; + + while(fast != slow) + { + fast = nums[fast]; + slow = nums[slow]; + } + + return fast; + + } +}; \ No newline at end of file diff --git a/0287-find-the-duplicate-number/NOTES.md b/0287-find-the-duplicate-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0287-find-the-duplicate-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0287-find-the-duplicate-number/README.md b/0287-find-the-duplicate-number/README.md new file mode 100644 index 00000000..9394e105 --- /dev/null +++ b/0287-find-the-duplicate-number/README.md @@ -0,0 +1,37 @@ +

287. Find the Duplicate Number

Medium


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

You must solve the problem without modifying the array nums and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,2,2]
+Output: 2
+
+ +

Example 2:

+ +
Input: nums = [3,1,3,4,2]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem in linear runtime complexity?
  • +
+
\ No newline at end of file diff --git a/0289-game-of-life/0289-game-of-life.cpp b/0289-game-of-life/0289-game-of-life.cpp new file mode 100644 index 00000000..eec57c7c --- /dev/null +++ b/0289-game-of-life/0289-game-of-life.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + void gameOfLife(vector>& board) { + + vector dx = {-1, -1, -1, 0, 0, +1, +1, +1}; + vector dy = {-1, 0, +1, -1, +1, -1, 0, +1}; + + int n = board.size(); + int m = board[0].size(); + + set> st; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(board[i][j]) + st.insert({i, j}); + } + } + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + int alive = 0; + int dead = 0; + + for(int k = 0; k < 8; ++k) + { + int newx = i + dx[k]; + int newy = j + dy[k]; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m) + { + if(st.count({newx, newy})) + ++alive; + else + ++dead; + } + } + if(st.count({i, j})) + { + if(alive < 2 or alive > 3) + board[i][j] = 0; + } + else + { + if(alive == 3) + board[i][j] = 1; + } + } + } + } +}; \ No newline at end of file diff --git a/0289-game-of-life/NOTES.md b/0289-game-of-life/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0289-game-of-life/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0289-game-of-life/README.md b/0289-game-of-life/README.md new file mode 100644 index 00000000..4d231fac --- /dev/null +++ b/0289-game-of-life/README.md @@ -0,0 +1,44 @@ +

289. Game of Life

Medium


According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

+ +

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

+ +
    +
  1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
  2. +
  3. Any live cell with two or three live neighbors lives on to the next generation.
  4. +
  5. Any live cell with more than three live neighbors dies, as if by over-population.
  6. +
  7. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
  8. +
+ +

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

+ +

 

+

Example 1:

+ +
Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
+Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
+
+ +

Example 2:

+ +
Input: board = [[1,1],[1,0]]
+Output: [[1,1],[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 25
  • +
  • board[i][j] is 0 or 1.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
  • +
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
  • +
+
\ No newline at end of file diff --git a/0290-word-pattern/0290-word-pattern.cpp b/0290-word-pattern/0290-word-pattern.cpp new file mode 100644 index 00000000..1c1b3f23 --- /dev/null +++ b/0290-word-pattern/0290-word-pattern.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + bool wordPattern(string pattern, string s) { + + int count = 0; + stringstream ss(s); + vector words; + string word; + + int n = pattern.size(); + + while (ss >> word) + words.push_back(word); + + if(n != words.size()) + return false; + + unordered_map mp1; + unordered_map mp2; + + for(int i = 0; i290. Word Pattern

Easy


Given a pattern and a string s, find if s follows the same pattern.

+ +

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

+ +

 

+

Example 1:

+ +
Input: pattern = "abba", s = "dog cat cat dog"
+Output: true
+
+ +

Example 2:

+ +
Input: pattern = "abba", s = "dog cat cat fish"
+Output: false
+
+ +

Example 3:

+ +
Input: pattern = "aaaa", s = "dog cat cat dog"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pattern.length <= 300
  • +
  • pattern contains only lower-case English letters.
  • +
  • 1 <= s.length <= 3000
  • +
  • s contains only lowercase English letters and spaces ' '.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • All the words in s are separated by a single space.
  • +
+
\ No newline at end of file diff --git a/0295-find-median-from-data-stream/0295-find-median-from-data-stream.cpp b/0295-find-median-from-data-stream/0295-find-median-from-data-stream.cpp new file mode 100644 index 00000000..b21b83b7 --- /dev/null +++ b/0295-find-median-from-data-stream/0295-find-median-from-data-stream.cpp @@ -0,0 +1,52 @@ +class MedianFinder { +public: + + priority_queue maxHeap; + priority_queue, greater> minHeap; + + MedianFinder() { + + } + + void addNum(int num) { + if(maxHeap.empty() and minHeap.empty()) + maxHeap.push(num); + else if(num > maxHeap.top()) + minHeap.push(num); + else + maxHeap.push(num); + + int n = maxHeap.size(); + int m = minHeap.size(); + + if(abs(n-m) == 2) + { + if(n > m) + { + minHeap.push(maxHeap.top()); + maxHeap.pop(); + } + else + { + maxHeap.push(minHeap.top()); + minHeap.pop(); + } + } + } + + double findMedian() { + if(maxHeap.size() == minHeap.size()) + return (maxHeap.top() + minHeap.top()) / 2.0; + else if(maxHeap.size() > minHeap.size()) + return maxHeap.top(); + else + return minHeap.top(); + } +}; + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder* obj = new MedianFinder(); + * obj->addNum(num); + * double param_2 = obj->findMedian(); + */ \ No newline at end of file diff --git a/0295-find-median-from-data-stream/README.md b/0295-find-median-from-data-stream/README.md new file mode 100644 index 00000000..40d10740 --- /dev/null +++ b/0295-find-median-from-data-stream/README.md @@ -0,0 +1,50 @@ +

295. Find Median from Data Stream

Hard


The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

+ +
    +
  • For example, for arr = [2,3,4], the median is 3.
  • +
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
  • +
+ +

Implement the MedianFinder class:

+ +
    +
  • MedianFinder() initializes the MedianFinder object.
  • +
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • +
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
+[[], [1], [2], [], [3], []]
+Output
+[null, null, null, 1.5, null, 2.0]
+
+Explanation
+MedianFinder medianFinder = new MedianFinder();
+medianFinder.addNum(1);    // arr = [1]
+medianFinder.addNum(2);    // arr = [1, 2]
+medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
+medianFinder.addNum(3);    // arr[1, 2, 3]
+medianFinder.findMedian(); // return 2.0
+
+ +

 

+

Constraints:

+ +
    +
  • -105 <= num <= 105
  • +
  • There will be at least one element in the data structure before calling findMedian.
  • +
  • At most 5 * 104 calls will be made to addNum and findMedian.
  • +
+ +

 

+

Follow up:

+ +
    +
  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
+
\ No newline at end of file diff --git a/0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.cpp b/0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.cpp new file mode 100644 index 00000000..dbb79fcc --- /dev/null +++ b/0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.cpp @@ -0,0 +1,35 @@ +class Solution { + +private: + int helper(int idx, int prev, int n, vector& nums, vector>& dp) + { + if(idx == n) + return 0; + + if(dp[idx][prev+1] != -1) + { + return dp[idx][prev+1]; + } + + int notTake = helper(idx+1, prev, n, nums, dp); + + int take = 0; + + if(prev == -1 or nums[idx] > nums[prev]) + take = 1 + helper(idx+1, idx, n, nums, dp); + + return dp[idx][prev+1] = max(take, notTake); + } + + +public: + int lengthOfLIS(vector& nums) { + + int n = nums.size(); + + vector> dp(n+1, vector(n+1, -1)); + + return helper(0, -1, n, nums, dp); + + } +}; \ No newline at end of file diff --git a/0300-longest-increasing-subsequence/NOTES.md b/0300-longest-increasing-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0300-longest-increasing-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0300-longest-increasing-subsequence/README.md b/0300-longest-increasing-subsequence/README.md new file mode 100644 index 00000000..74241c8e --- /dev/null +++ b/0300-longest-increasing-subsequence/README.md @@ -0,0 +1,33 @@ +

300. Longest Increasing Subsequence

Medium


Given an integer array nums, return the length of the longest strictly increasing subsequence.

+ +

 

+

Example 1:

+ +
Input: nums = [10,9,2,5,3,7,101,18]
+Output: 4
+Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
+
+ +

Example 2:

+ +
Input: nums = [0,1,0,3,2,3]
+Output: 4
+
+ +

Example 3:

+ +
Input: nums = [7,7,7,7,7,7,7]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2500
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

+
\ No newline at end of file diff --git a/0307-range-sum-query-mutable/0307-range-sum-query-mutable.cpp b/0307-range-sum-query-mutable/0307-range-sum-query-mutable.cpp new file mode 100644 index 00000000..0f5e7e2a --- /dev/null +++ b/0307-range-sum-query-mutable/0307-range-sum-query-mutable.cpp @@ -0,0 +1,121 @@ +class NumArray { +public: + + public: + void buildTree(int idx, int low, int high) + { + if (low == high) + { + tree[idx] = arr[low]; + return; + } + + int mid = (low + high) >> 1; + buildTree(2 * idx + 1, low, mid); + buildTree(2 * idx + 2, mid + 1, high); + + // updation part + + // sum + tree[idx] = tree[2 * idx + 1] + tree[2 * idx + 2]; + + // min + // tree[idx] = min(tree[2 * idx + 1], tree[2 * idx + 2]); + return; + } + + public: + int queryTree(int idx, int low, int high, int l, int r) + { + // no overlap + // l r low high or low high l r + if (r < low or l > high) + return 0; + // return INT_MAX; // min + + // complete overlap + // [l low high r] + if (low >= l and high <= r) + return tree[idx]; + + // partial overlap + int mid = (low + high) / 2; + int left = queryTree(2 * idx + 1, low, mid, l, r); + int right = queryTree(2 * idx + 2, mid + 1, high, l, r); + + // updation part + // sum + + return left + right; + + // min + // return min(left, right); + } + +public: + void updateTree(int idx, int low, int high, int ind, int val) + { + if (low == high) + { + // sum ranges increment tree[idx] by val case + // tree[idx] += val; + + // min and update single value case + tree[idx] = val; + return; + } + int mid = (low + high) >> 1; + if (ind <= mid) + updateTree(2 * idx + 1, low, mid, ind, val); + else + updateTree(2 * idx + 2, mid + 1, high, ind, val); + + // updation Part + // sum + + tree[idx] = tree[2 * idx + 1] + tree[2 * idx + 2]; + + // min + + // tree[idx] = min(tree[2 * idx + 1], tree[2 * idx + 2]); + } + + void build() + { + buildTree(0, 0, N - 1); + } + + int query(int l, int r) + { + return queryTree(0, 0, N - 1, l, r); + } + + void Update(int ind, int val) + { + updateTree(0, 0, N - 1, ind, val); + } + + vector tree, arr; + int N; + NumArray(vector& nums) { + N = nums.size(); + arr = nums; + tree.resize(N*4 + 5); + build(); + } + + void update(int index, int val) { + Update(index,val); + } + + int sumRange(int left, int right) { + return query(left, right); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); + */ \ No newline at end of file diff --git a/0307-range-sum-query-mutable/NOTES.md b/0307-range-sum-query-mutable/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0307-range-sum-query-mutable/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0307. Range Sum Query - Mutable.cpp b/0307. Range Sum Query - Mutable.cpp new file mode 100644 index 00000000..ffd454f5 --- /dev/null +++ b/0307. Range Sum Query - Mutable.cpp @@ -0,0 +1,127 @@ +class NumArray +{ +public: + int arr[100005], seg[100005 * 4]; // for segment Tree + vector ans; + + void build(int ind, int low, int high) + { + if (high == low) + { + seg[ind] = arr[low]; + return; + } + int mid = (low + high) / 2; + build(2 * ind + 1, low, mid); + build(2 * ind + 2, mid + 1, high); + + // find max in range + // seg[ind] = max(seg[2 * ind + 1],seg[2 * ind + 2]); + + // find sum in range + seg[ind] = seg[2 * ind + 1] + seg[2 * ind + 2]; + } + + int query(int ind, int low, int high, int l, int r) + { + if (low >= l && high <= r) // [ 1 - 1 ] + return seg[ind]; + + if (high < l || low > r) + // return INT_MIN; ( when we doing for max) + return 0; + + int mid = (low + high) / 2; + int left = query(2 * ind + 1, low, mid, l, r); + int right = query(2 * ind + 2, mid + 1, high, l, r); + // return max(left, right); + return left + right; + } + + void updateSeg(int idx, int low, int high, int index, int val) + { + // no overlap + if (index < low || index > high) + return; + + // total overlap + if (low == high) + { + if (low == index) + seg[idx] = val; + return; + } + + // partial overlap + int mid = (low + high) / 2; + updateSeg(2 * idx + 1, low, mid, index, val); // low child + updateSeg(2 * idx + 2, mid + 1, high, index, val); // high child + seg[idx] = seg[2 * idx + 1] + seg[2 * idx + 2]; + } + + NumArray(vector &nums) + { + ans = nums; + for (int i = 0; i < nums.size(); ++i) + arr[i] = nums[i]; + build(0, 0, nums.size() - 1); + } + + void update(int index, int val) + { + updateSeg(0, 0, ans.size() - 1, index, val); + } + + int sumRange(int left, int right) + { + return query(0, 0, ans.size() - 1, left, right); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); + */ + +// Another Approach + +class NumArray +{ +public: + vector ans; + int sum = 0; + NumArray(vector &nums) + { + sum = 0; + ans = nums; + for (int i = 0; i < nums.size(); ++i) + { + sum += nums[i]; + } + } + + void update(int index, int val) + { + sum -= ans[index]; + ans[index] = val; + sum += val; + } + + int sumRange(int left, int right) + { + int res = sum; + + for (int i = 0; i < left; ++i) + { + res -= ans[i]; + } + for (int i = right + 1; i < ans.size(); ++i) + { + res -= ans[i]; + } + + return res; + } +}; diff --git a/0309-best-time-to-buy-and-sell-stock-with-cooldown/0309-best-time-to-buy-and-sell-stock-with-cooldown.cpp b/0309-best-time-to-buy-and-sell-stock-with-cooldown/0309-best-time-to-buy-and-sell-stock-with-cooldown.cpp new file mode 100644 index 00000000..3f431264 --- /dev/null +++ b/0309-best-time-to-buy-and-sell-stock-with-cooldown/0309-best-time-to-buy-and-sell-stock-with-cooldown.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + + int helper(int index, int buy, vector& prices, vector>& dp) + { + if(index >= prices.size()) + return 0; + if(dp[index][buy] != -1) + return dp[index][buy]; + if(buy) + return dp[index][buy] = max(-prices[index] + helper(index+1,0,prices ,dp), helper(index+1, 1,prices,dp)); + return dp[index][buy] = max(prices[index] + helper(index+2,1,prices, dp), helper(index+1,0,prices ,dp)); + } + + int maxProfit(vector& prices) { + + int n = prices.size(); + vector> dp(n,vector(2,-1)); + + return helper(0,1,prices,dp); + } +}; \ No newline at end of file diff --git a/0309-best-time-to-buy-and-sell-stock-with-cooldown/NOTES.md b/0309-best-time-to-buy-and-sell-stock-with-cooldown/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0309-best-time-to-buy-and-sell-stock-with-cooldown/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0309-best-time-to-buy-and-sell-stock-with-cooldown/README.md b/0309-best-time-to-buy-and-sell-stock-with-cooldown/README.md new file mode 100644 index 00000000..38466a8b --- /dev/null +++ b/0309-best-time-to-buy-and-sell-stock-with-cooldown/README.md @@ -0,0 +1,32 @@ +

309. Best Time to Buy and Sell Stock with Cooldown

Medium


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

+ +
    +
  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
  • +
+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [1,2,3,0,2]
+Output: 3
+Explanation: transactions = [buy, sell, cooldown, buy, sell]
+
+ +

Example 2:

+ +
Input: prices = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 5000
  • +
  • 0 <= prices[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/0310-minimum-height-trees/0310-minimum-height-trees.cpp b/0310-minimum-height-trees/0310-minimum-height-trees.cpp new file mode 100644 index 00000000..075848c2 --- /dev/null +++ b/0310-minimum-height-trees/0310-minimum-height-trees.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + vector> graph(n); + vector indegree(n, 0), ans; + + for(auto &e : edges){ + graph[e[0]].push_back(e[1]); + graph[e[1]].push_back(e[0]); + indegree[e[0]]++; + indegree[e[1]]++; + } + + queue q; + for(int i=0; i310. Minimum Height Trees

Medium


A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

+ +

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

+ +

Return a list of all MHTs' root labels. You can return the answer in any order.

+ +

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

+ +

 

+

Example 1:

+ +
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
+Output: [1]
+Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
+
+ +

Example 2:

+ +
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
+Output: [3,4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 104
  • +
  • edges.length == n - 1
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • All the pairs (ai, bi) are distinct.
  • +
  • The given input is guaranteed to be a tree and there will be no repeated edges.
  • +
+
\ No newline at end of file diff --git a/0312-burst-balloons/0312-burst-balloons.cpp b/0312-burst-balloons/0312-burst-balloons.cpp new file mode 100644 index 00000000..17a0993a --- /dev/null +++ b/0312-burst-balloons/0312-burst-balloons.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + + int helper(int i, int j, vector& nums, vector >& dp) + { + if(i > j) + return 0; + if(dp[i][j] != -1) + return dp[i][j]; + int maxi = INT_MIN; + for(int idx = i; idx <= j; ++idx) + { + int cost = nums[i-1] * nums[idx] * nums[j+1] + helper(i, idx - 1, nums, dp) + helper(idx + 1, j, nums , dp); + maxi = max(maxi, cost); + } + + return dp[i][j] = maxi; + } + + + int maxCoins(vector& nums) { + + int n = nums.size(); + nums.push_back(1); + nums.insert(nums.begin(),1); + + + // vector >dp(n+1,vector(n+1,-1)); + // return helper(1,n, nums, dp); + + vector> dp(n+2,vector(n+2,0)); + + for(int i = n; i >= 1; --i) + { + for(int j = 1; j<=n; ++j) + { + if(i > j) + continue; + int maxi = INT_MIN; + for(int idx = i; idx <= j; ++idx) + { + int cost = nums[i-1] * nums[idx] * nums[j+1] + dp[i][idx-1] + dp[idx+1][j]; + maxi = max(maxi, cost); + } + + dp[i][j] = maxi; + } + } + + return dp[1][n]; + } +}; \ No newline at end of file diff --git a/0312-burst-balloons/NOTES.md b/0312-burst-balloons/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0312-burst-balloons/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0312-burst-balloons/README.md b/0312-burst-balloons/README.md new file mode 100644 index 00000000..22efd541 --- /dev/null +++ b/0312-burst-balloons/README.md @@ -0,0 +1,30 @@ +

312. Burst Balloons

Hard


You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

+ +

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

+ +

Return the maximum coins you can collect by bursting the balloons wisely.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,5,8]
+Output: 167
+Explanation:
+nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
+coins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167
+ +

Example 2:

+ +
Input: nums = [1,5]
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • 0 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0319-bulb-switcher/0319-bulb-switcher.cpp b/0319-bulb-switcher/0319-bulb-switcher.cpp new file mode 100644 index 00000000..d1f9e968 --- /dev/null +++ b/0319-bulb-switcher/0319-bulb-switcher.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int bulbSwitch(int n) { + + return sqrt(n); + + } +}; \ No newline at end of file diff --git a/0319-bulb-switcher/README.md b/0319-bulb-switcher/README.md new file mode 100644 index 00000000..03dde920 --- /dev/null +++ b/0319-bulb-switcher/README.md @@ -0,0 +1,36 @@ +

319. Bulb Switcher

Medium


There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

+ +

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.

+ +

Return the number of bulbs that are on after n rounds.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 1
+Explanation: At first, the three bulbs are [off, off, off].
+After the first round, the three bulbs are [on, on, on].
+After the second round, the three bulbs are [on, off, on].
+After the third round, the three bulbs are [on, off, off]. 
+So you should return 1 because there is only one bulb is on.
+ +

Example 2:

+ +
Input: n = 0
+Output: 0
+
+ +

Example 3:

+ +
Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 109
  • +
+
\ No newline at end of file diff --git a/0322-coin-change/0322-coin-change.cpp b/0322-coin-change/0322-coin-change.cpp new file mode 100644 index 00000000..851c27a3 --- /dev/null +++ b/0322-coin-change/0322-coin-change.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + + int n = coins.size(); + + vector prev(amount+1,0), curr(amount+1, 0); + + for(int i = 0; i <= amount; ++i) + { + prev[i] = (i % coins[n-1] == 0 ? i/coins[n-1] : 1e9); + } + + for(int i = n-2; i >= 0; --i) + { + for(int j = 0; j <= amount; ++j) + { + int notTake = prev[j]; + + int take = INT_MAX; + + if(coins[i] <= j) + take = 1 + curr[j-coins[i]]; + + curr[j] = min(take, notTake); + } + prev = curr; + } + + return (prev[amount] >= 1e9 ? -1 : prev[amount]); + } +}; \ No newline at end of file diff --git a/0322-coin-change/NOTES.md b/0322-coin-change/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0322-coin-change/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0322-coin-change/README.md b/0322-coin-change/README.md new file mode 100644 index 00000000..6aa78759 --- /dev/null +++ b/0322-coin-change/README.md @@ -0,0 +1,35 @@ +

322. Coin Change

Medium


You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

+ +

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

+ +

You may assume that you have an infinite number of each kind of coin.

+ +

 

+

Example 1:

+ +
Input: coins = [1,2,5], amount = 11
+Output: 3
+Explanation: 11 = 5 + 5 + 1
+
+ +

Example 2:

+ +
Input: coins = [2], amount = 3
+Output: -1
+
+ +

Example 3:

+ +
Input: coins = [1], amount = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= coins.length <= 12
  • +
  • 1 <= coins[i] <= 231 - 1
  • +
  • 0 <= amount <= 104
  • +
+
\ No newline at end of file diff --git a/0324-wiggle-sort-ii/0324-wiggle-sort-ii.cpp b/0324-wiggle-sort-ii/0324-wiggle-sort-ii.cpp new file mode 100644 index 00000000..b49df90a --- /dev/null +++ b/0324-wiggle-sort-ii/0324-wiggle-sort-ii.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + void wiggleSort(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + vector ans(n); + + int k = n-1; + + for(int i = 1; i < n; i += 2) + { + ans[i] = nums[k--]; + } + + for(int i = 0; i < n; i += 2) + { + ans[i] = nums[k--]; + } + + nums = ans; + } +}; \ No newline at end of file diff --git a/0324-wiggle-sort-ii/NOTES.md b/0324-wiggle-sort-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0324-wiggle-sort-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0324-wiggle-sort-ii/README.md b/0324-wiggle-sort-ii/README.md new file mode 100644 index 00000000..ae6f43d0 --- /dev/null +++ b/0324-wiggle-sort-ii/README.md @@ -0,0 +1,29 @@ +

324. Wiggle Sort II

Medium


Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

+ +

You may assume the input array always has a valid answer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,5,1,1,6,4]
+Output: [1,6,1,5,1,4]
+Explanation: [1,4,1,5,1,6] is also accepted.
+
+ +

Example 2:

+ +
Input: nums = [1,3,2,2,3,1]
+Output: [2,3,1,3,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 0 <= nums[i] <= 5000
  • +
  • It is guaranteed that there will be an answer for the given input nums.
  • +
+ +

 

+Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
\ No newline at end of file diff --git a/0330-patching-array/0330-patching-array.cpp b/0330-patching-array/0330-patching-array.cpp new file mode 100644 index 00000000..ae09c27a --- /dev/null +++ b/0330-patching-array/0330-patching-array.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int minPatches(vector& nums, int n) { + + long long maxReach = 0; + int patch = 0, i = 0; + + while(maxReach < n) + { + if(i < nums.size() and nums[i] <= maxReach + 1) + { + maxReach += nums[i]; + ++i; + } + else + { + ++patch; + maxReach += (maxReach + 1); + } + } + + return patch; + + } +}; \ No newline at end of file diff --git a/0330-patching-array/README.md b/0330-patching-array/README.md new file mode 100644 index 00000000..fcebede2 --- /dev/null +++ b/0330-patching-array/README.md @@ -0,0 +1,39 @@ +

330. Patching Array

Hard


Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.

+ +

Return the minimum number of patches required.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3], n = 6
+Output: 1
+Explanation:
+Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
+Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
+Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
+So we only need 1 patch.
+
+ +

Example 2:

+ +
Input: nums = [1,5,10], n = 20
+Output: 2
+Explanation: The two patches can be [2, 4].
+
+ +

Example 3:

+ +
Input: nums = [1,2,2], n = 5
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 104
  • +
  • nums is sorted in ascending order.
  • +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0332-reconstruct-itinerary/0332-reconstruct-itinerary.cpp b/0332-reconstruct-itinerary/0332-reconstruct-itinerary.cpp new file mode 100644 index 00000000..9f9058ab --- /dev/null +++ b/0332-reconstruct-itinerary/0332-reconstruct-itinerary.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + + unordered_map,greater>> map; + vector ans; + void dfs(string s) + { + auto &x=map[s]; + while(!x.empty()) + { + string to=x.top(); + x.pop(); + dfs(to); + } + cout< findItinerary(vector>& tickets) { + for(auto &x:tickets) + map[x[0]].push(x[1]); + dfs("JFK"); + reverse(ans.begin(),ans.end()); + return ans; + } +}; + + + \ No newline at end of file diff --git a/0332-reconstruct-itinerary/README.md b/0332-reconstruct-itinerary/README.md new file mode 100644 index 00000000..732c4175 --- /dev/null +++ b/0332-reconstruct-itinerary/README.md @@ -0,0 +1,36 @@ +

332. Reconstruct Itinerary

Hard


You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

+ +

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

+ +
    +
  • For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  • +
+ +

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

+ +

 

+

Example 1:

+ +
Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
+Output: ["JFK","MUC","LHR","SFO","SJC"]
+
+ +

Example 2:

+ +
Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
+Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
+Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tickets.length <= 300
  • +
  • tickets[i].length == 2
  • +
  • fromi.length == 3
  • +
  • toi.length == 3
  • +
  • fromi and toi consist of uppercase English letters.
  • +
  • fromi != toi
  • +
+
\ No newline at end of file diff --git a/0338-counting-bits/0338-counting-bits.cpp b/0338-counting-bits/0338-counting-bits.cpp new file mode 100644 index 00000000..ae3d944b --- /dev/null +++ b/0338-counting-bits/0338-counting-bits.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector countBits(int n) { + + vector dp(n+1, 0); + + dp[0] = 0; + + for(int i = 1; i <= n; ++i) + { + dp[i] = dp[i/2] + i%2; + } + + return dp; + } +}; \ No newline at end of file diff --git a/0338-counting-bits/NOTES.md b/0338-counting-bits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0338-counting-bits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0338-counting-bits/README.md b/0338-counting-bits/README.md new file mode 100644 index 00000000..6ee2a914 --- /dev/null +++ b/0338-counting-bits/README.md @@ -0,0 +1,41 @@ +

338. Counting Bits

Easy


Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: [0,1,1]
+Explanation:
+0 --> 0
+1 --> 1
+2 --> 10
+
+ +

Example 2:

+ +
Input: n = 5
+Output: [0,1,1,2,1,2]
+Explanation:
+0 --> 0
+1 --> 1
+2 --> 10
+3 --> 11
+4 --> 100
+5 --> 101
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
  • +
  • Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
  • +
+
\ No newline at end of file diff --git a/0341-flatten-nested-list-iterator/0341-flatten-nested-list-iterator.cpp b/0341-flatten-nested-list-iterator/0341-flatten-nested-list-iterator.cpp new file mode 100644 index 00000000..f450d064 --- /dev/null +++ b/0341-flatten-nested-list-iterator/0341-flatten-nested-list-iterator.cpp @@ -0,0 +1,57 @@ +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ + +class NestedIterator { +public: + + vector v; + int k = 0; + + void helper(vector& nestedList) + { + for(auto& itr : nestedList) + { + if(itr.isInteger()) + v.push_back(itr.getInteger()); + else + helper(itr.getList()); + } + } + + NestedIterator(vector &nestedList) { + + helper(nestedList); + + } + + int next() { + int ans = v[k]; + ++k; + return ans; + } + + bool hasNext() { + return k < v.size(); + } +}; + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i(nestedList); + * while (i.hasNext()) cout << i.next(); + */ \ No newline at end of file diff --git a/0341-flatten-nested-list-iterator/NOTES.md b/0341-flatten-nested-list-iterator/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0341-flatten-nested-list-iterator/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0341-flatten-nested-list-iterator/README.md b/0341-flatten-nested-list-iterator/README.md new file mode 100644 index 00000000..be9109a3 --- /dev/null +++ b/0341-flatten-nested-list-iterator/README.md @@ -0,0 +1,44 @@ +

341. Flatten Nested List Iterator

Medium


You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

+ +

Implement the NestedIterator class:

+ +
    +
  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • +
  • int next() Returns the next integer in the nested list.
  • +
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
  • +
+ +

Your code will be tested with the following pseudocode:

+ +
initialize iterator with nestedList
+res = []
+while iterator.hasNext()
+    append iterator.next() to the end of res
+return res
+
+ +

If res matches the expected flattened list, then your code will be judged as correct.

+ +

 

+

Example 1:

+ +
Input: nestedList = [[1,1],2,[1,1]]
+Output: [1,1,2,1,1]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
+
+ +

Example 2:

+ +
Input: nestedList = [1,[4,[6]]]
+Output: [1,4,6]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nestedList.length <= 500
  • +
  • The values of the integers in the nested list is in the range [-106, 106].
  • +
+
\ No newline at end of file diff --git a/0342-power-of-four/0342-power-of-four.cpp b/0342-power-of-four/0342-power-of-four.cpp new file mode 100644 index 00000000..eb1b35f2 --- /dev/null +++ b/0342-power-of-four/0342-power-of-four.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + + bool helper(int n) + { + if(n <= 0) + return false; + + if(n == 1) + return true; + + if(n % 4 == 0) + return helper(n/4); + + return false; + } + + bool isPowerOfFour(int n) { + return helper(n); + } +}; \ No newline at end of file diff --git a/0342-power-of-four/NOTES.md b/0342-power-of-four/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0342-power-of-four/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0342-power-of-four/README.md b/0342-power-of-four/README.md new file mode 100644 index 00000000..e5dba89e --- /dev/null +++ b/0342-power-of-four/README.md @@ -0,0 +1,24 @@ +

342. Power of Four

Easy


Given an integer n, return true if it is a power of four. Otherwise, return false.

+ +

An integer n is a power of four, if there exists an integer x such that n == 4x.

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/0343-integer-break/0343-integer-break.cpp b/0343-integer-break/0343-integer-break.cpp new file mode 100644 index 00000000..23c42f94 --- /dev/null +++ b/0343-integer-break/0343-integer-break.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + + int helper(int idx, int sum, int n, vector>& dp) + { + if(sum == 0) + return 1; + + if(sum < 0 or idx >= n) + return 0; + + if(dp[idx][sum] != -1) + return dp[idx][sum]; + + int res = helper(idx+1, sum, n, dp); + + dp[idx][sum] = res = max(res, idx * helper(idx, sum-idx, n, dp)); + + return res; + } + + int integerBreak(int n) { + + vector> dp(n+1, vector(n+1, -1)); + + return helper(1, n, n, dp); + + } +}; \ No newline at end of file diff --git a/0343-integer-break/NOTES.md b/0343-integer-break/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0343-integer-break/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0343-integer-break/README.md b/0343-integer-break/README.md new file mode 100644 index 00000000..eeb0e4fa --- /dev/null +++ b/0343-integer-break/README.md @@ -0,0 +1,26 @@ +

343. Integer Break

Medium


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

+ +

Return the maximum product you can get.

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: 2 = 1 + 1, 1 × 1 = 1.
+
+ +

Example 2:

+ +
Input: n = 10
+Output: 36
+Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 58
  • +
+
\ No newline at end of file diff --git a/0344-reverse-string/0344-reverse-string.cpp b/0344-reverse-string/0344-reverse-string.cpp new file mode 100644 index 00000000..c1441fef --- /dev/null +++ b/0344-reverse-string/0344-reverse-string.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + void reverseString(vector& s) { + + int n = s.size(); + + for(int i = 0; i < n/2; ++i) + swap(s[i], s[n-i-1]); + + } +}; \ No newline at end of file diff --git a/0344-reverse-string/NOTES.md b/0344-reverse-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0344-reverse-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0344-reverse-string/README.md b/0344-reverse-string/README.md new file mode 100644 index 00000000..5c9b221e --- /dev/null +++ b/0344-reverse-string/README.md @@ -0,0 +1,20 @@ +

344. Reverse String

Easy


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

+ +

You must do this by modifying the input array in-place with O(1) extra memory.

+ +

 

+

Example 1:

+
Input: s = ["h","e","l","l","o"]
+Output: ["o","l","l","e","h"]
+

Example 2:

+
Input: s = ["H","a","n","n","a","h"]
+Output: ["h","a","n","n","a","H"]
+
+

 

+

Constraints:

+ + +
\ No newline at end of file diff --git a/0349-intersection-of-two-arrays/0349-intersection-of-two-arrays.cpp b/0349-intersection-of-two-arrays/0349-intersection-of-two-arrays.cpp new file mode 100644 index 00000000..c4128d15 --- /dev/null +++ b/0349-intersection-of-two-arrays/0349-intersection-of-two-arrays.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + + vector res; + + set have(nums1.begin(),nums1.end()); + + for(auto& ele : nums2) + { + if(have.count(ele)) + { + res.push_back(ele); + have.erase(ele); + } + } + + return res; + } +}; \ No newline at end of file diff --git a/0349-intersection-of-two-arrays/NOTES.md b/0349-intersection-of-two-arrays/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0349-intersection-of-two-arrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0349-intersection-of-two-arrays/README.md b/0349-intersection-of-two-arrays/README.md new file mode 100644 index 00000000..24bc7284 --- /dev/null +++ b/0349-intersection-of-two-arrays/README.md @@ -0,0 +1,24 @@ +

349. Intersection of Two Arrays

Easy


Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,2,1], nums2 = [2,2]
+Output: [2]
+
+ +

Example 2:

+ +
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+Output: [9,4]
+Explanation: [4,9] is also accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/0350-intersection-of-two-arrays-ii/0350-intersection-of-two-arrays-ii.cpp b/0350-intersection-of-two-arrays-ii/0350-intersection-of-two-arrays-ii.cpp new file mode 100644 index 00000000..f0f633ae --- /dev/null +++ b/0350-intersection-of-two-arrays-ii/0350-intersection-of-two-arrays-ii.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + + map mp, mp2; + + vector ans; + + for(auto& ele : nums1) + { + ++mp[ele]; + } + + for(auto& ele : nums2) + { + ++mp2[ele]; + } + + for(auto&[f,e] : mp) + { + if(mp2.find(f) != mp2.end()) + { + for(int i = 0; i < min(e, mp2[f]); ++i) + ans.push_back(f); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0350-intersection-of-two-arrays-ii/README.md b/0350-intersection-of-two-arrays-ii/README.md new file mode 100644 index 00000000..20f1306d --- /dev/null +++ b/0350-intersection-of-two-arrays-ii/README.md @@ -0,0 +1,33 @@ +

350. Intersection of Two Arrays II

Easy


Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,2,1], nums2 = [2,2]
+Output: [2,2]
+
+ +

Example 2:

+ +
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+Output: [4,9]
+Explanation: [9,4] is also accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 1000
  • +
+ +

 

+

Follow up:

+ +
    +
  • What if the given array is already sorted? How would you optimize your algorithm?
  • +
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • +
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
  • +
+
\ No newline at end of file diff --git a/0352-data-stream-as-disjoint-intervals/0352-data-stream-as-disjoint-intervals.cpp b/0352-data-stream-as-disjoint-intervals/0352-data-stream-as-disjoint-intervals.cpp new file mode 100644 index 00000000..594a7e0d --- /dev/null +++ b/0352-data-stream-as-disjoint-intervals/0352-data-stream-as-disjoint-intervals.cpp @@ -0,0 +1,47 @@ +class SummaryRanges { +public: + + set s; + + SummaryRanges() { + + } + + void addNum(int value) { + s.insert(value); + } + + vector> getIntervals() { + + vector> res; + + int start = -1, end = -1; + for(auto itr : s) + { + if(start == -1 and end == -1) + { + start = itr, end = itr; + } + end = itr; + if(s.find(itr + 1) == s.end()) + { + res.push_back({start,end}); + start = -1, end = -1; + } + else + { + continue; + } + } + + return res; + + } +}; + +/** + * Your SummaryRanges object will be instantiated and called as such: + * SummaryRanges* obj = new SummaryRanges(); + * obj->addNum(value); + * vector> param_2 = obj->getIntervals(); + */ \ No newline at end of file diff --git a/0352-data-stream-as-disjoint-intervals/README.md b/0352-data-stream-as-disjoint-intervals/README.md new file mode 100644 index 00000000..40fda598 --- /dev/null +++ b/0352-data-stream-as-disjoint-intervals/README.md @@ -0,0 +1,44 @@ +

352. Data Stream as Disjoint Intervals

Hard


Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.

+ +

Implement the SummaryRanges class:

+ +
    +
  • SummaryRanges() Initializes the object with an empty stream.
  • +
  • void addNum(int value) Adds the integer value to the stream.
  • +
  • int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. The answer should be sorted by starti.
  • +
+ +

 

+

Example 1:

+ +
Input
+["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
+[[], [1], [], [3], [], [7], [], [2], [], [6], []]
+Output
+[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
+
+Explanation
+SummaryRanges summaryRanges = new SummaryRanges();
+summaryRanges.addNum(1);      // arr = [1]
+summaryRanges.getIntervals(); // return [[1, 1]]
+summaryRanges.addNum(3);      // arr = [1, 3]
+summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
+summaryRanges.addNum(7);      // arr = [1, 3, 7]
+summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
+summaryRanges.addNum(2);      // arr = [1, 2, 3, 7]
+summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
+summaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]
+summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= value <= 104
  • +
  • At most 3 * 104 calls will be made to addNum and getIntervals.
  • +
+ +

 

+

Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?

+
\ No newline at end of file diff --git a/0354-russian-doll-envelopes/NOTES.md b/0354-russian-doll-envelopes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0354-russian-doll-envelopes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0354-russian-doll-envelopes/README.md b/0354-russian-doll-envelopes/README.md new file mode 100644 index 00000000..561fbe15 --- /dev/null +++ b/0354-russian-doll-envelopes/README.md @@ -0,0 +1,31 @@ +

354. Russian Doll Envelopes

Hard


You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

+ +

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

+ +

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

+ +

Note: You cannot rotate an envelope.

+ +

 

+

Example 1:

+ +
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
+Output: 3
+Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
+
+ +

Example 2:

+ +
Input: envelopes = [[1,1],[1,1],[1,1]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= envelopes.length <= 105
  • +
  • envelopes[i].length == 2
  • +
  • 1 <= wi, hi <= 105
  • +
+
\ No newline at end of file diff --git a/0368-largest-divisible-subset/0368-largest-divisible-subset.cpp b/0368-largest-divisible-subset/0368-largest-divisible-subset.cpp new file mode 100644 index 00000000..d5cc332d --- /dev/null +++ b/0368-largest-divisible-subset/0368-largest-divisible-subset.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + + int n = nums.size(); + + vector dp(n+1,1); + vector hash(n); + int lastIndex = -1; + int res = 1; + sort(nums.begin(),nums.end()); + + for(int i = 0; i dp[i]) + { + dp[i] = dp[j] + 1; + hash[i] = j; + } + } + if(dp[i] > res) + { + lastIndex = i; + res = dp[i]; + } + } + if(res == 1) + return {nums[0]}; + vector ans; + ans.push_back(nums[lastIndex]); + + while(hash[lastIndex] != lastIndex) + { + lastIndex = hash[lastIndex]; + ans.push_back(nums[lastIndex]); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0368-largest-divisible-subset/README.md b/0368-largest-divisible-subset/README.md new file mode 100644 index 00000000..ae432a88 --- /dev/null +++ b/0368-largest-divisible-subset/README.md @@ -0,0 +1,32 @@ +

368. Largest Divisible Subset

Medium


Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

+ +
    +
  • answer[i] % answer[j] == 0, or
  • +
  • answer[j] % answer[i] == 0
  • +
+ +

If there are multiple solutions, return any of them.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: [1,2]
+Explanation: [1,3] is also accepted.
+
+ +

Example 2:

+ +
Input: nums = [1,2,4,8]
+Output: [1,2,4,8]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 2 * 109
  • +
  • All the integers in nums are unique.
  • +
+
\ No newline at end of file diff --git a/0373-find-k-pairs-with-smallest-sums/0373-find-k-pairs-with-smallest-sums.cpp b/0373-find-k-pairs-with-smallest-sums/0373-find-k-pairs-with-smallest-sums.cpp new file mode 100644 index 00000000..29d83f55 --- /dev/null +++ b/0373-find-k-pairs-with-smallest-sums/0373-find-k-pairs-with-smallest-sums.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + + int n = nums1.size(); + int m = nums2.size(); + + priority_queue> > pq; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + int sum = nums1[i] + nums2[j]; + + if(pq.size() < k) + { + pq.push({sum, {nums1[i], nums2[j]}}); + } + else if(sum < pq.top().first) + { + pq.pop(); + pq.push({sum, {nums1[i], nums2[j]}}); + } + else + break; + } + } + + vector > ans; + + while(!pq.empty()) + { + int a = pq.top().second.first; + int b = pq.top().second.second; + + ans.push_back({a, b}); + + pq.pop(); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0373-find-k-pairs-with-smallest-sums/README.md b/0373-find-k-pairs-with-smallest-sums/README.md new file mode 100644 index 00000000..97846ec1 --- /dev/null +++ b/0373-find-k-pairs-with-smallest-sums/README.md @@ -0,0 +1,38 @@ +

373. Find K Pairs with Smallest Sums

Medium


You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

+ +

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

+ +

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
+Output: [[1,2],[1,4],[1,6]]
+Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
+
+ +

Example 2:

+ +
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
+Output: [[1,1],[1,1]]
+Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
+
+ +

Example 3:

+ +
Input: nums1 = [1,2], nums2 = [3], k = 3
+Output: [[1,3],[2,3]]
+Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 105
  • +
  • -109 <= nums1[i], nums2[i] <= 109
  • +
  • nums1 and nums2 both are sorted in ascending order.
  • +
  • 1 <= k <= 104
  • +
+
\ No newline at end of file diff --git a/0377-combination-sum-iv/0377-combination-sum-iv.cpp b/0377-combination-sum-iv/0377-combination-sum-iv.cpp new file mode 100644 index 00000000..3aaa86fa --- /dev/null +++ b/0377-combination-sum-iv/0377-combination-sum-iv.cpp @@ -0,0 +1,33 @@ +class Solution { + +private: + int helper(int idx, int sum, vector& nums, int target, vector>& dp) + { + if(idx == nums.size()) + { + return sum == target; + } + + if(dp[idx][sum] != -1) + return dp[idx][sum]; + + int notTake = helper(idx+1, sum, nums, target, dp); + + int take = 0; + + if(sum + nums[idx] <= target) + take = helper(0, sum + nums[idx], nums, target, dp); + + return dp[idx][sum] = take + notTake; + } +public: + int combinationSum4(vector& nums, int target) { + + int n = nums.size(); + + vector> dp(n+1, vector(target+1, -1)); + + return helper(0, 0, nums, target, dp); + + } +}; \ No newline at end of file diff --git a/0377-combination-sum-iv/NOTES.md b/0377-combination-sum-iv/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0377-combination-sum-iv/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0377-combination-sum-iv/README.md b/0377-combination-sum-iv/README.md new file mode 100644 index 00000000..842b55ae --- /dev/null +++ b/0377-combination-sum-iv/README.md @@ -0,0 +1,40 @@ +

377. Combination Sum IV

Medium


Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

+ +

The test cases are generated so that the answer can fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3], target = 4
+Output: 7
+Explanation:
+The possible combination ways are:
+(1, 1, 1, 1)
+(1, 1, 2)
+(1, 2, 1)
+(1, 3)
+(2, 1, 1)
+(2, 2)
+(3, 1)
+Note that different sequences are counted as different combinations.
+
+ +

Example 2:

+ +
Input: nums = [9], target = 3
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= 1000
  • +
  • All the elements of nums are unique.
  • +
  • 1 <= target <= 1000
  • +
+ +

 

+

Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?

+
\ No newline at end of file diff --git a/0377. Combination Sum IV.cpp b/0377. Combination Sum IV.cpp new file mode 100644 index 00000000..69579857 --- /dev/null +++ b/0377. Combination Sum IV.cpp @@ -0,0 +1,30 @@ +// 377.✅ Combination Sum IV + +class Solution +{ +public: + vector dp; + + Solution() + { + dp.resize(1001); + fill(dp.begin(), dp.end(), -1); + } + + int combinationSum4(vector &nums, int target, int currSum = 0) + { + if (currSum > target) + return 0; + if (currSum == target) + return 1; + if (dp[currSum] != -1) + return dp[currSum]; + int ways = 0; + for (int i = 0; i < nums.size(); i++) + { + if (currSum + nums[i] <= target) + ways += combinationSum4(nums, target, currSum + nums[i]); + } + return dp[currSum] = ways; + } +}; \ No newline at end of file diff --git a/0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.cpp b/0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.cpp new file mode 100644 index 00000000..347d6302 --- /dev/null +++ b/0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.cpp @@ -0,0 +1,42 @@ +class RandomizedSet { +public: + unordered_map mp; + vector v; + RandomizedSet() { + + } + + bool insert(int val) { + if(mp.find(val) == mp.end()) + { + v.push_back(val) ; + mp[val] = v.size()-1; + return true; + } + return false; + } + + bool remove(int val) { + if(mp.find(val) == mp.end()) + return false; + + int last = v.back() ; + mp[last] = mp[val]; + v[mp[val]] = last; + v.pop_back() ; + mp.erase(val) ; + return true; + } + + int getRandom() { + return v[rand()%v.size()]; + } +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet* obj = new RandomizedSet(); + * bool param_1 = obj->insert(val); + * bool param_2 = obj->remove(val); + * int param_3 = obj->getRandom(); + */ \ No newline at end of file diff --git a/0380-insert-delete-getrandom-o1/NOTES.md b/0380-insert-delete-getrandom-o1/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0380-insert-delete-getrandom-o1/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0380-insert-delete-getrandom-o1/README.md b/0380-insert-delete-getrandom-o1/README.md new file mode 100644 index 00000000..fc1cda7b --- /dev/null +++ b/0380-insert-delete-getrandom-o1/README.md @@ -0,0 +1,40 @@ +

380. Insert Delete GetRandom O(1)

Medium


Implement the RandomizedSet class:

+ +
    +
  • RandomizedSet() Initializes the RandomizedSet object.
  • +
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • +
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • +
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
  • +
+ +

You must implement the functions of the class such that each function works in average O(1) time complexity.

+ +

 

+

Example 1:

+ +
Input
+["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
+[[], [1], [2], [2], [], [1], [2], []]
+Output
+[null, true, false, true, 2, true, false, 2]
+
+Explanation
+RandomizedSet randomizedSet = new RandomizedSet();
+randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
+randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
+randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
+randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
+randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
+randomizedSet.insert(2); // 2 was already in the set, so return false.
+randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= val <= 231 - 1
  • +
  • At most 2 * 105 calls will be made to insert, remove, and getRandom.
  • +
  • There will be at least one element in the data structure when getRandom is called.
  • +
+
\ No newline at end of file diff --git a/0382-linked-list-random-node/0382-linked-list-random-node.cpp b/0382-linked-list-random-node/0382-linked-list-random-node.cpp new file mode 100644 index 00000000..7d22969b --- /dev/null +++ b/0382-linked-list-random-node/0382-linked-list-random-node.cpp @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + vector v; + Solution(ListNode* head) { + while(head) + { + v.push_back(head->val); + head = head->next; + } + } + + int getRandom() { + return v[rand()%v.size()]; + } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution* obj = new Solution(head); + * int param_1 = obj->getRandom(); + */ \ No newline at end of file diff --git a/0382-linked-list-random-node/README.md b/0382-linked-list-random-node/README.md new file mode 100644 index 00000000..21f56322 --- /dev/null +++ b/0382-linked-list-random-node/README.md @@ -0,0 +1,45 @@ +

382. Linked List Random Node

Medium


Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

+ +

Implement the Solution class:

+ +
    +
  • Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
  • +
  • int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
+[[[1, 2, 3]], [], [], [], [], []]
+Output
+[null, 1, 3, 2, 2, 3]
+
+Explanation
+Solution solution = new Solution([1, 2, 3]);
+solution.getRandom(); // return 1
+solution.getRandom(); // return 3
+solution.getRandom(); // return 2
+solution.getRandom(); // return 2
+solution.getRandom(); // return 3
+// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list will be in the range [1, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • At most 104 calls will be made to getRandom.
  • +
+ +

 

+

Follow up:

+ +
    +
  • What if the linked list is extremely large and its length is unknown to you?
  • +
  • Could you solve this efficiently without using extra space?
  • +
+
\ No newline at end of file diff --git a/0384-shuffle-an-array/0384-shuffle-an-array.cpp b/0384-shuffle-an-array/0384-shuffle-an-array.cpp new file mode 100644 index 00000000..8bd8e359 --- /dev/null +++ b/0384-shuffle-an-array/0384-shuffle-an-array.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + vector org; + int n; + + Solution(vector& nums) { + org = nums; + n = nums.size(); + } + + vector reset() { + return org; + } + + vector shuffle() { + vector temp = org; + int size = org.size(); + + for(int i = n-1; i>=0; --i) + { + int j = rand() % size; + swap(temp[i],temp[j]); + --size; + } + + return temp; + } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution* obj = new Solution(nums); + * vector param_1 = obj->reset(); + * vector param_2 = obj->shuffle(); + */ \ No newline at end of file diff --git a/0384-shuffle-an-array/NOTES.md b/0384-shuffle-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0384-shuffle-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0387-first-unique-character-in-a-string/0387-first-unique-character-in-a-string.cpp b/0387-first-unique-character-in-a-string/0387-first-unique-character-in-a-string.cpp new file mode 100644 index 00000000..654d516d --- /dev/null +++ b/0387-first-unique-character-in-a-string/0387-first-unique-character-in-a-string.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int firstUniqChar(string s) { + + int n = s.size(); + + map mp; + + for(auto& ch : s) + ++mp[ch]; + + for(int i = 0; i < n; ++i) + { + if(mp[s[i]] == 1) + return i; + } + + return -1; + } +}; \ No newline at end of file diff --git a/0387-first-unique-character-in-a-string/NOTES.md b/0387-first-unique-character-in-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0387-first-unique-character-in-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0387-first-unique-character-in-a-string/README.md b/0387-first-unique-character-in-a-string/README.md new file mode 100644 index 00000000..e06661f4 --- /dev/null +++ b/0387-first-unique-character-in-a-string/README.md @@ -0,0 +1,21 @@ +

387. First Unique Character in a String

Easy


Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

+ +

 

+

Example 1:

+
Input: s = "leetcode"
+Output: 0
+

Example 2:

+
Input: s = "loveleetcode"
+Output: 2
+

Example 3:

+
Input: s = "aabb"
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0389-find-the-difference/0389-find-the-difference.java b/0389-find-the-difference/0389-find-the-difference.java new file mode 100644 index 00000000..e0564259 --- /dev/null +++ b/0389-find-the-difference/0389-find-the-difference.java @@ -0,0 +1,14 @@ +class Solution { + public char findTheDifference(String s, String t) { + + char ch = 0; + + for(char c : s.toCharArray()) + ch ^= c; + + for(char c : t.toCharArray()) + ch ^= c; + + return ch; + } +} \ No newline at end of file diff --git a/0389-find-the-difference/NOTES.md b/0389-find-the-difference/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0389-find-the-difference/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0389-find-the-difference/README.md b/0389-find-the-difference/README.md new file mode 100644 index 00000000..0663dd96 --- /dev/null +++ b/0389-find-the-difference/README.md @@ -0,0 +1,29 @@ +

389. Find the Difference

Easy


You are given two strings s and t.

+ +

String t is generated by random shuffling string s and then add one more letter at a random position.

+ +

Return the letter that was added to t.

+ +

 

+

Example 1:

+ +
Input: s = "abcd", t = "abcde"
+Output: "e"
+Explanation: 'e' is the letter that was added.
+
+ +

Example 2:

+ +
Input: s = "", t = "y"
+Output: "y"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 1000
  • +
  • t.length == s.length + 1
  • +
  • s and t consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0392-is-subsequence/0392-is-subsequence.java b/0392-is-subsequence/0392-is-subsequence.java new file mode 100644 index 00000000..e6742030 --- /dev/null +++ b/0392-is-subsequence/0392-is-subsequence.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isSubsequence(String s, String t) { + + int k = 0; + + for(int i = 0; i < t.length() && k < s.length(); ++i) + { + if(s.charAt(k) == t.charAt(i)) + ++k; + } + + return (k == s.length()); + + } +} \ No newline at end of file diff --git a/0392-is-subsequence/NOTES.md b/0392-is-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0392-is-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0392-is-subsequence/README.md b/0392-is-subsequence/README.md new file mode 100644 index 00000000..56e9b407 --- /dev/null +++ b/0392-is-subsequence/README.md @@ -0,0 +1,23 @@ +

392. Is Subsequence

Easy


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

+ +

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

+ +

 

+

Example 1:

+
Input: s = "abc", t = "ahbgdc"
+Output: true
+

Example 2:

+
Input: s = "axc", t = "ahbgdc"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 100
  • +
  • 0 <= t.length <= 104
  • +
  • s and t consist only of lowercase English letters.
  • +
+ +

 

+Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
\ No newline at end of file diff --git a/0399-evaluate-division/0399-evaluate-division.cpp b/0399-evaluate-division/0399-evaluate-division.cpp new file mode 100644 index 00000000..e2187e6a --- /dev/null +++ b/0399-evaluate-division/0399-evaluate-division.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + + unordered_map>> graph; + + double dfs(string src, string dst, unordered_set& visited) + { + if(graph.find(src) == graph.end()) + return -1; + + if(src == dst) + return 1; + + for(auto itr : graph[src]) + { + if(visited.count(itr.first)) + continue; + visited.insert(itr.first); + + double res = dfs(itr.first, dst, visited); + + if(res != -1) + return res * itr.second; + } + + return -1; + } + + vector calcEquation(vector>& equations, vector& values, vector>& queries) { + + int n = equations.size(); + + for(int i = 0; i < n; ++i) + { + string u = equations[i][0]; + string v = equations[i][1]; + + double val = values[i]; + + graph[u].push_back({v, val}); + graph[v].push_back({u, (double)1/val}); + } + + vector result; + + for(auto itr : queries) + { + unordered_set visited; + + result.push_back(dfs(itr[0], itr[1], visited)); + } + + return result; + + } +}; \ No newline at end of file diff --git a/0399-evaluate-division/README.md b/0399-evaluate-division/README.md new file mode 100644 index 00000000..1e00055c --- /dev/null +++ b/0399-evaluate-division/README.md @@ -0,0 +1,46 @@ +

399. Evaluate Division

Medium


You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.

+ +

You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.

+ +

Return the answers to all queries. If a single answer cannot be determined, return -1.0.

+ +

Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

+ +

 

+

Example 1:

+ +
Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
+Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
+Explanation: 
+Given: a / b = 2.0, b / c = 3.0
+queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
+return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
+
+ +

Example 2:

+ +
Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
+Output: [3.75000,0.40000,5.00000,0.20000]
+
+ +

Example 3:

+ +
Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
+Output: [0.50000,2.00000,-1.00000,-1.00000]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= equations.length <= 20
  • +
  • equations[i].length == 2
  • +
  • 1 <= Ai.length, Bi.length <= 5
  • +
  • values.length == equations.length
  • +
  • 0.0 < values[i] <= 20.0
  • +
  • 1 <= queries.length <= 20
  • +
  • queries[i].length == 2
  • +
  • 1 <= Cj.length, Dj.length <= 5
  • +
  • Ai, Bi, Cj, Dj consist of lower case English letters and digits.
  • +
+
\ No newline at end of file diff --git a/0402-remove-k-digits/0402-remove-k-digits.cpp b/0402-remove-k-digits/0402-remove-k-digits.cpp new file mode 100644 index 00000000..3a06c361 --- /dev/null +++ b/0402-remove-k-digits/0402-remove-k-digits.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + string removeKdigits(string num, int k) { + + stack st; + + st.push(num[0] - '0'); + + for(int i = 1; i < num.size(); ++i) + { + while(!st.empty() and st.top() > (num[i] - '0') and k) + { + st.pop(); + k--; + } + + st.push(num[i] - '0'); + if(st.size() == 1 and st.top() == 0) + st.pop(); + } + + while(!st.empty() and k--) + { + st.pop(); + } + + string ans; + + while(!st.empty()) + { + ans += (st.top() + '0'); + st.pop(); + } + + reverse(ans.begin(), ans.end()); + + return ans.empty() ? "0" : ans; + + } +}; \ No newline at end of file diff --git a/0402-remove-k-digits/NOTES.md b/0402-remove-k-digits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0402-remove-k-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0402-remove-k-digits/README.md b/0402-remove-k-digits/README.md new file mode 100644 index 00000000..4319e3f3 --- /dev/null +++ b/0402-remove-k-digits/README.md @@ -0,0 +1,33 @@ +

402. Remove K Digits

Medium


Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

+ +

 

+

Example 1:

+ +
Input: num = "1432219", k = 3
+Output: "1219"
+Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
+
+ +

Example 2:

+ +
Input: num = "10200", k = 1
+Output: "200"
+Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
+
+ +

Example 3:

+ +
Input: num = "10", k = 2
+Output: "0"
+Explanation: Remove all the digits from the number and it is left with nothing which is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= num.length <= 105
  • +
  • num consists of only digits.
  • +
  • num does not have any leading zeros except for the zero itself.
  • +
+
\ No newline at end of file diff --git a/0403-frog-jump/0403-frog-jump.cpp b/0403-frog-jump/0403-frog-jump.cpp new file mode 100644 index 00000000..ab2bef65 --- /dev/null +++ b/0403-frog-jump/0403-frog-jump.cpp @@ -0,0 +1,37 @@ +class Solution { + +private: + bool helper(int idx, int n, int canJump, vector& stones, map, int>& dp) + { + if(idx == n-1) + return 1; + + if(idx >= n) + return 0; + + bool result = false; + + if(dp.find({idx, canJump}) != dp.end()) + return dp[{idx, canJump}]; + + for(int jump = -1; jump <= 1; ++jump) + { + int jumpIdx = lower_bound(stones.begin(), stones.end(), stones[idx] + canJump + jump) - stones.begin(); + + if(jumpIdx > idx and jumpIdx < n and stones[idx] + canJump + jump == stones[jumpIdx]) + result |= helper(jumpIdx, n, canJump + jump, stones, dp); + } + + + return dp[{idx, canJump}] = result; + } +public: + bool canCross(vector& stones) { + + int n = stones.size(); + + map, int> dp; + + return helper(0, n, 0, stones, dp); + } +}; \ No newline at end of file diff --git a/0403-frog-jump/NOTES.md b/0403-frog-jump/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0403-frog-jump/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0403-frog-jump/README.md b/0403-frog-jump/README.md new file mode 100644 index 00000000..e2b6e567 --- /dev/null +++ b/0403-frog-jump/README.md @@ -0,0 +1,31 @@ +

403. Frog Jump

Hard


A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

+ +

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.

+ +

If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.

+ +

 

+

Example 1:

+ +
Input: stones = [0,1,3,5,6,8,12,17]
+Output: true
+Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
+
+ +

Example 2:

+ +
Input: stones = [0,1,2,3,4,8,9,11]
+Output: false
+Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= stones.length <= 2000
  • +
  • 0 <= stones[i] <= 231 - 1
  • +
  • stones[0] == 0
  • +
  • stones is sorted in a strictly increasing order.
  • +
+
\ No newline at end of file diff --git a/0404-sum-of-left-leaves/0404-sum-of-left-leaves.cpp b/0404-sum-of-left-leaves/0404-sum-of-left-leaves.cpp new file mode 100644 index 00000000..09675766 --- /dev/null +++ b/0404-sum-of-left-leaves/0404-sum-of-left-leaves.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, int& sum) + { + if(!root) + return; + + if(root->left and !root->left->left and !root->left->right) + { + sum += root->left->val; + helper(root->right, sum); + } + else + { + helper(root->left, sum); + helper(root->right, sum); + } + + } + + int sumOfLeftLeaves(TreeNode* root) { + + int sum = 0; + + helper(root, sum); + + return sum; + + } +}; \ No newline at end of file diff --git a/0404-sum-of-left-leaves/README.md b/0404-sum-of-left-leaves/README.md new file mode 100644 index 00000000..34e2f167 --- /dev/null +++ b/0404-sum-of-left-leaves/README.md @@ -0,0 +1,26 @@ +

404. Sum of Left Leaves

Easy


Given the root of a binary tree, return the sum of all left leaves.

+ +

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: 24
+Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/0409-longest-palindrome/0409-longest-palindrome.cpp b/0409-longest-palindrome/0409-longest-palindrome.cpp new file mode 100644 index 00000000..d2c5f246 --- /dev/null +++ b/0409-longest-palindrome/0409-longest-palindrome.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int longestPalindrome(string s) { + map m ; + bool odd = 0; + for(auto i : s) + ++m[i]; + + int ind = 0; + + for(auto i : m) + { + if(i.second % 2 == 0) + ind += i.second; + else + { + ind += i.second - 1; + odd = true; + } + } + if(odd) + ind += 1; + return ind; + } +}; \ No newline at end of file diff --git a/0409-longest-palindrome/NOTES.md b/0409-longest-palindrome/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0409-longest-palindrome/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0409-longest-palindrome/README.md b/0409-longest-palindrome/README.md new file mode 100644 index 00000000..2d84a7b5 --- /dev/null +++ b/0409-longest-palindrome/README.md @@ -0,0 +1,27 @@ +

409. Longest Palindrome

Easy


Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

+ +

Letters are case sensitive, for example, "Aa" is not considered a palindrome.

+ +

 

+

Example 1:

+ +
Input: s = "abccccdd"
+Output: 7
+Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
+
+ +

Example 2:

+ +
Input: s = "a"
+Output: 1
+Explanation: The longest palindrome that can be built is "a", whose length is 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2000
  • +
  • s consists of lowercase and/or uppercase English letters only.
  • +
+
\ No newline at end of file diff --git a/0410-split-array-largest-sum/0410-split-array-largest-sum.cpp b/0410-split-array-largest-sum/0410-split-array-largest-sum.cpp new file mode 100644 index 00000000..98f31f83 --- /dev/null +++ b/0410-split-array-largest-sum/0410-split-array-largest-sum.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + + int canSplit(vector& nums, int mid) + { + int count = 1; + int sum = 0; + + for(auto itr : nums) + { + if(sum + itr > mid) + { + sum = itr; + ++count; + } + else + sum += itr; + } + return count; + } + + int splitArray(vector& nums, int k) { + + int low = *max_element(nums.begin(),nums.end()); + int high = accumulate(nums.begin(),nums.end(),0); + + int ans = low; + + while(low <= high) + { + int mid = (low + high) / 2; + + if(canSplit(nums,mid) > k) + { + low = mid + 1; + } + else + { + ans = mid; + high = mid - 1; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0410-split-array-largest-sum/NOTES.md b/0410-split-array-largest-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0410-split-array-largest-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0410-split-array-largest-sum/README.md b/0410-split-array-largest-sum/README.md new file mode 100644 index 00000000..3715962f --- /dev/null +++ b/0410-split-array-largest-sum/README.md @@ -0,0 +1,32 @@ +

410. Split Array Largest Sum

Hard


Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.

+ +

Return the minimized largest sum of the split.

+ +

A subarray is a contiguous part of the array.

+ +

 

+

Example 1:

+ +
Input: nums = [7,2,5,10,8], k = 2
+Output: 18
+Explanation: There are four ways to split nums into two subarrays.
+The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5], k = 2
+Output: 9
+Explanation: There are four ways to split nums into two subarrays.
+The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 106
  • +
  • 1 <= k <= min(50, nums.length)
  • +
+
\ No newline at end of file diff --git a/0427-construct-quad-tree/0427-construct-quad-tree.cpp b/0427-construct-quad-tree/0427-construct-quad-tree.cpp new file mode 100644 index 00000000..f315dbcb --- /dev/null +++ b/0427-construct-quad-tree/0427-construct-quad-tree.cpp @@ -0,0 +1,67 @@ +/* +// Definition for a QuadTree node. +class Node { +public: + bool val; + bool isLeaf; + Node* topLeft; + Node* topRight; + Node* bottomLeft; + Node* bottomRight; + + Node() { + val = false; + isLeaf = false; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf) { + val = _val; + isLeaf = _isLeaf; + topLeft = NULL; + topRight = NULL; + bottomLeft = NULL; + bottomRight = NULL; + } + + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { + val = _val; + isLeaf = _isLeaf; + topLeft = _topLeft; + topRight = _topRight; + bottomLeft = _bottomLeft; + bottomRight = _bottomRight; + } +}; +*/ + +class Solution { + public: + Node* construct(vector>& grid) { + return helper(grid, 0, 0, grid.size()); + } + + private: + Node* helper(const vector>& grid, int i, int j, int w) { + if (allSame(grid, i, j, w)) + return new Node(grid[i][j], true); + + Node* node = new Node(true, false); + node->topLeft = helper(grid, i, j, w / 2); + node->topRight = helper(grid, i, j + w / 2, w / 2); + node->bottomLeft = helper(grid, i + w / 2, j, w / 2); + node->bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2); + return node; + } + + bool allSame(const vector>& grid, int i, int j, int w) { + return all_of(begin(grid) + i, begin(grid) + i + w, + [&](const vector& row) { + return all_of(begin(row) + j, begin(row) + j + w, + [&](int num) { return num == grid[i][j]; }); + }); + } +}; \ No newline at end of file diff --git a/0427-construct-quad-tree/README.md b/0427-construct-quad-tree/README.md new file mode 100644 index 00000000..c056a027 --- /dev/null +++ b/0427-construct-quad-tree/README.md @@ -0,0 +1,71 @@ +

427. Construct Quad Tree

Medium


Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.

+ +

Return the root of the Quad-Tree representing the grid.

+ +

Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.

+ +

A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:

+ +
    +
  • val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
  • +
  • isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
  • +
+ +
class Node {
+    public boolean val;
+    public boolean isLeaf;
+    public Node topLeft;
+    public Node topRight;
+    public Node bottomLeft;
+    public Node bottomRight;
+}
+ +

We can construct a Quad-Tree from a two-dimensional area using the following steps:

+ +
    +
  1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
  2. +
  3. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
  4. +
  5. Recurse for each of the children with the proper sub-grid.
  6. +
+ +

If you want to know more about the Quad-Tree, you can refer to the wiki.

+ +

Quad-Tree format:

+ +

The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.

+ +

It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].

+ +

If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1],[1,0]]
+Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
+Explanation: The explanation of this example is shown below:
+Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
+
+
+ +

Example 2:

+ +

+ +
Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
+Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
+Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
+The topLeft, bottomLeft and bottomRight each has the same value.
+The topRight have different values so we divide it into 4 sub-grids where each has the same value.
+Explanation is shown in the photo below:
+
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • n == 2x where 0 <= x <= 6
  • +
+
\ No newline at end of file diff --git a/0435-non-overlapping-intervals/0435-non-overlapping-intervals.cpp b/0435-non-overlapping-intervals/0435-non-overlapping-intervals.cpp new file mode 100644 index 00000000..d7e1179b --- /dev/null +++ b/0435-non-overlapping-intervals/0435-non-overlapping-intervals.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + + int n = intervals.size(); + + sort(intervals.begin(), intervals.end(),[&](const auto &a, const auto & b){ + return a[1] < b[1]; + }); + + int cnt = 1; + + int prev = intervals[0][1]; + + for(int i = 1; i < n; ++i) + { + if(intervals[i][0] >= prev) + { + ++cnt; + prev = intervals[i][1]; + } + } + + return n - cnt; + + + } +}; \ No newline at end of file diff --git a/0435-non-overlapping-intervals/NOTES.md b/0435-non-overlapping-intervals/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0435-non-overlapping-intervals/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0435-non-overlapping-intervals/README.md b/0435-non-overlapping-intervals/README.md new file mode 100644 index 00000000..c05f8684 --- /dev/null +++ b/0435-non-overlapping-intervals/README.md @@ -0,0 +1,33 @@ +

435. Non-overlapping Intervals

Medium


Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

+ +

 

+

Example 1:

+ +
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
+Output: 1
+Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
+
+ +

Example 2:

+ +
Input: intervals = [[1,2],[1,2],[1,2]]
+Output: 2
+Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
+
+ +

Example 3:

+ +
Input: intervals = [[1,2],[2,3]]
+Output: 0
+Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 105
  • +
  • intervals[i].length == 2
  • +
  • -5 * 104 <= starti < endi <= 5 * 104
  • +
+
\ No newline at end of file diff --git a/0442-find-all-duplicates-in-an-array/0442-find-all-duplicates-in-an-array.cpp b/0442-find-all-duplicates-in-an-array/0442-find-all-duplicates-in-an-array.cpp new file mode 100644 index 00000000..0912efd0 --- /dev/null +++ b/0442-find-all-duplicates-in-an-array/0442-find-all-duplicates-in-an-array.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector findDuplicates(vector& nums) { + + int n = nums.size(); + + vector res ; + + for(int i = 0; i < n; ++i) + { + if(nums[abs(nums[i])-1] < 0) + { + res.push_back(abs(nums[i])); + } + else + { + nums[abs(nums[i])-1] = - nums[abs(nums[i])-1]; + } + } + + return res; + + } +}; diff --git a/0442-find-all-duplicates-in-an-array/NOTES.md b/0442-find-all-duplicates-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0442-find-all-duplicates-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0442-find-all-duplicates-in-an-array/README.md b/0442-find-all-duplicates-in-an-array/README.md new file mode 100644 index 00000000..1aaf2301 --- /dev/null +++ b/0442-find-all-duplicates-in-an-array/README.md @@ -0,0 +1,25 @@ +

442. Find All Duplicates in an Array

Medium


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

+ +

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

+ +

 

+

Example 1:

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

Example 2:

+
Input: nums = [1,1,2]
+Output: [1]
+

Example 3:

+
Input: nums = [1]
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
  • Each element in nums appears once or twice.
  • +
+
\ No newline at end of file diff --git a/0443-string-compression/0443-string-compression.cpp b/0443-string-compression/0443-string-compression.cpp new file mode 100644 index 00000000..c5efcad9 --- /dev/null +++ b/0443-string-compression/0443-string-compression.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int compress(vector& chars) { + + int running = 0,n = chars.size(); + int j = 0; + for(int i = 0; i 0 and chars[i] == chars[i-1]) + { + ++running; + } + else + { + if(running > 1) + { + string here = to_string(running); + for(auto itr : here) + chars[j++] = itr; + } + running = 0; + chars[j++] = chars[i]; + running = 1; + } + } + + if(running > 1) + { + string here = to_string(running); + for(auto itr : here) + chars[j++] = itr; + } + + return j; + } +}; \ No newline at end of file diff --git a/0443-string-compression/README.md b/0443-string-compression/README.md new file mode 100644 index 00000000..5392816b --- /dev/null +++ b/0443-string-compression/README.md @@ -0,0 +1,44 @@ +

443. String Compression

Medium


Given an array of characters chars, compress it using the following algorithm:

+ +

Begin with an empty string s. For each group of consecutive repeating characters in chars:

+ +
    +
  • If the group's length is 1, append the character to s.
  • +
  • Otherwise, append the character followed by the group's length.
  • +
+ +

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

+ +

After you are done modifying the input array, return the new length of the array.

+ +

You must write an algorithm that uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: chars = ["a","a","b","b","c","c","c"]
+Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
+Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
+
+ +

Example 2:

+ +
Input: chars = ["a"]
+Output: Return 1, and the first character of the input array should be: ["a"]
+Explanation: The only group is "a", which remains uncompressed since it's a single character.
+
+ +

Example 3:

+ +
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
+Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
+Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
+ +

 

+

Constraints:

+ +
    +
  • 1 <= chars.length <= 2000
  • +
  • chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
  • +
+
\ No newline at end of file diff --git a/0445-add-two-numbers-ii/0445-add-two-numbers-ii.cpp b/0445-add-two-numbers-ii/0445-add-two-numbers-ii.cpp new file mode 100644 index 00000000..3d81442a --- /dev/null +++ b/0445-add-two-numbers-ii/0445-add-two-numbers-ii.cpp @@ -0,0 +1,63 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + stack st1; + stack st2; + + while(l1) + { + st1.push(l1->val); + l1 = l1->next; + } + + while(l2) + { + st2.push(l2->val); + l2 = l2->next; + } + + ListNode* dummy = new ListNode(0); + ListNode* ptr = dummy; + + int carry = 0; + + while(!st1.empty() or !st2.empty()) + { + int a = 0, b = 0; + + if(!st1.empty()) + { + a = st1.top(); + st1.pop(); + } + if(!st2.empty()) + { + b = st2.top(); + st2.pop(); + } + + int sum = (a + b + ptr->val); + + ptr->val = sum % 10; + + ListNode* cur = new ListNode(sum/10); + + cur->next = ptr; + + ptr = cur; + } + + return (ptr->val == 0 ? ptr->next : ptr); + } +}; \ No newline at end of file diff --git a/0445-add-two-numbers-ii/NOTES.md b/0445-add-two-numbers-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0445-add-two-numbers-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0445-add-two-numbers-ii/README.md b/0445-add-two-numbers-ii/README.md new file mode 100644 index 00000000..ee38ba81 --- /dev/null +++ b/0445-add-two-numbers-ii/README.md @@ -0,0 +1,35 @@ +

445. Add Two Numbers II

Medium


You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

+ +

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
Input: l1 = [7,2,4,3], l2 = [5,6,4]
+Output: [7,8,0,7]
+
+ +

Example 2:

+ +
Input: l1 = [2,4,3], l2 = [5,6,4]
+Output: [8,0,7]
+
+ +

Example 3:

+ +
Input: l1 = [0], l2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • +
+ +

 

+

Follow up: Could you solve it without reversing the input lists?

+
\ No newline at end of file diff --git a/0446-arithmetic-slices-ii-subsequence/0446-arithmetic-slices-ii-subsequence.cpp b/0446-arithmetic-slices-ii-subsequence/0446-arithmetic-slices-ii-subsequence.cpp new file mode 100644 index 00000000..db1219f9 --- /dev/null +++ b/0446-arithmetic-slices-ii-subsequence/0446-arithmetic-slices-ii-subsequence.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int n = nums.size(); + int ans = 0; + + vector> dp(n); + + for(int i = 1; i < n; ++i) + { + for(int j = 0; j < i; ++j) + { + long long cd = (long long) nums[i] - nums[j]; + int count = dp[j].count(cd) ? dp[j][cd] : 0; + dp[i][cd] += count + 1; + ans += count; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/0446-arithmetic-slices-ii-subsequence/NOTES.md b/0446-arithmetic-slices-ii-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0446-arithmetic-slices-ii-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0446-arithmetic-slices-ii-subsequence/README.md b/0446-arithmetic-slices-ii-subsequence/README.md new file mode 100644 index 00000000..af5ccfdd --- /dev/null +++ b/0446-arithmetic-slices-ii-subsequence/README.md @@ -0,0 +1,47 @@ +

446. Arithmetic Slices II - Subsequence

Hard


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

+ +

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

+ +
    +
  • For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
  • +
  • For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
  • +
+ +

A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

+ +
    +
  • For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
  • +
+ +

The test cases are generated so that the answer fits in 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [2,4,6,8,10]
+Output: 7
+Explanation: All arithmetic subsequence slices are:
+[2,4,6]
+[4,6,8]
+[6,8,10]
+[2,4,6,8]
+[4,6,8,10]
+[2,4,6,8,10]
+[2,6,10]
+
+ +

Example 2:

+ +
Input: nums = [7,7,7,7,7]
+Output: 16
+Explanation: Any subsequence of this array is arithmetic.
+
+ +

 

+

Constraints:

+ +
    +
  • 1  <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.cpp b/0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.cpp new file mode 100644 index 00000000..793ad7b1 --- /dev/null +++ b/0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + string frequencySort(string s) { + unordered_map mp; + + for(auto itr : s) + ++mp[itr]; + + priority_queue> pq; + for(auto itr : mp) + pq.push({itr.second,itr.first}); + + string ans; + + while(!pq.empty()) + { + ans += string(pq.top().first,pq.top().second); + pq.pop(); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0451-sort-characters-by-frequency/NOTES.md b/0451-sort-characters-by-frequency/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0451-sort-characters-by-frequency/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0451-sort-characters-by-frequency/README.md b/0451-sort-characters-by-frequency/README.md new file mode 100644 index 00000000..6eceb8b1 --- /dev/null +++ b/0451-sort-characters-by-frequency/README.md @@ -0,0 +1,37 @@ +

451. Sort Characters By Frequency

Medium


Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

+ +

Return the sorted string. If there are multiple answers, return any of them.

+ +

 

+

Example 1:

+ +
Input: s = "tree"
+Output: "eert"
+Explanation: 'e' appears twice while 'r' and 't' both appear once.
+So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
+
+ +

Example 2:

+ +
Input: s = "cccaaa"
+Output: "aaaccc"
+Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
+Note that "cacaca" is incorrect, as the same characters must be together.
+
+ +

Example 3:

+ +
Input: s = "Aabb"
+Output: "bbAa"
+Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
+Note that 'A' and 'a' are treated as two different characters.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 105
  • +
  • s consists of uppercase and lowercase English letters and digits.
  • +
+
\ No newline at end of file diff --git a/0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.cpp b/0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.cpp new file mode 100644 index 00000000..fd04b700 --- /dev/null +++ b/0452-minimum-number-of-arrows-to-burst-balloons/0452-minimum-number-of-arrows-to-burst-balloons.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findMinArrowShots(vector>& p) { + + sort(p.begin(), p.end()); + int lastpoint = p[0][1]; + int ans = 1; + for(auto point : p) { + if(point[0] > lastpoint) { + ans++; + lastpoint = point[1]; + } + lastpoint = min(point[1],lastpoint); + } + return ans; + + } +}; \ No newline at end of file diff --git a/0452-minimum-number-of-arrows-to-burst-balloons/NOTES.md b/0452-minimum-number-of-arrows-to-burst-balloons/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0452-minimum-number-of-arrows-to-burst-balloons/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0452-minimum-number-of-arrows-to-burst-balloons/README.md b/0452-minimum-number-of-arrows-to-burst-balloons/README.md new file mode 100644 index 00000000..2223a5e2 --- /dev/null +++ b/0452-minimum-number-of-arrows-to-burst-balloons/README.md @@ -0,0 +1,41 @@ +

452. Minimum Number of Arrows to Burst Balloons

Medium


There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

+ +

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

+ +

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

+ +

 

+

Example 1:

+ +
Input: points = [[10,16],[2,8],[1,6],[7,12]]
+Output: 2
+Explanation: The balloons can be burst by 2 arrows:
+- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
+- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
+
+ +

Example 2:

+ +
Input: points = [[1,2],[3,4],[5,6],[7,8]]
+Output: 4
+Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
+
+ +

Example 3:

+ +
Input: points = [[1,2],[2,3],[3,4],[4,5]]
+Output: 2
+Explanation: The balloons can be burst by 2 arrows:
+- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
+- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= points.length <= 105
  • +
  • points[i].length == 2
  • +
  • -231 <= xstart < xend <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0455-assign-cookies/0455-assign-cookies.cpp b/0455-assign-cookies/0455-assign-cookies.cpp new file mode 100644 index 00000000..de9ce97d --- /dev/null +++ b/0455-assign-cookies/0455-assign-cookies.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int findContentChildren(vector& g, vector& s) { + + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + + int j = 0; + int cnt = 0; + int i = 0; + + while(j < s.size() and i < g.size()) + { + if(g[i] <= s[j]) + { + ++i, ++j, ++cnt; + } + else + ++j; + } + + return cnt; + } +}; \ No newline at end of file diff --git a/0455-assign-cookies/README.md b/0455-assign-cookies/README.md new file mode 100644 index 00000000..9387f6b5 --- /dev/null +++ b/0455-assign-cookies/README.md @@ -0,0 +1,32 @@ +

455. Assign Cookies

Easy


Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

+ +

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

+ +

 

+

Example 1:

+ +
Input: g = [1,2,3], s = [1,1]
+Output: 1
+Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
+And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
+You need to output 1.
+
+ +

Example 2:

+ +
Input: g = [1,2], s = [1,2,3]
+Output: 2
+Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
+You have 3 cookies and their sizes are big enough to gratify all of the children, 
+You need to output 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= g.length <= 3 * 104
  • +
  • 0 <= s.length <= 3 * 104
  • +
  • 1 <= g[i], s[j] <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0456-132-pattern/0456-132-pattern.cpp b/0456-132-pattern/0456-132-pattern.cpp new file mode 100644 index 00000000..a1973605 --- /dev/null +++ b/0456-132-pattern/0456-132-pattern.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool find132pattern(vector& nums) { + + int n = nums.size(); + + int s3 = INT_MIN; + + stack st; + + for(int i = n-1; i >= 0; --i) + { + if(nums[i] < s3) + return true; + + while(!st.empty() and st.top() < nums[i]) + { + s3 = st.top(); + st.pop(); + } + + st.push(nums[i]); + } + + return false; + + } +}; \ No newline at end of file diff --git a/0456-132-pattern/NOTES.md b/0456-132-pattern/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0456-132-pattern/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0456-132-pattern/README.md b/0456-132-pattern/README.md new file mode 100644 index 00000000..049ce47c --- /dev/null +++ b/0456-132-pattern/README.md @@ -0,0 +1,35 @@ +

456. 132 Pattern

Medium


Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

+ +

Return true if there is a 132 pattern in nums, otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: false
+Explanation: There is no 132 pattern in the sequence.
+
+ +

Example 2:

+ +
Input: nums = [3,1,4,2]
+Output: true
+Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
+
+ +

Example 3:

+ +
Input: nums = [-1,3,2,0]
+Output: true
+Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 2 * 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0458. Poor Pigs.cpp b/0458. Poor Pigs.cpp new file mode 100644 index 00000000..f9d748de --- /dev/null +++ b/0458. Poor Pigs.cpp @@ -0,0 +1,10 @@ +// 458.✅ Poor Pigs + +class Solution +{ +public: + int poorPigs(int buckets, int poisonTime, int totalTime) + { + return ceil(log(buckets) / log(totalTime / poisonTime + 1)); + } +}; \ No newline at end of file diff --git a/0459-repeated-substring-pattern/0459-repeated-substring-pattern.cpp b/0459-repeated-substring-pattern/0459-repeated-substring-pattern.cpp new file mode 100644 index 00000000..26cf484f --- /dev/null +++ b/0459-repeated-substring-pattern/0459-repeated-substring-pattern.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + bool repeatedSubstringPattern(string s) { + + int n = s.size(); + + if(n == 1) + return false; + + for(int i = 0; i < n/2; ++i) + { + int currLength = i+1; + + string currString = s.substr(0, i+1); + string newString = currString; + + if(n % currLength == 0) + { + while(newString.size() < s.size()) + { + newString += currString; + } + } + + if(newString == s) + return true; + } + + return false; + } +}; \ No newline at end of file diff --git a/0459-repeated-substring-pattern/NOTES.md b/0459-repeated-substring-pattern/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0459-repeated-substring-pattern/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0459-repeated-substring-pattern/README.md b/0459-repeated-substring-pattern/README.md new file mode 100644 index 00000000..9ed1b971 --- /dev/null +++ b/0459-repeated-substring-pattern/README.md @@ -0,0 +1,31 @@ +

459. Repeated Substring Pattern

Easy


Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

+ +

 

+

Example 1:

+ +
Input: s = "abab"
+Output: true
+Explanation: It is the substring "ab" twice.
+
+ +

Example 2:

+ +
Input: s = "aba"
+Output: false
+
+ +

Example 3:

+ +
Input: s = "abcabcabcabc"
+Output: true
+Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0460-lfu-cache/0460-lfu-cache.cpp b/0460-lfu-cache/0460-lfu-cache.cpp new file mode 100644 index 00000000..b9412581 --- /dev/null +++ b/0460-lfu-cache/0460-lfu-cache.cpp @@ -0,0 +1,49 @@ +class LFUCache { + int capacity; + int minFreq; + unordered_map> keyVal; + unordered_map> freqList; + unordered_map::iterator> pos; +public: + LFUCache(int capacity) { + this->capacity = capacity; + minFreq = 0; + } + + int get(int key) { + if(keyVal.find(key) == keyVal.end()) + return -1; + freqList[keyVal[key].second].erase(pos[key]); + keyVal[key].second++; + freqList[keyVal[key].second].push_back(key); + pos[key] = --freqList[keyVal[key].second].end(); + if(freqList[minFreq].empty()) + minFreq++; + return keyVal[key].first; + } + + void put(int key, int value) { + if(!capacity) + return; + if(keyVal.find(key) != keyVal.end()) { + keyVal[key].first = value; + freqList[keyVal[key].second].erase(pos[key]); + keyVal[key].second++; + freqList[keyVal[key].second].push_back(key); + pos[key] = --freqList[keyVal[key].second].end(); + if(freqList[minFreq].empty()) + minFreq++; + return; + } + if(keyVal.size() == capacity) { + int delKey = freqList[minFreq].front(); + keyVal.erase(delKey); + pos.erase(delKey); + freqList[minFreq].pop_front(); + } + keyVal[key] = {value,1}; + freqList[1].push_back(key); + pos[key] = --freqList[1].end(); + minFreq = 1; + } +}; \ No newline at end of file diff --git a/0460-lfu-cache/README.md b/0460-lfu-cache/README.md new file mode 100644 index 00000000..a75deca0 --- /dev/null +++ b/0460-lfu-cache/README.md @@ -0,0 +1,59 @@ +

460. LFU Cache

Hard


Design and implement a data structure for a Least Frequently Used (LFU) cache.

+ +

Implement the LFUCache class:

+ +
    +
  • LFUCache(int capacity) Initializes the object with the capacity of the data structure.
  • +
  • int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.
  • +
  • void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.
  • +
+ +

To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.

+ +

When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.

+ +

The functions get and put must each run in O(1) average time complexity.

+ +

 

+

Example 1:

+ +
Input
+["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
+[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
+Output
+[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
+
+Explanation
+// cnt(x) = the use counter for key x
+// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)
+LFUCache lfu = new LFUCache(2);
+lfu.put(1, 1);   // cache=[1,_], cnt(1)=1
+lfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1
+lfu.get(1);      // return 1
+                 // cache=[1,2], cnt(2)=1, cnt(1)=2
+lfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
+                 // cache=[3,1], cnt(3)=1, cnt(1)=2
+lfu.get(2);      // return -1 (not found)
+lfu.get(3);      // return 3
+                 // cache=[3,1], cnt(3)=2, cnt(1)=2
+lfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
+                 // cache=[4,3], cnt(4)=1, cnt(3)=2
+lfu.get(1);      // return -1 (not found)
+lfu.get(3);      // return 3
+                 // cache=[3,4], cnt(4)=1, cnt(3)=3
+lfu.get(4);      // return 4
+                 // cache=[4,3], cnt(4)=2, cnt(3)=3
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= capacity <= 104
  • +
  • 0 <= key <= 105
  • +
  • 0 <= value <= 109
  • +
  • At most 2 * 105 calls will be made to get and put.
  • +
+ +

 

+ 
\ No newline at end of file diff --git a/0462-minimum-moves-to-equal-array-elements-ii/0462-minimum-moves-to-equal-array-elements-ii.cpp b/0462-minimum-moves-to-equal-array-elements-ii/0462-minimum-moves-to-equal-array-elements-ii.cpp new file mode 100644 index 00000000..4e5db170 --- /dev/null +++ b/0462-minimum-moves-to-equal-array-elements-ii/0462-minimum-moves-to-equal-array-elements-ii.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minMoves2(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + int med; + if(n&1) + med = nums[n/2]; + else + med = (nums[n/2] + nums[(n/2) - 1])/2; + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + ans += abs(med - nums[i]); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0462-minimum-moves-to-equal-array-elements-ii/NOTES.md b/0462-minimum-moves-to-equal-array-elements-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0462-minimum-moves-to-equal-array-elements-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0462-minimum-moves-to-equal-array-elements-ii/README.md b/0462-minimum-moves-to-equal-array-elements-ii/README.md new file mode 100644 index 00000000..9c851770 --- /dev/null +++ b/0462-minimum-moves-to-equal-array-elements-ii/README.md @@ -0,0 +1,31 @@ +

462. Minimum Moves to Equal Array Elements II

Medium


Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

+ +

In one move, you can increment or decrement an element of the array by 1.

+ +

Test cases are designed so that the answer will fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3]
+Output: 2
+Explanation:
+Only two moves are needed (remember each move increments or decrements one element):
+[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
+
+ +

Example 2:

+ +
Input: nums = [1,10,2,9]
+Output: 16
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0472-concatenated-words/0472-concatenated-words.cpp b/0472-concatenated-words/0472-concatenated-words.cpp new file mode 100644 index 00000000..701e4c6d --- /dev/null +++ b/0472-concatenated-words/0472-concatenated-words.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + bool helper(string str, unordered_map& mp, vector& words) + { + int n = str.size(); + + for(int i = 0; i < n; ++i) + { + string left = str.substr(0,i); + string right = str.substr(i); + + if(mp[left] and (mp[right] or helper(right,mp,words))) + return true; + } + return false; + } + + vector findAllConcatenatedWordsInADict(vector& words) { + + unordered_map mp; + + for(auto itr : words) + ++mp[itr]; + + vector ans; + + for(auto itr : words) + { + if(helper(itr,mp, words)) + ans.push_back(itr); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0472-concatenated-words/README.md b/0472-concatenated-words/README.md new file mode 100644 index 00000000..543d6429 --- /dev/null +++ b/0472-concatenated-words/README.md @@ -0,0 +1,30 @@ +

472. Concatenated Words

Hard


Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.

+ +

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

+ +

 

+

Example 1:

+ +
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
+Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
+Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
+"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; 
+"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
+ +

Example 2:

+ +
Input: words = ["cat","dog","catdog"]
+Output: ["catdog"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 104
  • +
  • 1 <= words[i].length <= 30
  • +
  • words[i] consists of only lowercase English letters.
  • +
  • All the strings of words are unique.
  • +
  • 1 <= sum(words[i].length) <= 105
  • +
+
\ No newline at end of file diff --git a/0476-number-complement/0476-number-complement.cpp b/0476-number-complement/0476-number-complement.cpp new file mode 100644 index 00000000..1670a955 --- /dev/null +++ b/0476-number-complement/0476-number-complement.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int findComplement(int num) { + + int ans = 0; + bool ok = false; + + for(int i = 31; i >= 0; --i) + { + if(!(num & (1 << i)) and ok) + { + ans += (1 << i); + } + + if(num & (1 << i)) + { + ok = true; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0476-number-complement/README.md b/0476-number-complement/README.md new file mode 100644 index 00000000..b46eec80 --- /dev/null +++ b/0476-number-complement/README.md @@ -0,0 +1,33 @@ +

476. Number Complement

Easy


The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

+ +
    +
  • For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
  • +
+ +

Given an integer num, return its complement.

+ +

 

+

Example 1:

+ +
Input: num = 5
+Output: 2
+Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
+
+ +

Example 2:

+ +
Input: num = 1
+Output: 0
+Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num < 231
  • +
+ +

 

+

Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/

+
\ No newline at end of file diff --git a/0486-predict-the-winner/0486-predict-the-winner.cpp b/0486-predict-the-winner/0486-predict-the-winner.cpp new file mode 100644 index 00000000..9a5f4f9c --- /dev/null +++ b/0486-predict-the-winner/0486-predict-the-winner.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + + + int helper(int i, int j, vector& nums, vector>& dp) + { + if(i == j) + return nums[i]; + if(dp[i][j] != -1) + return dp[i][j]; + int start = nums[i] - helper(i+1, j, nums, dp); + int end = nums[j] - helper(i,j-1,nums, dp); + + return dp[i][j] = max(start, end); + } + + bool PredictTheWinner(vector& nums) { + + int n = nums.size(); + vector > dp(n, vector(n,-1)); + return helper(0 , n-1, nums, dp) >= 0; + + } +}; \ No newline at end of file diff --git a/0486-predict-the-winner/README.md b/0486-predict-the-winner/README.md new file mode 100644 index 00000000..42b757b5 --- /dev/null +++ b/0486-predict-the-winner/README.md @@ -0,0 +1,33 @@ +

486. Predict the Winner

Medium


You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.

+ +

Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.

+ +

Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.

+ +

 

+

Example 1:

+ +
Input: nums = [1,5,2]
+Output: false
+Explanation: Initially, player 1 can choose between 1 and 2. 
+If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). 
+So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. 
+Hence, player 1 will never be the winner and you need to return false.
+
+ +

Example 2:

+ +
Input: nums = [1,5,233,7]
+Output: true
+Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
+Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 20
  • +
  • 0 <= nums[i] <= 107
  • +
+
\ No newline at end of file diff --git a/0491-non-decreasing-subsequences/0491-non-decreasing-subsequences.cpp b/0491-non-decreasing-subsequences/0491-non-decreasing-subsequences.cpp new file mode 100644 index 00000000..332cbc5d --- /dev/null +++ b/0491-non-decreasing-subsequences/0491-non-decreasing-subsequences.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + void helper(int idx, vector& ds, vector>& res,vector& nums, int prev) + { + if(idx >= nums.size()) + { + if(ds.size() >= 2) + res.push_back(ds); + return; + } + + if(prev == -1 or nums[prev] <= nums[idx]) + { + ds.push_back(nums[idx]); + helper(idx+1,ds,res,nums, idx); + ds.pop_back(); + } + helper(idx+1, ds, res, nums, prev); + } + + + vector> findSubsequences(vector& nums) { + + vector ds; + vector> res; + + helper(0,ds,res,nums,-1); + + set> s(res.begin(),res.end()); + + vector> ans(s.begin(),s.end()); + + return ans; + + } +}; \ No newline at end of file diff --git a/0491-non-decreasing-subsequences/NOTES.md b/0491-non-decreasing-subsequences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0491-non-decreasing-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0491-non-decreasing-subsequences/README.md b/0491-non-decreasing-subsequences/README.md new file mode 100644 index 00000000..d50f1d96 --- /dev/null +++ b/0491-non-decreasing-subsequences/README.md @@ -0,0 +1,23 @@ +

491. Non-decreasing Subsequences

Medium


Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [4,6,7,7]
+Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
+
+ +

Example 2:

+ +
Input: nums = [4,4,3,2,1]
+Output: [[4,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 15
  • +
  • -100 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0493-reverse-pairs/0493-reverse-pairs.cpp b/0493-reverse-pairs/0493-reverse-pairs.cpp new file mode 100644 index 00000000..51d3c6f5 --- /dev/null +++ b/0493-reverse-pairs/0493-reverse-pairs.cpp @@ -0,0 +1,75 @@ +#define ll long long int + +class Solution { +public: + + int merge(int start, int mid, int end, vector& nums, vector& temp) + { + int i = start, j = mid+1, k = i; + + int cnt = 0; + + int right = mid+1; + + for(int left = start; left <= mid; ++left) + { + while(right <= end and nums[left] > (ll) 2 * nums[right]) + ++right; + + cnt += (right - (mid + 1)); + } + + while(i <= mid and j <= end) + { + if(nums[i] <= nums[j]) + temp[k++] = nums[i++]; + else + temp[k++] = nums[j++]; + } + + while(i <= mid) + temp[k++] = nums[i++]; + + while(j <= end) + temp[k++] = nums[j++]; + + for(int i = start; i<= end; ++i) + nums[i] = temp[i]; + + return cnt; + } + + + int mergeSort(int i, int j, vector& nums, vector& temp) + { + int cnt = 0; + + if( i < j) + { + int mid = i + (j - i)/2; + + cnt += mergeSort(i, mid, nums, temp); + cnt += mergeSort(mid+1, j, nums, temp); + cnt += merge(i, mid, j, nums, temp); + } + + return cnt; + } + + + int reversePairs(vector& nums) { + + int n = nums.size(); + + vector temp(n); + + int ans = mergeSort(0, n-1 , nums, temp); + + for(auto itr : nums) + cout<493. Reverse Pairs

Hard


Given an integer array nums, return the number of reverse pairs in the array.

+ +

A reverse pair is a pair (i, j) where:

+ +
    +
  • 0 <= i < j < nums.length and
  • +
  • nums[i] > 2 * nums[j].
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [1,3,2,3,1]
+Output: 2
+Explanation: The reverse pairs are:
+(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
+(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
+
+ +

Example 2:

+ +
Input: nums = [2,4,3,5,1]
+Output: 3
+Explanation: The reverse pairs are:
+(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
+(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
+(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0501-find-mode-in-binary-search-tree/0501-find-mode-in-binary-search-tree.cpp b/0501-find-mode-in-binary-search-tree/0501-find-mode-in-binary-search-tree.cpp new file mode 100644 index 00000000..e9971d98 --- /dev/null +++ b/0501-find-mode-in-binary-search-tree/0501-find-mode-in-binary-search-tree.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, unordered_map& mp, int& maxi) + { + if(root) + { + helper(root->left, mp, maxi); + ++mp[root->val]; + maxi = max(maxi, mp[root->val]); + helper(root->right, mp, maxi); + } + } + + vector findMode(TreeNode* root) { + + unordered_map mp; + + int maxi = 0; + + helper(root, mp, maxi); + + vector ans; + + for(auto& itr : mp) + { + if(itr.second == maxi) + ans.push_back(itr.first); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0501-find-mode-in-binary-search-tree/README.md b/0501-find-mode-in-binary-search-tree/README.md new file mode 100644 index 00000000..eaf7c94d --- /dev/null +++ b/0501-find-mode-in-binary-search-tree/README.md @@ -0,0 +1,35 @@ +

501. Find Mode in Binary Search Tree

Easy


Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

+ +

If the tree has more than one mode, return them in any order.

+ +

Assume a BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,2]
+Output: [2]
+
+ +

Example 2:

+ +
Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ +

 

+Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
\ No newline at end of file diff --git a/0502-ipo/0502-ipo.cpp b/0502-ipo/0502-ipo.cpp new file mode 100644 index 00000000..23ee8b76 --- /dev/null +++ b/0502-ipo/0502-ipo.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { + + int n = capital.size(); + vector > vp; + for(int i = 0; i < n; ++i) + vp.push_back({capital[i],profits[i]}); + + sort(vp.begin(),vp.end()); + + priority_queue pq; + + int j = 0; + + for(int i = 0; i < k; ++i) + { + while(j < n and vp[j].first <= w) + pq.push(vp[j++].second); + + if(pq.empty()) + break; + + w += pq.top(); + pq.pop(); + } + + return w; + } +}; + + \ No newline at end of file diff --git a/0502-ipo/NOTES.md b/0502-ipo/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0502-ipo/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0502-ipo/README.md b/0502-ipo/README.md new file mode 100644 index 00000000..80db493d --- /dev/null +++ b/0502-ipo/README.md @@ -0,0 +1,41 @@ +

502. IPO

Hard


Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.

+ +

You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.

+ +

Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.

+ +

Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.

+ +

The answer is guaranteed to fit in a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
+Output: 4
+Explanation: Since your initial capital is 0, you can only start the project indexed 0.
+After finishing it you will obtain profit 1 and your capital becomes 1.
+With capital 1, you can either start the project indexed 1 or the project indexed 2.
+Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
+Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
+
+ +

Example 2:

+ +
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= 105
  • +
  • 0 <= w <= 109
  • +
  • n == profits.length
  • +
  • n == capital.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= profits[i] <= 104
  • +
  • 0 <= capital[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0508-most-frequent-subtree-sum/0508-most-frequent-subtree-sum.cpp b/0508-most-frequent-subtree-sum/0508-most-frequent-subtree-sum.cpp new file mode 100644 index 00000000..1fbe59eb --- /dev/null +++ b/0508-most-frequent-subtree-sum/0508-most-frequent-subtree-sum.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + unordered_map mp; + int maxCount = 0; + + int helper(TreeNode * root) + { + if(!root) + return 0; + int currSum = root->val + helper(root->left) + helper(root->right); + ++mp[currSum]; + maxCount = max(maxCount,mp[currSum]); + + return currSum; + } + + vector findFrequentTreeSum(TreeNode* root) { + + helper(root); + + vector ans; + + for(auto itr : mp) + { + if(itr.second == maxCount) + ans.push_back(itr.first); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0508-most-frequent-subtree-sum/NOTES.md b/0508-most-frequent-subtree-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0508-most-frequent-subtree-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0508-most-frequent-subtree-sum/README.md b/0508-most-frequent-subtree-sum/README.md new file mode 100644 index 00000000..a12618c5 --- /dev/null +++ b/0508-most-frequent-subtree-sum/README.md @@ -0,0 +1,25 @@ +

508. Most Frequent Subtree Sum

Medium


Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

+ +

The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).

+ +

 

+

Example 1:

+ +
Input: root = [5,2,-3]
+Output: [2,-3,4]
+
+ +

Example 2:

+ +
Input: root = [5,2,-5]
+Output: [2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/0509-fibonacci-number/0509-fibonacci-number.cpp b/0509-fibonacci-number/0509-fibonacci-number.cpp new file mode 100644 index 00000000..ed9538c8 --- /dev/null +++ b/0509-fibonacci-number/0509-fibonacci-number.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + + + vector> expo(vector> mat, int n) + { + vector> ans = mat; + + if(n == 1) + return mat; + + + while( n > 0) + { + if(n & 1) + ans = mult(ans, mat); + + mat = mult(mat, mat); + + n >>= 1; + } + + return ans; + } + + vector> mult(vector>mat1, vector> mat2) + { + vector> ans(2, vector(2)); + + for(int i = 0; i < 2; ++i) + { + for(int j = 0; j < 2; ++j) + { + for(int k = 0; k < 2; ++k) + { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + + return ans; + + } + + int fib(int n) { + + if(n == 0) + return 0; + + vector> mat = {{1,1}, {1,0}}; + + vector> ans = expo(mat, n-1); + + return ans[0][1]; + } +}; \ No newline at end of file diff --git a/0509-fibonacci-number/NOTES.md b/0509-fibonacci-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0509-fibonacci-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0509-fibonacci-number/README.md b/0509-fibonacci-number/README.md new file mode 100644 index 00000000..328aa572 --- /dev/null +++ b/0509-fibonacci-number/README.md @@ -0,0 +1,37 @@ +

509. Fibonacci Number

Easy


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

+ +
F(0) = 0, F(1) = 1
+F(n) = F(n - 1) + F(n - 2), for n > 1.
+
+ +

Given n, calculate F(n).

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
+
+ +

Example 2:

+ +
Input: n = 3
+Output: 2
+Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
+
+ +

Example 3:

+ +
Input: n = 4
+Output: 3
+Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 30
  • +
+
\ No newline at end of file diff --git a/0513-find-bottom-left-tree-value/0513-find-bottom-left-tree-value.cpp b/0513-find-bottom-left-tree-value/0513-find-bottom-left-tree-value.cpp new file mode 100644 index 00000000..2859c4be --- /dev/null +++ b/0513-find-bottom-left-tree-value/0513-find-bottom-left-tree-value.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + map mp; + + void findLeftValue(TreeNode* root, int currLevel , int& maxLevel) + { + if(root) + { + findLeftValue(root->left, currLevel + 1, maxLevel); + findLeftValue(root->right, currLevel + 1, maxLevel); + + maxLevel = max(maxLevel , currLevel); + + if(mp.find(maxLevel) == mp.end()) + mp[maxLevel] = root->val; + } + } + + int findBottomLeftValue(TreeNode* root) { + + int maxLevel = 0; + + findLeftValue(root, 0, maxLevel); + + return mp[maxLevel]; + } +}; \ No newline at end of file diff --git a/0513-find-bottom-left-tree-value/NOTES.md b/0513-find-bottom-left-tree-value/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0513-find-bottom-left-tree-value/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0513-find-bottom-left-tree-value/README.md b/0513-find-bottom-left-tree-value/README.md new file mode 100644 index 00000000..a733cb60 --- /dev/null +++ b/0513-find-bottom-left-tree-value/README.md @@ -0,0 +1,23 @@ +

513. Find Bottom Left Tree Value

Medium


Given the root of a binary tree, return the leftmost value in the last row of the tree.

+ +

 

+

Example 1:

+ +
Input: root = [2,1,3]
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [1,2,3,4,null,5,6,null,null,7]
+Output: 7
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0514-freedom-trail/0514-freedom-trail.cpp b/0514-freedom-trail/0514-freedom-trail.cpp new file mode 100644 index 00000000..4eaf3a81 --- /dev/null +++ b/0514-freedom-trail/0514-freedom-trail.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + + int helper(int idx, int ptr, int n, int m, string& ring, string& key, vector>& dp) + { + if(idx >= m) + return 0; + + if(dp[idx][ptr] != -1) + return dp[idx][ptr]; + + int steps = 1e9; + + for(int i = 0; i < n; ++i) + { + if(ring[i] == key[idx]) + steps = min(steps, 1 + min(abs(i - ptr), n - abs(i-ptr)) + helper(idx+1, i, n, m, ring, key, dp)); + } + + return dp[idx][ptr] = steps; + } + + int findRotateSteps(string ring, string key) { + + int n = ring.size(); + int m = key.size(); + + vector> dp(m+1, vector(n+1, -1)); + + return helper(0, 0, n, m, ring, key, dp); + + } +}; \ No newline at end of file diff --git a/0514-freedom-trail/NOTES.md b/0514-freedom-trail/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0514-freedom-trail/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0514-freedom-trail/README.md b/0514-freedom-trail/README.md new file mode 100644 index 00000000..7f40ba56 --- /dev/null +++ b/0514-freedom-trail/README.md @@ -0,0 +1,40 @@ +

514. Freedom Trail

Hard


In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.

+ +

Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.

+ +

Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button.

+ +

At the stage of rotating the ring to spell the key character key[i]:

+ +
    +
  1. You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i].
  2. +
  3. If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.
  4. +
+ +

 

+

Example 1:

+ +
Input: ring = "godding", key = "gd"
+Output: 4
+Explanation:
+For the first key character 'g', since it is already in place, we just need 1 step to spell this character. 
+For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
+Also, we need 1 more step for spelling.
+So the final output is 4.
+
+ +

Example 2:

+ +
Input: ring = "godding", key = "godding"
+Output: 13
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= ring.length, key.length <= 100
  • +
  • ring and key consist of only lower case English letters.
  • +
  • It is guaranteed that key could always be spelled by rotating ring.
  • +
+
\ No newline at end of file diff --git a/0515-find-largest-value-in-each-tree-row/0515-find-largest-value-in-each-tree-row.cpp b/0515-find-largest-value-in-each-tree-row/0515-find-largest-value-in-each-tree-row.cpp new file mode 100644 index 00000000..f2f14855 --- /dev/null +++ b/0515-find-largest-value-in-each-tree-row/0515-find-largest-value-in-each-tree-row.cpp @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector largestValues(TreeNode* root) { + + if(!root) + return {}; + + queue q; + + vector ans; + + q.push(root); + + while(!q.empty()) + { + int size = q.size(); + + int maxi = INT_MIN; + + for(int i = 0; i < size; ++i) + { + TreeNode* curr = q.front(); + q.pop(); + + maxi = max(maxi, curr->val); + + if(curr->left) + q.push(curr->left); + + if(curr->right) + q.push(curr->right); + } + + ans.push_back(maxi); + } + return ans; + } +}; \ No newline at end of file diff --git a/0515-find-largest-value-in-each-tree-row/NOTES.md b/0515-find-largest-value-in-each-tree-row/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0515-find-largest-value-in-each-tree-row/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0515-find-largest-value-in-each-tree-row/README.md b/0515-find-largest-value-in-each-tree-row/README.md new file mode 100644 index 00000000..95bb431d --- /dev/null +++ b/0515-find-largest-value-in-each-tree-row/README.md @@ -0,0 +1,23 @@ +

515. Find Largest Value in Each Tree Row

Medium


Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

+ +

 

+

Example 1:

+ +
Input: root = [1,3,2,5,3,null,9]
+Output: [1,3,9]
+
+ +

Example 2:

+ +
Input: root = [1,2,3]
+Output: [1,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0516-longest-palindromic-subsequence/0516-longest-palindromic-subsequence.cpp b/0516-longest-palindromic-subsequence/0516-longest-palindromic-subsequence.cpp new file mode 100644 index 00000000..cd968a2f --- /dev/null +++ b/0516-longest-palindromic-subsequence/0516-longest-palindromic-subsequence.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + + int helper(int i, int j, string& s, string& t, int n, vector>& dp) + { + if(i >= n or j >= n) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + if(s[i] == t[j]) + return dp[i][j] = 1 + helper(i+1, j+1, s, t, n, dp); + + return dp[i][j] = max(helper(i+1,j, s, t, n, dp), helper(i, j+1, s, t, n, dp)); + } + + int longestPalindromeSubseq(string s) { + + int n = s.size(); + string t = s; + reverse(t.begin(),t.end()); + + vector> dp(n+1, vector(n+1,-1)); + + return helper(0, 0, s, t, n, dp); + } +}; \ No newline at end of file diff --git a/0516-longest-palindromic-subsequence/README.md b/0516-longest-palindromic-subsequence/README.md new file mode 100644 index 00000000..4bf9ad9e --- /dev/null +++ b/0516-longest-palindromic-subsequence/README.md @@ -0,0 +1,27 @@ +

516. Longest Palindromic Subsequence

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "bbbab"
+Output: 4
+Explanation: One possible longest palindromic subsequence is "bbbb".
+
+ +

Example 2:

+ +
Input: s = "cbbd"
+Output: 2
+Explanation: One possible longest palindromic subsequence is "bb".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0518-coin-change-ii/0518-coin-change-ii.cpp b/0518-coin-change-ii/0518-coin-change-ii.cpp new file mode 100644 index 00000000..62a8898c --- /dev/null +++ b/0518-coin-change-ii/0518-coin-change-ii.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int change(int amount, vector& coins) { + + int n = coins.size(); + + vector prev(amount+1, 0), curr(amount+1, 0); + + for(int i = 0; i <= amount; ++i) + { + prev[i] = (i % coins[n-1] == 0 ? 1 : 0); + } + + for(int i = n-2; i >= 0; --i) + { + for(int j = 0; j <= amount; ++j) + { + int notTake = prev[j]; + + int take = 0; + + if(coins[i] <= j) + { + take = curr[j-coins[i]]; + } + + curr[j] = take + notTake; + } + prev = curr; + } + + return prev[amount]; + + } +}; \ No newline at end of file diff --git a/0518-coin-change-ii/NOTES.md b/0518-coin-change-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0518-coin-change-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0518-coin-change-ii/README.md b/0518-coin-change-ii/README.md new file mode 100644 index 00000000..25495b07 --- /dev/null +++ b/0518-coin-change-ii/README.md @@ -0,0 +1,43 @@ +

518. Coin Change II

Medium


You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

+ +

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

+ +

You may assume that you have an infinite number of each kind of coin.

+ +

The answer is guaranteed to fit into a signed 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: amount = 5, coins = [1,2,5]
+Output: 4
+Explanation: there are four ways to make up the amount:
+5=5
+5=2+2+1
+5=2+1+1+1
+5=1+1+1+1+1
+
+ +

Example 2:

+ +
Input: amount = 3, coins = [2]
+Output: 0
+Explanation: the amount of 3 cannot be made up just with coins of 2.
+
+ +

Example 3:

+ +
Input: amount = 10, coins = [10]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= coins.length <= 300
  • +
  • 1 <= coins[i] <= 5000
  • +
  • All the values of coins are unique.
  • +
  • 0 <= amount <= 5000
  • +
+
\ No newline at end of file diff --git a/0520-detect-capital/0520-detect-capital.cpp b/0520-detect-capital/0520-detect-capital.cpp new file mode 100644 index 00000000..ae35aa50 --- /dev/null +++ b/0520-detect-capital/0520-detect-capital.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool detectCapitalUse(string word) { + + int caps = 0; + int n = word.size(); + + for(auto itr : word) + { + if(isupper(itr)) + ++caps; + } + + return caps == 0 or caps == n or (caps == 1 and isupper(word[0])); + + } +}; \ No newline at end of file diff --git a/0520-detect-capital/NOTES.md b/0520-detect-capital/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0520-detect-capital/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0520-detect-capital/README.md b/0520-detect-capital/README.md new file mode 100644 index 00000000..7ab5b8cc --- /dev/null +++ b/0520-detect-capital/README.md @@ -0,0 +1,26 @@ +

520. Detect Capital

Easy


We define the usage of capitals in a word to be right when one of the following cases holds:

+ +
    +
  • All letters in this word are capitals, like "USA".
  • +
  • All letters in this word are not capitals, like "leetcode".
  • +
  • Only the first letter in this word is capital, like "Google".
  • +
+ +

Given a string word, return true if the usage of capitals in it is right.

+ +

 

+

Example 1:

+
Input: word = "USA"
+Output: true
+

Example 2:

+
Input: word = "FlaG"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 100
  • +
  • word consists of lowercase and uppercase English letters.
  • +
+
\ No newline at end of file diff --git a/0523-continuous-subarray-sum/0523-continuous-subarray-sum.cpp b/0523-continuous-subarray-sum/0523-continuous-subarray-sum.cpp new file mode 100644 index 00000000..47037b9c --- /dev/null +++ b/0523-continuous-subarray-sum/0523-continuous-subarray-sum.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool checkSubarraySum(vector& nums, int k) { + + int n = nums.size(); + + map mp; + + int sum = 0; + + mp[0] = -1; + + for(int i = 0; i < n; ++i) + { + sum += nums[i]; + + int rem = sum % k; + + if(mp.find(rem) != mp.end()) + { + if(i - mp[rem] > 1) + return true; + } + else + mp[rem] = i; + } + + return false; + } +}; \ No newline at end of file diff --git a/0523-continuous-subarray-sum/NOTES.md b/0523-continuous-subarray-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0523-continuous-subarray-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0523-continuous-subarray-sum/README.md b/0523-continuous-subarray-sum/README.md new file mode 100644 index 00000000..0bf5d8e1 --- /dev/null +++ b/0523-continuous-subarray-sum/README.md @@ -0,0 +1,48 @@ +

523. Continuous Subarray Sum

Medium


Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

+ +

A good subarray is a subarray where:

+ +
    +
  • its length is at least two, and
  • +
  • the sum of the elements of the subarray is a multiple of k.
  • +
+ +

Note that:

+ +
    +
  • A subarray is a contiguous part of the array.
  • +
  • An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [23,2,4,6,7], k = 6
+Output: true
+Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
+
+ +

Example 2:

+ +
Input: nums = [23,2,6,4,7], k = 6
+Output: true
+Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
+42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
+
+ +

Example 3:

+ +
Input: nums = [23,2,6,4,7], k = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
  • 0 <= sum(nums[i]) <= 231 - 1
  • +
  • 1 <= k <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0525-contiguous-array/0525-contiguous-array.cpp b/0525-contiguous-array/0525-contiguous-array.cpp new file mode 100644 index 00000000..1d4d98ec --- /dev/null +++ b/0525-contiguous-array/0525-contiguous-array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int findMaxLength(vector& nums) { + + map mp; + + mp.insert({0, -1}); + + int sum = 0, ans = 0, n = nums.size(); + + for(int i = 0; i < n; ++i) + { + sum += (nums[i] == 1 ? 1 : -1); + if(mp.find(sum) != mp.end()) + ans = max(ans, i - mp[sum]); + else + mp[sum] = i; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0525-contiguous-array/NOTES.md b/0525-contiguous-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0525-contiguous-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0530-minimum-absolute-difference-in-bst/0530-minimum-absolute-difference-in-bst.cpp b/0530-minimum-absolute-difference-in-bst/0530-minimum-absolute-difference-in-bst.cpp new file mode 100644 index 00000000..7a9d4d49 --- /dev/null +++ b/0530-minimum-absolute-difference-in-bst/0530-minimum-absolute-difference-in-bst.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + +private: + int helper(TreeNode* root, int& mini, int& val) + { + if(root->left) + helper(root->left,mini, val); + + if(val >= 0) + mini = min(mini, root->val - val); + + val = root->val; + + if(root->right) + helper(root->right, mini , val); + + return mini; + } + +public: + int getMinimumDifference(TreeNode* root) { + + int mini = INT_MAX,val = -1; + + return helper(root, mini, val); + + } +}; \ No newline at end of file diff --git a/0530-minimum-absolute-difference-in-bst/README.md b/0530-minimum-absolute-difference-in-bst/README.md new file mode 100644 index 00000000..652088ce --- /dev/null +++ b/0530-minimum-absolute-difference-in-bst/README.md @@ -0,0 +1,26 @@ +

530. Minimum Absolute Difference in BST

Easy


Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,6,1,3]
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [1,0,48,null,null,12,49]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 104].
  • +
  • 0 <= Node.val <= 105
  • +
+ +

 

+

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

+
\ No newline at end of file diff --git a/0542-01-matrix/0542-01-matrix.cpp b/0542-01-matrix/0542-01-matrix.cpp new file mode 100644 index 00000000..5adf57ae --- /dev/null +++ b/0542-01-matrix/0542-01-matrix.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + vector> updateMatrix(vector>& mat) { + + int n = mat.size(), m = mat[0].size(); + + queue>> q; + + vector> dist(n, vector(m)); + + vector> visited(n, vector(m, false)); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(mat[i][j] == 0) + { + dist[i][j] = 0; + q.push({0,{i,j}}); + visited[i][j] = true; + } + } + } + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1, 0}; + + while(!q.empty()) + { + auto curr = q.front(); + q.pop(); + + int curDist = curr.first; + int x = curr.second.first; + int y = curr.second.second; + + if(mat[x][y] == 1) + { + dist[x][y] = curDist; + } + + for(int i = 0; i < 4; ++i) + { + int newX = dx[i] + x; + int newY = dy[i] + y; + + if(newX >= 0 and newY >= 0 and newX < n and newY < m and !visited[newX][newY]) + { + q.push({curDist + 1, {newX, newY}}); + visited[newX][newY] = true; + } + } + } + + return dist; + } +}; \ No newline at end of file diff --git a/0542-01-matrix/NOTES.md b/0542-01-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0542-01-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0542-01-matrix/README.md b/0542-01-matrix/README.md new file mode 100644 index 00000000..931bf9a2 --- /dev/null +++ b/0542-01-matrix/README.md @@ -0,0 +1,29 @@ +

542. 01 Matrix

Medium


Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

+ +

The distance between two adjacent cells is 1.

+ +

 

+

Example 1:

+ +
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
+Output: [[0,0,0],[0,1,0],[0,0,0]]
+
+ +

Example 2:

+ +
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
+Output: [[0,0,0],[0,1,0],[1,2,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 1 <= m, n <= 104
  • +
  • 1 <= m * n <= 104
  • +
  • mat[i][j] is either 0 or 1.
  • +
  • There is at least one 0 in mat.
  • +
+
\ No newline at end of file diff --git a/0543-diameter-of-binary-tree/0543-diameter-of-binary-tree.cpp b/0543-diameter-of-binary-tree/0543-diameter-of-binary-tree.cpp new file mode 100644 index 00000000..e64aec71 --- /dev/null +++ b/0543-diameter-of-binary-tree/0543-diameter-of-binary-tree.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int helper(TreeNode* root, int& ans) + { + if(!root) + return 0; + + int left = helper(root->left, ans); + int right = helper(root->right, ans); + + ans = max(ans, left + right); + + return 1 + max(left, right); + } + + int diameterOfBinaryTree(TreeNode* root) { + + int ans = 0; + helper(root, ans); + return ans; + } +}; \ No newline at end of file diff --git a/0543-diameter-of-binary-tree/NOTES.md b/0543-diameter-of-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0543-diameter-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0543-diameter-of-binary-tree/README.md b/0543-diameter-of-binary-tree/README.md new file mode 100644 index 00000000..26e6fc34 --- /dev/null +++ b/0543-diameter-of-binary-tree/README.md @@ -0,0 +1,28 @@ +

543. Diameter of Binary Tree

Easy


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

+ +

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

+ +

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

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5]
+Output: 3
+Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
+
+ +

Example 2:

+ +
Input: root = [1,2]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0547-number-of-provinces/0547-number-of-provinces.cpp b/0547-number-of-provinces/0547-number-of-provinces.cpp new file mode 100644 index 00000000..c7f0c37e --- /dev/null +++ b/0547-number-of-provinces/0547-number-of-provinces.cpp @@ -0,0 +1,100 @@ +class DSU{ + private: + vector rank, parent, size; + public: + DSU(int n) + { + rank.resize(n+1, 0); + parent.resize(n+1); + size.resize(n+1, 1); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findPar(int u) + { + if(parent[u] == u) + return parent[u]; + return parent[u] = findPar(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findPar(u); + int parV = findPar(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findPar(u); + int parV = findPar(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findPar(u) == findPar(v); + } +}; + +class Solution { +public: + int findCircleNum(vector>& isConnected) { + + int n = isConnected.size(); + int m = isConnected[0].size(); + + DSU dsu(n); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(isConnected[i][j] == 1) + dsu.unionBySize(i+1, j+1); + } + } + + int cnt = 0; + + for(int i = 1; i <= n; ++i) + { + if(dsu.findPar(i) == i) + ++cnt; + } + + return cnt; + + } +}; \ No newline at end of file diff --git a/0547-number-of-provinces/NOTES.md b/0547-number-of-provinces/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0547-number-of-provinces/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0547-number-of-provinces/README.md b/0547-number-of-provinces/README.md new file mode 100644 index 00000000..a3193d12 --- /dev/null +++ b/0547-number-of-provinces/README.md @@ -0,0 +1,33 @@ +

547. Number of Provinces

Medium


There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

+ +

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

+ +

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

+ +

Return the total number of provinces.

+ +

 

+

Example 1:

+ +
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
+Output: 2
+
+ +

Example 2:

+ +
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 200
  • +
  • n == isConnected.length
  • +
  • n == isConnected[i].length
  • +
  • isConnected[i][j] is 1 or 0.
  • +
  • isConnected[i][i] == 1
  • +
  • isConnected[i][j] == isConnected[j][i]
  • +
+
\ No newline at end of file diff --git a/0552-student-attendance-record-ii/0552-student-attendance-record-ii.cpp b/0552-student-attendance-record-ii/0552-student-attendance-record-ii.cpp new file mode 100644 index 00000000..f87965aa --- /dev/null +++ b/0552-student-attendance-record-ii/0552-student-attendance-record-ii.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + + const int mod = 1e9+7; + + int helper(int n, int absent, int late, vector>>& dp) + { + if(n == 0) + return 1; + + if(dp[n][absent][late] != -1) + return dp[n][absent][late]; + + int total = 0; + + total += helper(n-1, absent, 2, dp); + total %= mod; + + if(absent > 0) + { + total += helper(n-1, absent-1, 2, dp); + total %= mod; + } + + if(late > 0) + { + total += helper(n-1, absent, late-1, dp); + total %= mod; + } + + return dp[n][absent][late] = total; + } + + int checkRecord(int n) { + + vector>> dp(n+1, vector>(2, vector(3, -1))); + + return helper(n, 1, 2, dp); + + } +}; \ No newline at end of file diff --git a/0552-student-attendance-record-ii/NOTES.md b/0552-student-attendance-record-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0552-student-attendance-record-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0556-next-greater-element-iii/0556-next-greater-element-iii.cpp b/0556-next-greater-element-iii/0556-next-greater-element-iii.cpp new file mode 100644 index 00000000..6d89562c --- /dev/null +++ b/0556-next-greater-element-iii/0556-next-greater-element-iii.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + + long long next_Permutation(int n) + { + string str = to_string(n); + + int breakPoint = -1; + + int m = str.size(); + + for(int i = m-2; i >= 0; --i) + { + if(str[i] < str[i+1]) + { + breakPoint = i; + break; + } + } + + if(breakPoint == -1) + { + reverse(str.begin(), str.end()); + } + else + { + for(int i = m-1; i > breakPoint; --i) + { + if(str[i] > str[breakPoint]) + { + swap(str[i], str[breakPoint]); + break; + } + } + + reverse(str.begin() + breakPoint + 1 , str.end()); + } + + return stoll(str); + } + + int nextGreaterElement(int n) { + + long long nextGreater = next_Permutation(n); + + return (nextGreater > INT_MAX or nextGreater <= n ? -1 : nextGreater); + + } +}; \ No newline at end of file diff --git a/0556-next-greater-element-iii/README.md b/0556-next-greater-element-iii/README.md new file mode 100644 index 00000000..3827d0f3 --- /dev/null +++ b/0556-next-greater-element-iii/README.md @@ -0,0 +1,19 @@ +

556. Next Greater Element III

Medium


Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.

+ +

Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

+ +

 

+

Example 1:

+
Input: n = 12
+Output: 21
+

Example 2:

+
Input: n = 21
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0557-reverse-words-in-a-string-iii/0557-reverse-words-in-a-string-iii.cpp b/0557-reverse-words-in-a-string-iii/0557-reverse-words-in-a-string-iii.cpp new file mode 100644 index 00000000..610932ec --- /dev/null +++ b/0557-reverse-words-in-a-string-iii/0557-reverse-words-in-a-string-iii.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + string reverseWords(string s) { + + stringstream ss(s); + + string word; + + string ans; + + while(ss >> word) + { + reverse(word.begin(), word.end()); + ans += word + ' '; + } + + ans.pop_back(); + + return ans; + + } +}; \ No newline at end of file diff --git a/0557-reverse-words-in-a-string-iii/NOTES.md b/0557-reverse-words-in-a-string-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0557-reverse-words-in-a-string-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0557-reverse-words-in-a-string-iii/README.md b/0557-reverse-words-in-a-string-iii/README.md new file mode 100644 index 00000000..cdc6104c --- /dev/null +++ b/0557-reverse-words-in-a-string-iii/README.md @@ -0,0 +1,21 @@ +

557. Reverse Words in a String III

Easy


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

+ +

 

+

Example 1:

+
Input: s = "Let's take LeetCode contest"
+Output: "s'teL ekat edoCteeL tsetnoc"
+

Example 2:

+
Input: s = "God Ding"
+Output: "doG gniD"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s contains printable ASCII characters.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • There is at least one word in s.
  • +
  • All the words in s are separated by a single space.
  • +
+
\ No newline at end of file diff --git a/0560-subarray-sum-equals-k/0560-subarray-sum-equals-k.cpp b/0560-subarray-sum-equals-k/0560-subarray-sum-equals-k.cpp new file mode 100644 index 00000000..617fb67d --- /dev/null +++ b/0560-subarray-sum-equals-k/0560-subarray-sum-equals-k.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int subarraySum(vector& nums, int k) { + + unordered_map mp; + + int sum = 0, counter = 0; + + mp.insert({0, 1}); + + for(auto& itr : nums) + { + sum += itr; + + if(mp.find(sum - k) != mp.end()) + counter += mp[sum - k]; + + ++mp[sum]; + } + + return counter; + } +}; \ No newline at end of file diff --git a/0560-subarray-sum-equals-k/NOTES.md b/0560-subarray-sum-equals-k/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0560-subarray-sum-equals-k/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0560-subarray-sum-equals-k/README.md b/0560-subarray-sum-equals-k/README.md new file mode 100644 index 00000000..ab207d65 --- /dev/null +++ b/0560-subarray-sum-equals-k/README.md @@ -0,0 +1,21 @@ +

560. Subarray Sum Equals K

Medium


Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+
Input: nums = [1,1,1], k = 2
+Output: 2
+

Example 2:

+
Input: nums = [1,2,3], k = 3
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
  • -107 <= k <= 107
  • +
+
\ No newline at end of file diff --git a/0564-find-the-closest-palindrome/0564-find-the-closest-palindrome.cpp b/0564-find-the-closest-palindrome/0564-find-the-closest-palindrome.cpp new file mode 100644 index 00000000..0d79df33 --- /dev/null +++ b/0564-find-the-closest-palindrome/0564-find-the-closest-palindrome.cpp @@ -0,0 +1,61 @@ +using ll = long long; + +class Solution { +public: + + ll palindrome(ll firstHalf, bool isEven) + { + ll resultNum = firstHalf; + + if(!isEven) + firstHalf /= 10; + + while(firstHalf > 0) + { + resultNum = (resultNum * 10) + (firstHalf%10); + firstHalf /= 10; + } + + return resultNum; + } + + string nearestPalindromic(string n) { + + int sz = n.size(); + int mid = sz/2; + + ll firstHalfLen = (sz % 2 == 0 ? mid : mid+1); + + ll firstHalf = stoll(n.substr(0, firstHalfLen)); + + vector pos; + + pos.push_back(palindrome(firstHalf, sz % 2 == 0)); + pos.push_back(palindrome(firstHalf+1, sz % 2 == 0)); + pos.push_back(palindrome(firstHalf-1, sz % 2 == 0)); + pos.push_back(pow(10, sz-1) - 1); + pos.push_back(pow(10, sz) + 1); + + ll diff = LONG_MAX; + ll res = LONG_MAX; + ll orgNum = stoll(n); + + for(auto& num : pos) + { + if(num == orgNum) continue; + + if(abs(num - orgNum) < diff) + { + diff = abs(num - orgNum); + res = num; + } + else if(abs(num - orgNum) == diff) + { + res = min(res, num); + } + } + + return to_string(res); + + } +}; \ No newline at end of file diff --git a/0564-find-the-closest-palindrome/NOTES.md b/0564-find-the-closest-palindrome/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0564-find-the-closest-palindrome/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0564-find-the-closest-palindrome/README.md b/0564-find-the-closest-palindrome/README.md new file mode 100644 index 00000000..a5b4ec14 --- /dev/null +++ b/0564-find-the-closest-palindrome/README.md @@ -0,0 +1,28 @@ +

564. Find the Closest Palindrome

Hard


Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

+ +

The closest is defined as the absolute difference minimized between two integers.

+ +

 

+

Example 1:

+ +
Input: n = "123"
+Output: "121"
+
+ +

Example 2:

+ +
Input: n = "1"
+Output: "0"
+Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n.length <= 18
  • +
  • n consists of only digits.
  • +
  • n does not have leading zeros.
  • +
  • n is representing an integer in the range [1, 1018 - 1].
  • +
+
\ No newline at end of file diff --git a/0567-permutation-in-string/0567-permutation-in-string.cpp b/0567-permutation-in-string/0567-permutation-in-string.cpp new file mode 100644 index 00000000..a8f32418 --- /dev/null +++ b/0567-permutation-in-string/0567-permutation-in-string.cpp @@ -0,0 +1,33 @@ +class Solution { + bool areVectorsEqual(vector a, vector b){ + for(int i=0; i<26; i++){ + if(a[i]!=b[i]) return false; + } + return true; + } +public: + bool checkInclusion(string s1, string s2) { + if(s2.size() freqS1(26, 0); + for(char c: s1) freqS1[c-'a']++; + + vector freqS2(26, 0); + int i=0, j=0; + + while(j567. Permutation in String

Medium


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: s1 = "ab", s2 = "eidbaooo"
+Output: true
+Explanation: s2 contains one permutation of s1 ("ba").
+
+ +

Example 2:

+ +
Input: s1 = "ab", s2 = "eidboaoo"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s1.length, s2.length <= 104
  • +
  • s1 and s2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0576-out-of-boundary-paths/0576-out-of-boundary-paths.cpp b/0576-out-of-boundary-paths/0576-out-of-boundary-paths.cpp new file mode 100644 index 00000000..379ead6e --- /dev/null +++ b/0576-out-of-boundary-paths/0576-out-of-boundary-paths.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + int dp[55][55][55]; + + const int mod = 1e9+7; + + int boundaryPaths(int i, int j, int n, int m, int maxMove) + { + if(maxMove >= 0 and i < 0 or j < 0 or i >= n or j >= m) + return 1; + + if(dp[i][j][maxMove] != -1) + return dp[i][j][maxMove]; + + int up = 0, right = 0, down = 0, left = 0; + + if(maxMove) + { + up = boundaryPaths(i-1, j, n, m, maxMove-1); + right = boundaryPaths(i, j+1, n, m, maxMove-1); + down = boundaryPaths(i+1, j, n, m, maxMove-1); + left = boundaryPaths(i, j-1, n, m, maxMove-1); + } + + return dp[i][j][maxMove] = ((((up%mod + right%mod)%mod + down%mod)%mod + left%mod) % mod); + } + + int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { + + memset(dp, -1, sizeof(dp)); + + return boundaryPaths(startRow, startColumn, m, n, maxMove); + + } +}; \ No newline at end of file diff --git a/0576-out-of-boundary-paths/NOTES.md b/0576-out-of-boundary-paths/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0576-out-of-boundary-paths/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0576-out-of-boundary-paths/README.md b/0576-out-of-boundary-paths/README.md new file mode 100644 index 00000000..25a688e2 --- /dev/null +++ b/0576-out-of-boundary-paths/README.md @@ -0,0 +1,27 @@ +

576. Out of Boundary Paths

Medium


There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

+ +

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
+Output: 6
+
+ +

Example 2:

+ +
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 50
  • +
  • 0 <= maxMove <= 50
  • +
  • 0 <= startRow < m
  • +
  • 0 <= startColumn < n
  • +
+
\ No newline at end of file diff --git a/0584-find-customer-referee/0584-find-customer-referee.sql b/0584-find-customer-referee/0584-find-customer-referee.sql new file mode 100644 index 00000000..7f77caac --- /dev/null +++ b/0584-find-customer-referee/0584-find-customer-referee.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below + +select name from Customer where referee_id is null or referee_id != 2; \ No newline at end of file diff --git a/0584-find-customer-referee/NOTES.md b/0584-find-customer-referee/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0584-find-customer-referee/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0584-find-customer-referee/README.md b/0584-find-customer-referee/README.md new file mode 100644 index 00000000..372be3cf --- /dev/null +++ b/0584-find-customer-referee/README.md @@ -0,0 +1,47 @@ +

584. Find Customer Referee

Easy


Table: Customer

+ +
+-------------+---------+
+| Column Name | Type    |
++-------------+---------+
+| id          | int     |
+| name        | varchar |
+| referee_id  | int     |
++-------------+---------+
+In SQL, id is the primary key column for this table.
+Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.
+
+ +

 

+ +

Find the names of the customer that are not referred by the customer with id = 2.

+ +

Return the result table in any order.

+ +

The result format is in the following example.

+ +

 

+

Example 1:

+ +
Input: 
+Customer table:
++----+------+------------+
+| id | name | referee_id |
++----+------+------------+
+| 1  | Will | null       |
+| 2  | Jane | null       |
+| 3  | Alex | 2          |
+| 4  | Bill | null       |
+| 5  | Zack | 1          |
+| 6  | Mark | 2          |
++----+------+------------+
+Output: 
++------+
+| name |
++------+
+| Will |
+| Jane |
+| Bill |
+| Zack |
++------+
+
+
\ No newline at end of file diff --git a/0590-n-ary-tree-postorder-traversal/0590-n-ary-tree-postorder-traversal.cpp b/0590-n-ary-tree-postorder-traversal/0590-n-ary-tree-postorder-traversal.cpp new file mode 100644 index 00000000..fb8c1b94 --- /dev/null +++ b/0590-n-ary-tree-postorder-traversal/0590-n-ary-tree-postorder-traversal.cpp @@ -0,0 +1,45 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + + void postorder(Node* root, vector& ans) + { + if(root) + { + for(auto& chlNode : root->children) + { + postorder(chlNode, ans); + } + ans.push_back(root->val); + } + } + + vector postorder(Node* root) { + + vector ans; + + postorder(root, ans); + + return ans; + + } +}; \ No newline at end of file diff --git a/0590-n-ary-tree-postorder-traversal/NOTES.md b/0590-n-ary-tree-postorder-traversal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0590-n-ary-tree-postorder-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0590-n-ary-tree-postorder-traversal/README.md b/0590-n-ary-tree-postorder-traversal/README.md new file mode 100644 index 00000000..cee6f44d --- /dev/null +++ b/0590-n-ary-tree-postorder-traversal/README.md @@ -0,0 +1,29 @@ +

590. N-ary Tree Postorder Traversal

Easy


Given the root of an n-ary tree, return the postorder traversal of its nodes' values.

+ +

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

+ +

 

+

Example 1:

+ +
Input: root = [1,null,3,2,4,null,5,6]
+Output: [5,6,3,2,4,1]
+
+ +

Example 2:

+ +
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The height of the n-ary tree is less than or equal to 1000.
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+
\ No newline at end of file diff --git a/0592-fraction-addition-and-subtraction/0592-fraction-addition-and-subtraction.cpp b/0592-fraction-addition-and-subtraction/0592-fraction-addition-and-subtraction.cpp new file mode 100644 index 00000000..532239f0 --- /dev/null +++ b/0592-fraction-addition-and-subtraction/0592-fraction-addition-and-subtraction.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + string fractionAddition(string expression) { + + int num = 0; + int den = 1; + + int i = 0, n = expression.size(); + + while(i < n) + { + int curNum = 0; + int curDen = 0; + + bool isNeg = (expression[i] == '-'); + + if(expression[i] == '+' or expression[i] == '-') + ++i; + + while(i < n && isdigit(expression[i])) + { + int val = expression[i] - '0'; + curNum = (curNum * 10) + val; + ++i; + } + + ++i; + if(isNeg) curNum *= -1; + + while(i < n && isdigit(expression[i])) + { + int val = expression[i] - '0'; + curDen = (curDen * 10) + val; + ++i; + } + + num = (num * curDen) + (curNum * den); + den = den * curDen; + } + + int gcd = abs(__gcd(num, den)); + num /= gcd; + den /= gcd; + + return to_string(num) + "/" + to_string(den); + } +}; \ No newline at end of file diff --git a/0592-fraction-addition-and-subtraction/README.md b/0592-fraction-addition-and-subtraction/README.md new file mode 100644 index 00000000..5d1558c5 --- /dev/null +++ b/0592-fraction-addition-and-subtraction/README.md @@ -0,0 +1,34 @@ +

592. Fraction Addition and Subtraction

Medium


Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

+ +

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

+ +

 

+

Example 1:

+ +
Input: expression = "-1/2+1/2"
+Output: "0/1"
+
+ +

Example 2:

+ +
Input: expression = "-1/2+1/2+1/3"
+Output: "1/3"
+
+ +

Example 3:

+ +
Input: expression = "1/3-1/2"
+Output: "-1/6"
+
+ +

 

+

Constraints:

+ +
    +
  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • +
  • Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • +
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • +
  • The number of given fractions will be in the range [1, 10].
  • +
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
  • +
+
\ No newline at end of file diff --git a/0595-big-countries/0595-big-countries.sql b/0595-big-countries/0595-big-countries.sql new file mode 100644 index 00000000..4ade2dde --- /dev/null +++ b/0595-big-countries/0595-big-countries.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below + +select name, population, area from World where area >= 3000000 or population >= 25000000 order by name asc; \ No newline at end of file diff --git a/0595-big-countries/NOTES.md b/0595-big-countries/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0595-big-countries/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0606-construct-string-from-binary-tree/0606-construct-string-from-binary-tree.cpp b/0606-construct-string-from-binary-tree/0606-construct-string-from-binary-tree.cpp new file mode 100644 index 00000000..0323b754 --- /dev/null +++ b/0606-construct-string-from-binary-tree/0606-construct-string-from-binary-tree.cpp @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, string& ans) + { + if(root) + { + ans += to_string(root->val); + + if(root->left) + { + ans += '('; + helper(root->left, ans); + ans += ')'; + } + + if(root->right) + { + if(!root->left) + ans += "()"; + ans += '('; + helper(root->right, ans); + ans += ')'; + } + } + } + + string tree2str(TreeNode* root) { + + string ans; + helper(root, ans); + return ans; + } +}; \ No newline at end of file diff --git a/0606-construct-string-from-binary-tree/NOTES.md b/0606-construct-string-from-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0606-construct-string-from-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0606-construct-string-from-binary-tree/README.md b/0606-construct-string-from-binary-tree/README.md new file mode 100644 index 00000000..d304033f --- /dev/null +++ b/0606-construct-string-from-binary-tree/README.md @@ -0,0 +1,27 @@ +

606. Construct String from Binary Tree

Easy


Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

+ +

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4]
+Output: "1(2(4))(3)"
+Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)"
+
+ +

Example 2:

+ +
Input: root = [1,2,3,null,4]
+Output: "1(2()(4))(3)"
+Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/0621-task-scheduler/0621-task-scheduler.cpp b/0621-task-scheduler/0621-task-scheduler.cpp new file mode 100644 index 00000000..1b34b091 --- /dev/null +++ b/0621-task-scheduler/0621-task-scheduler.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int leastInterval(vector& tasks, int n) { + + mapmp; + int count = 0; + + for(auto ele : tasks) + { + mp[ele]++; + count = max(count, mp[ele]); + } + + int ans = (count-1)*(n+1); + + for(auto e : mp) + { + if(e.second == count) + ans++; + } + + return max((int)tasks.size(), ans); + } +}; \ No newline at end of file diff --git a/0621-task-scheduler/README.md b/0621-task-scheduler/README.md new file mode 100644 index 00000000..a449ed32 --- /dev/null +++ b/0621-task-scheduler/README.md @@ -0,0 +1,95 @@ +

621. Task Scheduler

Medium


You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.

+ +

​Return the minimum number of intervals required to complete all tasks.

+ +

 

+

Example 1:

+ +
+

Input: tasks = ["A","A","A","B","B","B"], n = 2

+ +

Output: 8

+ +

Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.

+ +

After completing task A, you must wait two cycles before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th cycle, you can do A again as 2 intervals have passed.

+
+ +

Example 2:

+ +
+

Input: tasks = ["A","C","A","B","D","B"], n = 1

+ +

Output: 6

+ +

Explanation: A possible sequence is: A -> B -> C -> D -> A -> B.

+ +

With a cooling interval of 1, you can repeat a task after just one other task.

+
+ +

Example 3:

+ +
+

Input: tasks = ["A","A","A", "B","B","B"], n = 3

+ +

Output: 10

+ +

Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.

+ +

There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tasks.length <= 104
  • +
  • tasks[i] is an uppercase English letter.
  • +
  • 0 <= n <= 100
  • +
+
\ No newline at end of file diff --git a/0623-add-one-row-to-tree/0623-add-one-row-to-tree.cpp b/0623-add-one-row-to-tree/0623-add-one-row-to-tree.cpp new file mode 100644 index 00000000..6b5b032c --- /dev/null +++ b/0623-add-one-row-to-tree/0623-add-one-row-to-tree.cpp @@ -0,0 +1,63 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + + if(depth == 1) + { + TreeNode* node = new TreeNode(val); + + node->left = root; + + return node; + } + + queue q; + + --depth; + q.push(root); + + while(!q.empty()) + { + int sz = q.size(); + + for(int i = 0; i < sz; ++i) + { + TreeNode* curr = q.front(); + q.pop(); + + if(depth == 1) + { + TreeNode* nexLeft = curr->left ? curr->left : nullptr; + TreeNode* newNode1 = new TreeNode(val); + curr->left = newNode1; + newNode1->left = nexLeft; + + TreeNode* nexRight = curr->right ? curr->right : nullptr; + TreeNode* newNode2 = new TreeNode(val); + curr->right = newNode2; + newNode2->right = nexRight; + } + + if(curr->left) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + } + + --depth; + } + + return root; + } +}; \ No newline at end of file diff --git a/0623-add-one-row-to-tree/README.md b/0623-add-one-row-to-tree/README.md new file mode 100644 index 00000000..c1f4b23e --- /dev/null +++ b/0623-add-one-row-to-tree/README.md @@ -0,0 +1,37 @@ +

623. Add One Row to Tree

Medium


Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

+ +

Note that the root node is at depth 1.

+ +

The adding rule is:

+ +
    +
  • Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
  • +
  • cur's original left subtree should be the left subtree of the new left subtree root.
  • +
  • cur's original right subtree should be the right subtree of the new right subtree root.
  • +
  • If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
+Output: [4,1,1,2,null,null,6,3,1,5]
+
+ +

Example 2:

+ +
Input: root = [4,2,null,3,1], val = 1, depth = 3
+Output: [4,2,null,1,1,3,null,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • The depth of the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
  • -105 <= val <= 105
  • +
  • 1 <= depth <= the depth of tree + 1
  • +
+
\ No newline at end of file diff --git a/0624-maximum-distance-in-arrays/0624-maximum-distance-in-arrays.cpp b/0624-maximum-distance-in-arrays/0624-maximum-distance-in-arrays.cpp new file mode 100644 index 00000000..5ceb9190 --- /dev/null +++ b/0624-maximum-distance-in-arrays/0624-maximum-distance-in-arrays.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxDistance(vector>& arrays) { + + int left = arrays[0][0], right = arrays[0].back(), ans = 0; + + for(int i = 1; i < arrays.size(); i++) + { + ans = max(ans, max(abs(arrays[i][0] - right), abs(arrays[i].back() - left))); + left = min(left, arrays[i][0]); + right = max(right, arrays[i].back()); + } + + + return ans; + } +}; \ No newline at end of file diff --git a/0624-maximum-distance-in-arrays/README.md b/0624-maximum-distance-in-arrays/README.md new file mode 100644 index 00000000..77b7a756 --- /dev/null +++ b/0624-maximum-distance-in-arrays/README.md @@ -0,0 +1,32 @@ +

624. Maximum Distance in Arrays

Medium


You are given m arrays, where each array is sorted in ascending order.

+ +

You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.

+ +

Return the maximum distance.

+ +

 

+

Example 1:

+ +
Input: arrays = [[1,2,3],[4,5],[1,2,3]]
+Output: 4
+Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
+
+ +

Example 2:

+ +
Input: arrays = [[1],[1]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == arrays.length
  • +
  • 2 <= m <= 105
  • +
  • 1 <= arrays[i].length <= 500
  • +
  • -104 <= arrays[i][j] <= 104
  • +
  • arrays[i] is sorted in ascending order.
  • +
  • There will be at most 105 integers in all the arrays.
  • +
+
\ No newline at end of file diff --git a/0628-maximum-product-of-three-numbers/0628-maximum-product-of-three-numbers.cpp b/0628-maximum-product-of-three-numbers/0628-maximum-product-of-three-numbers.cpp new file mode 100644 index 00000000..75508a34 --- /dev/null +++ b/0628-maximum-product-of-three-numbers/0628-maximum-product-of-three-numbers.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maximumProduct(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + return max({nums[0] * nums[1] * nums[2], nums[0] * nums[1] * nums[n-1], nums[n-3] * nums[n-2] * nums[n-1]}); + + } +}; \ No newline at end of file diff --git a/0628-maximum-product-of-three-numbers/NOTES.md b/0628-maximum-product-of-three-numbers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0628-maximum-product-of-three-numbers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0628-maximum-product-of-three-numbers/README.md b/0628-maximum-product-of-three-numbers/README.md new file mode 100644 index 00000000..ecd0b816 --- /dev/null +++ b/0628-maximum-product-of-three-numbers/README.md @@ -0,0 +1,21 @@ +

628. Maximum Product of Three Numbers

Easy


Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: 6
+

Example 2:

+
Input: nums = [1,2,3,4]
+Output: 24
+

Example 3:

+
Input: nums = [-1,-2,-3]
+Output: -6
+
+

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/0629-k-inverse-pairs-array/0629-k-inverse-pairs-array.cpp b/0629-k-inverse-pairs-array/0629-k-inverse-pairs-array.cpp new file mode 100644 index 00000000..44bda9a0 --- /dev/null +++ b/0629-k-inverse-pairs-array/0629-k-inverse-pairs-array.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int mod = 1e9+7; + int kInversePairs(int n, int K) { + //dp[i][j] denote till i numbers how many jth inversion pair-containing permutations are there + vector> dp(n+1,vector(K+1,0)); + dp[0][0]=0; + for(int i=1;i<=K;i++){ + dp[1][i]=0; + } + for(int i=1;i<=n;i++){ + dp[i][0]=1; + } +for(int i=2;i<=n;i++){ + for(int j=1;j<=K;j++){ + dp[i][j]=(dp[i-1][j]+dp[i][j-1])%mod; + if(j-i>=0){ + dp[i][j]=(dp[i][j]-dp[i-1][j-i]+mod)%mod; + } + } + } + return dp[n][K]; + } +}; diff --git a/0629-k-inverse-pairs-array/README.md b/0629-k-inverse-pairs-array/README.md new file mode 100644 index 00000000..b9c1e1ff --- /dev/null +++ b/0629-k-inverse-pairs-array/README.md @@ -0,0 +1,27 @@ +

629. K Inverse Pairs Array

Hard


For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].

+ +

Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 3, k = 0
+Output: 1
+Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
+
+ +

Example 2:

+ +
Input: n = 3, k = 1
+Output: 2
+Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
  • 0 <= k <= 1000
  • +
+
\ No newline at end of file diff --git a/0633-sum-of-square-numbers/0633-sum-of-square-numbers.cpp b/0633-sum-of-square-numbers/0633-sum-of-square-numbers.cpp new file mode 100644 index 00000000..185bb33f --- /dev/null +++ b/0633-sum-of-square-numbers/0633-sum-of-square-numbers.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool judgeSquareSum(int c) { + + for(int i = 2; i * i <= c; ++i) + { + int cnt = 0; + + while(c % i == 0) + { + ++cnt; + c /= i; + } + + if(i % 4 == 3 and cnt % 2 != 0) + return false; + } + + return c%4 != 3; + + } +}; \ No newline at end of file diff --git a/0633-sum-of-square-numbers/NOTES.md b/0633-sum-of-square-numbers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0633-sum-of-square-numbers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0633-sum-of-square-numbers/README.md b/0633-sum-of-square-numbers/README.md new file mode 100644 index 00000000..efeadaa1 --- /dev/null +++ b/0633-sum-of-square-numbers/README.md @@ -0,0 +1,23 @@ +

633. Sum of Square Numbers

Medium


Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

+ +

 

+

Example 1:

+ +
Input: c = 5
+Output: true
+Explanation: 1 * 1 + 2 * 2 = 5
+
+ +

Example 2:

+ +
Input: c = 3
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= c <= 231 - 1
  • +
+
\ No newline at end of file diff --git a/0645-set-mismatch/0645-set-mismatch.cpp b/0645-set-mismatch/0645-set-mismatch.cpp new file mode 100644 index 00000000..37bdfca6 --- /dev/null +++ b/0645-set-mismatch/0645-set-mismatch.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector findErrorNums(vector& nums) { + + int n = nums.size(); + int missing = -1, repeat = -1; + + for(int i = 0; i < n; ++i) + { + if(nums[abs(nums[i])-1] < 0) + { + repeat = abs(nums[i]); + } + else + { + nums[abs(nums[i])-1] *= -1; + } + } + + for(int i = 0; i < n; ++i) + { + if(nums[i] > 0) + missing = i + 1; + } + + return {repeat, missing}; + } +}; \ No newline at end of file diff --git a/0645-set-mismatch/NOTES.md b/0645-set-mismatch/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0645-set-mismatch/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0645-set-mismatch/README.md b/0645-set-mismatch/README.md new file mode 100644 index 00000000..78699612 --- /dev/null +++ b/0645-set-mismatch/README.md @@ -0,0 +1,22 @@ +

645. Set Mismatch

Easy


You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

+ +

You are given an integer array nums representing the data status of this set after the error.

+ +

Find the number that occurs twice and the number that is missing and return them in the form of an array.

+ +

 

+

Example 1:

+
Input: nums = [1,2,2,4]
+Output: [2,3]
+

Example 2:

+
Input: nums = [1,1]
+Output: [1,2]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • 1 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0646-maximum-length-of-pair-chain/0646-maximum-length-of-pair-chain.cpp b/0646-maximum-length-of-pair-chain/0646-maximum-length-of-pair-chain.cpp new file mode 100644 index 00000000..80200bd0 --- /dev/null +++ b/0646-maximum-length-of-pair-chain/0646-maximum-length-of-pair-chain.cpp @@ -0,0 +1,33 @@ +class Solution { + +private: + int helper(int idx, int prev, int n, vector>& pairs, vector >& dp) + { + if(idx == n) + return 0; + + if(dp[idx][prev + 1] != -1) + return dp[idx][prev + 1]; + + int take = 0; + + int notTake = helper(idx + 1, prev, n, pairs, dp); + + if(prev == -1 or pairs[idx][0] > pairs[prev][1]) + take = max(1 + helper(idx + 1, idx, n, pairs, dp), notTake); + + return dp[idx][prev + 1] = max(take, notTake); + } +public: + int findLongestChain(vector>& pairs) { + + sort(pairs.begin(), pairs.end()); + + int n = pairs.size(); + + vector> dp(n+1, vector(n+1, -1)); + + return helper(0, -1, n, pairs, dp); + + } +}; \ No newline at end of file diff --git a/0646-maximum-length-of-pair-chain/NOTES.md b/0646-maximum-length-of-pair-chain/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0646-maximum-length-of-pair-chain/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0646-maximum-length-of-pair-chain/README.md b/0646-maximum-length-of-pair-chain/README.md new file mode 100644 index 00000000..0537ff05 --- /dev/null +++ b/0646-maximum-length-of-pair-chain/README.md @@ -0,0 +1,32 @@ +

646. Maximum Length of Pair Chain

Medium


You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

+ +

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

+ +

Return the length longest chain which can be formed.

+ +

You do not need to use up all the given intervals. You can select pairs in any order.

+ +

 

+

Example 1:

+ +
Input: pairs = [[1,2],[2,3],[3,4]]
+Output: 2
+Explanation: The longest chain is [1,2] -> [3,4].
+
+ +

Example 2:

+ +
Input: pairs = [[1,2],[7,8],[4,5]]
+Output: 3
+Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
+
+ +

 

+

Constraints:

+ +
    +
  • n == pairs.length
  • +
  • 1 <= n <= 1000
  • +
  • -1000 <= lefti < righti <= 1000
  • +
+
\ No newline at end of file diff --git a/0647-palindromic-substrings/0647-palindromic-substrings.cpp b/0647-palindromic-substrings/0647-palindromic-substrings.cpp new file mode 100644 index 00000000..750babdc --- /dev/null +++ b/0647-palindromic-substrings/0647-palindromic-substrings.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int countSubstrings(string s) { + + int n = s.size(); + + vector> dp(n+1, vector(n+1, 0)); + + int cnt = 0; + + for(int diff = 0; diff < n; ++diff) + { + for(int i = 0, j = diff; i < n and j < n; ++i, ++j) + { + if(i == j) + { + ++cnt; + dp[i][j] = 1; + } + else if(diff == 1 and s[i] == s[j]) + { + ++cnt; + dp[i][j] = 2; + } + else if(diff > 1 and s[i] == s[j] and dp[i+1][j-1]) + { + ++cnt; + dp[i][j] = dp[i+1][j-1] + 2; + } + } + } + + return cnt; + } +}; \ No newline at end of file diff --git a/0647-palindromic-substrings/README.md b/0647-palindromic-substrings/README.md new file mode 100644 index 00000000..f833b17e --- /dev/null +++ b/0647-palindromic-substrings/README.md @@ -0,0 +1,29 @@ +

647. Palindromic Substrings

Medium


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

+ +

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

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "abc"
+Output: 3
+Explanation: Three palindromic strings: "a", "b", "c".
+
+ +

Example 2:

+ +
Input: s = "aaa"
+Output: 6
+Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0648-replace-words/0648-replace-words.cpp b/0648-replace-words/0648-replace-words.cpp new file mode 100644 index 00000000..c01b7524 --- /dev/null +++ b/0648-replace-words/0648-replace-words.cpp @@ -0,0 +1,110 @@ +class Node +{ + private: + Node* child[26] = {nullptr}; + bool isWord = false; + + public: + bool containsKey(char ch) + { + return child[ch-'a'] != nullptr; + } + + Node* get(char ch) + { + return child[ch-'a']; + } + + void put(char ch, Node* newNode) + { + child[ch-'a'] = newNode; + } + + void setEnd() + { + isWord = true; + } + + bool isEnd() + { + return isWord; + } +}; + +class Trie{ + private: + Node* root; + + public: + Trie() + { + root = new Node(); + } + + void insert(string& word) + { + int n = word.size(); + Node* temp = root; + + for(int i = 0; i < n; ++i) + { + if(!temp->containsKey(word[i])) + temp->put(word[i], new Node()); + temp = temp->get(word[i]); + } + temp->setEnd(); + } + + string search(string& word) + { + int n = word.size(); + Node* temp = root; + string ans; + + for(int i = 0; i < n; ++i) + { + if(temp->containsKey(word[i])) + { + ans += word[i]; + } + else + return "-1"; + + temp = temp->get(word[i]); + + if(temp->isEnd()) + return ans; + } + + return "-1"; + } +}; + +class Solution { +public: + string replaceWords(vector& dictionary, string sentence) { + + Trie *trie = new Trie(); + + stringstream ss(sentence); + string word, ans; + + for(auto& str : dictionary) + trie->insert(str); + + while(ss >> word) + { + string curr = trie->search(word); + + if(curr != "-1") + ans += curr; + else + ans += word; + ans += " "; + } + + ans.pop_back(); + + return ans; + } +}; \ No newline at end of file diff --git a/0648-replace-words/NOTES.md b/0648-replace-words/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0648-replace-words/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0648-replace-words/README.md b/0648-replace-words/README.md new file mode 100644 index 00000000..aed11e37 --- /dev/null +++ b/0648-replace-words/README.md @@ -0,0 +1,34 @@ +

648. Replace Words

Medium


In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".

+ +

Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.

+ +

Return the sentence after the replacement.

+ +

 

+

Example 1:

+ +
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
+Output: "the cat was rat by the bat"
+
+ +

Example 2:

+ +
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
+Output: "a a b c"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= dictionary.length <= 1000
  • +
  • 1 <= dictionary[i].length <= 100
  • +
  • dictionary[i] consists of only lower-case letters.
  • +
  • 1 <= sentence.length <= 106
  • +
  • sentence consists of only lower-case letters and spaces.
  • +
  • The number of words in sentence is in the range [1, 1000]
  • +
  • The length of each word in sentence is in the range [1, 1000]
  • +
  • Every two consecutive words in sentence will be separated by exactly one space.
  • +
  • sentence does not have leading or trailing spaces.
  • +
+
\ No newline at end of file diff --git a/0649-dota2-senate/0649-dota2-senate.cpp b/0649-dota2-senate/0649-dota2-senate.cpp new file mode 100644 index 00000000..3c5e6518 --- /dev/null +++ b/0649-dota2-senate/0649-dota2-senate.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + string predictPartyVictory(string senate) { + queue q1, q2; + int n = senate.length(); + for(int i = 0; i q2.size())? "Radiant" : "Dire"; + } +}; \ No newline at end of file diff --git a/0649-dota2-senate/NOTES.md b/0649-dota2-senate/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0649-dota2-senate/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0650-2-keys-keyboard/0650-2-keys-keyboard.cpp b/0650-2-keys-keyboard/0650-2-keys-keyboard.cpp new file mode 100644 index 00000000..bf53ed7a --- /dev/null +++ b/0650-2-keys-keyboard/0650-2-keys-keyboard.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + + int helper(int n, int last, int tot, vector>& dp) + { + if(n < 0) + return 1e9; + + if(n == 0) + return 0; + + if(dp[n][last] != -1) + return dp[n][last]; + + int previousCopy = 1 + helper(n - last, last, tot, dp); + + int alreadyTaken = tot - n; + + int newCopy = 2 + helper(n - alreadyTaken, alreadyTaken, tot, dp); + + return dp[n][last] = min(newCopy, previousCopy); + + } + + int minSteps(int n) { + + if(n == 1) + return 0; + + vector> dp(n+1,vector(n+1, -1)); + + return helper(n-1, 1, n, dp) + 1; + + } +}; \ No newline at end of file diff --git a/0650-2-keys-keyboard/NOTES.md b/0650-2-keys-keyboard/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0650-2-keys-keyboard/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0650-2-keys-keyboard/README.md b/0650-2-keys-keyboard/README.md new file mode 100644 index 00000000..4d778549 --- /dev/null +++ b/0650-2-keys-keyboard/README.md @@ -0,0 +1,33 @@ +

650. 2 Keys Keyboard

Medium


There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:

+ +
    +
  • Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
  • +
  • Paste: You can paste the characters which are copied last time.
  • +
+ +

Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 3
+Explanation: Initially, we have one character 'A'.
+In step 1, we use Copy All operation.
+In step 2, we use Paste operation to get 'AA'.
+In step 3, we use Paste operation to get 'AAA'.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/0652-find-duplicate-subtrees/0652-find-duplicate-subtrees.cpp b/0652-find-duplicate-subtrees/0652-find-duplicate-subtrees.cpp new file mode 100644 index 00000000..18d632b6 --- /dev/null +++ b/0652-find-duplicate-subtrees/0652-find-duplicate-subtrees.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector v; + unordered_map > m; + + string help(TreeNode *root) + { + if(root == NULL) + return "#"; + string ans = to_string(root->val) + "-" + help(root->left) + "-" + help(root->right); + m[ans].push_back(root); + return ans; + } + + vector findDuplicateSubtrees(TreeNode* root) { + if(root == NULL) + return v; + + help(root); + + for(auto i = m.begin(); i != m.end(); i++) + { + if(i->second.size() > 1) + v.push_back(i->second[0]); + } + return v; + } +}; \ No newline at end of file diff --git a/0652-find-duplicate-subtrees/README.md b/0652-find-duplicate-subtrees/README.md new file mode 100644 index 00000000..b0404998 --- /dev/null +++ b/0652-find-duplicate-subtrees/README.md @@ -0,0 +1,33 @@ +

652. Find Duplicate Subtrees

Medium


Given the root of a binary tree, return all duplicate subtrees.

+ +

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

+ +

Two trees are duplicate if they have the same structure with the same node values.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,null,2,4,null,null,4]
+Output: [[2,4],[4]]
+
+ +

Example 2:

+ +
Input: root = [2,1,1]
+Output: [[1]]
+
+ +

Example 3:

+ +
Input: root = [2,2,2,3,null,3,null]
+Output: [[2,3],[3]]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the tree will be in the range [1, 5000]
  • +
  • -200 <= Node.val <= 200
  • +
+
\ No newline at end of file diff --git a/0661-image-smoother/0661-image-smoother.cpp b/0661-image-smoother/0661-image-smoother.cpp new file mode 100644 index 00000000..81933ccf --- /dev/null +++ b/0661-image-smoother/0661-image-smoother.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector> imageSmoother(vector>& img) { + int rows = img.size(); + int cols = img[0].size(); + vector> result(rows, vector(cols, 0)); + + for (int i = 0; i < rows; ++i) + { + for (int j = 0; j < cols; ++j) + { + int total_sum = 0; + int count = 0; + + for (int l = max(0, i-1); l < min(rows, i+2); ++l) + { + for (int k = max(0, j-1); k < min(cols, j+2); ++k) + { + total_sum += img[l][k]; + count += 1; + } + } + + result[i][j] = total_sum / count; + } + } + + return result; + } +}; \ No newline at end of file diff --git a/0661-image-smoother/README.md b/0661-image-smoother/README.md new file mode 100644 index 00000000..6bd8ee84 --- /dev/null +++ b/0661-image-smoother/README.md @@ -0,0 +1,35 @@ +

661. Image Smoother

Easy


An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).

+ +

Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.

+ +

 

+

Example 1:

+ +
Input: img = [[1,1,1],[1,0,1],[1,1,1]]
+Output: [[0,0,0],[0,0,0],[0,0,0]]
+Explanation:
+For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
+For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
+For the point (1,1): floor(8/9) = floor(0.88888889) = 0
+
+ +

Example 2:

+ +
Input: img = [[100,200,100],[200,50,200],[100,200,100]]
+Output: [[137,141,137],[141,138,141],[137,141,137]]
+Explanation:
+For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
+For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
+For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
+
+ +

 

+

Constraints:

+ +
    +
  • m == img.length
  • +
  • n == img[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= img[i][j] <= 255
  • +
+
\ No newline at end of file diff --git a/0662-maximum-width-of-binary-tree/0662-maximum-width-of-binary-tree.cpp b/0662-maximum-width-of-binary-tree/0662-maximum-width-of-binary-tree.cpp new file mode 100644 index 00000000..8effb2e0 --- /dev/null +++ b/0662-maximum-width-of-binary-tree/0662-maximum-width-of-binary-tree.cpp @@ -0,0 +1,52 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +#define ll long long int + +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + + if(!root) + return 0; + + ll res = 1; + + queue> q; + + q.push({root,0}); + + while(!q.empty()) + { + ll start = q.front().second; + ll end = q.back().second; + + res = max(res, end - start + 1); + + ll size = q.size(); + + for(int i = 0; i < size; ++i) + { + ll idx = q.front().second - start; + TreeNode* curr = q.front().first; + + q.pop(); + + if(curr->left) + q.push({curr->left,(ll)(2*idx)}); + if(curr->right) + q.push({curr->right,(ll)(2*idx)+ 1}); + } + } + + return (int)res; + } +}; \ No newline at end of file diff --git a/0662-maximum-width-of-binary-tree/NOTES.md b/0662-maximum-width-of-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0662-maximum-width-of-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0662-maximum-width-of-binary-tree/README.md b/0662-maximum-width-of-binary-tree/README.md new file mode 100644 index 00000000..3a8386e1 --- /dev/null +++ b/0662-maximum-width-of-binary-tree/README.md @@ -0,0 +1,38 @@ +

662. Maximum Width of Binary Tree

Medium


Given the root of a binary tree, return the maximum width of the given tree.

+ +

The maximum width of a tree is the maximum width among all levels.

+ +

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

+ +

It is guaranteed that the answer will in the range of a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
Input: root = [1,3,2,5,3,null,9]
+Output: 4
+Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
+
+ +

Example 2:

+ +
Input: root = [1,3,2,5,null,null,9,6,null,7]
+Output: 7
+Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
+
+ +

Example 3:

+ +
Input: root = [1,3,2,5]
+Output: 2
+Explanation: The maximum width exists in the second level with length 2 (3,2).
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3000].
  • +
  • -100 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0664-strange-printer/0664-strange-printer.cpp b/0664-strange-printer/0664-strange-printer.cpp new file mode 100644 index 00000000..42000946 --- /dev/null +++ b/0664-strange-printer/0664-strange-printer.cpp @@ -0,0 +1,30 @@ + +class Solution +{ +private: + int f[100][100]; + +private: + int dfs(const std::string& s, int l, int r) + { + if (l > r) return 0; + if (f[l][r]) return f[l][r]; + f[l][r] = dfs(s, l, r - 1) + 1; + for (int i = l; i < r; ++i) + { + if (s[i] == s[r]) + { + f[l][r] = std::min(f[l][r], dfs(s, l, i) + dfs(s, i + 1, r - 1)); + } + } + return f[l][r]; + } + +public: + int strangePrinter(std::string s) + { + memset(f, 0, sizeof(f)); + int len = (int)s.size(); + return dfs(s, 0, len - 1); + } +}; \ No newline at end of file diff --git a/0664-strange-printer/NOTES.md b/0664-strange-printer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0664-strange-printer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0664-strange-printer/README.md b/0664-strange-printer/README.md new file mode 100644 index 00000000..0a0cb354 --- /dev/null +++ b/0664-strange-printer/README.md @@ -0,0 +1,32 @@ +

664. Strange Printer

Hard


There is a strange printer with the following two special properties:

+ +
    +
  • The printer can only print a sequence of the same character each time.
  • +
  • At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
  • +
+ +

Given a string s, return the minimum number of turns the printer needed to print it.

+ +

 

+

Example 1:

+ +
Input: s = "aaabbb"
+Output: 2
+Explanation: Print "aaa" first and then print "bbb".
+
+ +

Example 2:

+ +
Input: s = "aba"
+Output: 2
+Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0673-number-of-longest-increasing-subsequence/0673-number-of-longest-increasing-subsequence.cpp b/0673-number-of-longest-increasing-subsequence/0673-number-of-longest-increasing-subsequence.cpp new file mode 100644 index 00000000..414af113 --- /dev/null +++ b/0673-number-of-longest-increasing-subsequence/0673-number-of-longest-increasing-subsequence.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int findNumberOfLIS(vector& nums) { + + int n = nums.size(); + + vector dp(n, 1) , cnt(n , 1); + + int maxi = 0, ans = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < i; ++j) + { + if(nums[i] > nums[j] and dp[j] + 1 > dp[i]) + { + dp[i] = 1 + dp[j]; + cnt[i] = cnt[j]; + } + + else if(nums[i] > nums[j] and dp[j] + 1 == dp[i]) + { + cnt[i] += cnt[j]; + } + } + + maxi = max(maxi, dp[i]); + } + + for(int i = 0; i < n; ++i) + { + if(dp[i] == maxi) + ans += cnt[i]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0673-number-of-longest-increasing-subsequence/NOTES.md b/0673-number-of-longest-increasing-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0673-number-of-longest-increasing-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0673-number-of-longest-increasing-subsequence/README.md b/0673-number-of-longest-increasing-subsequence/README.md new file mode 100644 index 00000000..31ee34a3 --- /dev/null +++ b/0673-number-of-longest-increasing-subsequence/README.md @@ -0,0 +1,27 @@ +

673. Number of Longest Increasing Subsequence

Medium


Given an integer array nums, return the number of longest increasing subsequences.

+ +

Notice that the sequence has to be strictly increasing.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,5,4,7]
+Output: 2
+Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2]
+Output: 5
+Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2000
  • +
  • -106 <= nums[i] <= 106
  • +
+
\ No newline at end of file diff --git a/0678-valid-parenthesis-string/NOTES.md b/0678-valid-parenthesis-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0678-valid-parenthesis-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0678-valid-parenthesis-string/README.md b/0678-valid-parenthesis-string/README.md new file mode 100644 index 00000000..26a61d26 --- /dev/null +++ b/0678-valid-parenthesis-string/README.md @@ -0,0 +1,30 @@ +

678. Valid Parenthesis String

Medium


Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

+ +

The following rules define a valid string:

+ +
    +
  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • +
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • +
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • +
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
  • +
+ +

 

+

Example 1:

+
Input: s = "()"
+Output: true
+

Example 2:

+
Input: s = "(*)"
+Output: true
+

Example 3:

+
Input: s = "(*))"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s[i] is '(', ')' or '*'.
  • +
+
\ No newline at end of file diff --git a/0684-redundant-connection/0684-redundant-connection.cpp b/0684-redundant-connection/0684-redundant-connection.cpp new file mode 100644 index 00000000..f9c2bb42 --- /dev/null +++ b/0684-redundant-connection/0684-redundant-connection.cpp @@ -0,0 +1,104 @@ +class DSU +{ + private: + vector rank, parent, size; + + public: + DSU(int n) + { + rank.resize(n+1, 0); + parent.resize(n+1); + size.resize(n+1, 0); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + return u; + + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + vector findRedundantConnection(vector>& edges) { + + int n = edges.size(); + + DSU dsu(n); + + vector ans; + + for(auto itr : edges) + { + int u = itr[0]; + int v = itr[1]; + + if(dsu.isSame(u,v)) + { + ans.clear(); + ans.push_back(u); + ans.push_back(v); + } + else + dsu.unionByRank(u,v); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0684-redundant-connection/NOTES.md b/0684-redundant-connection/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0684-redundant-connection/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0684-redundant-connection/README.md b/0684-redundant-connection/README.md new file mode 100644 index 00000000..73428588 --- /dev/null +++ b/0684-redundant-connection/README.md @@ -0,0 +1,32 @@ +

684. Redundant Connection

Medium


In this problem, a tree is an undirected graph that is connected and has no cycles.

+ +

You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.

+ +

Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.

+ +

 

+

Example 1:

+ +
Input: edges = [[1,2],[1,3],[2,3]]
+Output: [2,3]
+
+ +

Example 2:

+ +
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
+Output: [1,4]
+
+ +

 

+

Constraints:

+ +
    +
  • n == edges.length
  • +
  • 3 <= n <= 1000
  • +
  • edges[i].length == 2
  • +
  • 1 <= ai < bi <= edges.length
  • +
  • ai != bi
  • +
  • There are no repeated edges.
  • +
  • The given graph is connected.
  • +
+
\ No newline at end of file diff --git a/0688-knight-probability-in-chessboard/0688-knight-probability-in-chessboard.cpp b/0688-knight-probability-in-chessboard/0688-knight-probability-in-chessboard.cpp new file mode 100644 index 00000000..ce550e79 --- /dev/null +++ b/0688-knight-probability-in-chessboard/0688-knight-probability-in-chessboard.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + double knightProbability(int n, int k, int row, int column) { + + if(n == 1 and k == 1) + return 0.0; + + vector> curr(n, vector(n,0.0)); + + curr[row][column] = 1.0; + + for(int moves = 1; moves <= k; ++moves) + { + vector> next(n, vector(n,0.0)); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(curr[i][j] != 0) + { + int dx[8]={ 2, 1, -1, -2, -2, -1, 1, 2 }; + int dy[8]={ 1, 2, 2, 1, -1, -2, -2, -1 }; + + for(int k = 0; k < 8; ++k) + { + int newx = dx[k] + i; + int newy = dy[k] + j; + + if(newx >= 0 and newx < n and newy >= 0 and newy < n) + { + next[newx][newy] += curr[i][j]/8.0; + } + } + } + } + } + + curr = next; + } + + double ans = 0.0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + ans += curr[i][j]; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0688-knight-probability-in-chessboard/README.md b/0688-knight-probability-in-chessboard/README.md new file mode 100644 index 00000000..66bda063 --- /dev/null +++ b/0688-knight-probability-in-chessboard/README.md @@ -0,0 +1,35 @@ +

688. Knight Probability in Chessboard

Medium


On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).

+ +

A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.

+ +

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

+ +

The knight continues moving until it has made exactly k moves or has moved off the chessboard.

+ +

Return the probability that the knight remains on the board after it has stopped moving.

+ +

 

+

Example 1:

+ +
Input: n = 3, k = 2, row = 0, column = 0
+Output: 0.06250
+Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
+From each of those positions, there are also two moves that will keep the knight on the board.
+The total probability the knight stays on the board is 0.0625.
+
+ +

Example 2:

+ +
Input: n = 1, k = 0, row = 0, column = 0
+Output: 1.00000
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 25
  • +
  • 0 <= k <= 100
  • +
  • 0 <= row, column <= n - 1
  • +
+
\ No newline at end of file diff --git a/0692-top-k-frequent-words/0692-top-k-frequent-words.cpp b/0692-top-k-frequent-words/0692-top-k-frequent-words.cpp new file mode 100644 index 00000000..b96d979b --- /dev/null +++ b/0692-top-k-frequent-words/0692-top-k-frequent-words.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector topKFrequent(vector& words, int k) { + + map mp; + vector ans; + for(auto itr : words) + ++mp[itr]; + + vector> vp; + for(auto itr : mp) + { + vp.push_back({itr.second,itr.first}); + } + + sort(vp.begin(),vp.end(),[&](const auto &a , auto& b){ + if(a.first == b.first) + return a.second < b.second; + return a.first > b.first; + }); + + for(int i = 0; i692. Top K Frequent Words

Medium


Given an array of strings words and an integer k, return the k most frequent strings.

+ +

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

+ +

 

+

Example 1:

+ +
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
+Output: ["i","love"]
+Explanation: "i" and "love" are the two most frequent words.
+Note that "i" comes before "love" due to a lower alphabetical order.
+
+ +

Example 2:

+ +
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
+Output: ["the","is","sunny","day"]
+Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 500
  • +
  • 1 <= words[i].length <= 10
  • +
  • words[i] consists of lowercase English letters.
  • +
  • k is in the range [1, The number of unique words[i]]
  • +
+ +

 

+

Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?

+
\ No newline at end of file diff --git a/0698-partition-to-k-equal-sum-subsets/0698-partition-to-k-equal-sum-subsets.cpp b/0698-partition-to-k-equal-sum-subsets/0698-partition-to-k-equal-sum-subsets.cpp new file mode 100644 index 00000000..77c96166 --- /dev/null +++ b/0698-partition-to-k-equal-sum-subsets/0698-partition-to-k-equal-sum-subsets.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + bool helper(int idx, int currSum, int targetSum, vector& nums, vector& visited, int k) + { + if(k == 0) return true; + if(currSum > targetSum) return false; + if(currSum == targetSum) return helper(nums.size()-1, 0, targetSum, nums, visited, k-1); + + for(int i = idx; i>= 0; --i) + { + if(!visited[i]) + { + visited[i] = true; + if(helper(i - 1, currSum + nums[i], targetSum, nums, visited, k)) + return true; + visited[i] = false; + } + } + + return false; + } + + bool canPartitionKSubsets(vector& nums, int k) { + + int n = nums.size(); + int sum = accumulate(nums.begin(),nums.end(),0); + int maxi = *max_element(nums.begin(),nums.end()); + + if(sum % k != 0 or maxi > sum/k) + return false; + + vector visited(n,false); + + return helper(n-1, 0, sum/k, nums,visited,k); + } +}; \ No newline at end of file diff --git a/0698-partition-to-k-equal-sum-subsets/NOTES.md b/0698-partition-to-k-equal-sum-subsets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0698-partition-to-k-equal-sum-subsets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0698-partition-to-k-equal-sum-subsets/README.md b/0698-partition-to-k-equal-sum-subsets/README.md new file mode 100644 index 00000000..45cec40d --- /dev/null +++ b/0698-partition-to-k-equal-sum-subsets/README.md @@ -0,0 +1,25 @@ +

698. Partition to K Equal Sum Subsets

Medium


Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

+ +

 

+

Example 1:

+ +
Input: nums = [4,3,2,3,5,2,1], k = 4
+Output: true
+Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4], k = 3
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 16
  • +
  • 1 <= nums[i] <= 104
  • +
  • The frequency of each element is in the range [1, 4].
  • +
+
\ No newline at end of file diff --git a/0703-kth-largest-element-in-a-stream/0703-kth-largest-element-in-a-stream.cpp b/0703-kth-largest-element-in-a-stream/0703-kth-largest-element-in-a-stream.cpp new file mode 100644 index 00000000..9b60ab35 --- /dev/null +++ b/0703-kth-largest-element-in-a-stream/0703-kth-largest-element-in-a-stream.cpp @@ -0,0 +1,37 @@ +class KthLargest { + +private: + priority_queue, greater> pq; + int size; + +public: + KthLargest(int k, vector& nums) { + + size = k; + + for(auto itr : nums) + { + pq.push(itr); + + if(pq.size() > k) + pq.pop(); + } + } + + int add(int val) { + + pq.push(val); + + if(pq.size() > size) + pq.pop(); + + return pq.top(); + + } +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ \ No newline at end of file diff --git a/0703-kth-largest-element-in-a-stream/NOTES.md b/0703-kth-largest-element-in-a-stream/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0703-kth-largest-element-in-a-stream/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0703-kth-largest-element-in-a-stream/README.md b/0703-kth-largest-element-in-a-stream/README.md new file mode 100644 index 00000000..009d56ff --- /dev/null +++ b/0703-kth-largest-element-in-a-stream/README.md @@ -0,0 +1,39 @@ +

703. Kth Largest Element in a Stream

Easy


Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

+ +

Implement KthLargest class:

+ +
    +
  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • +
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
  • +
+ +

 

+

Example 1:

+ +
Input
+["KthLargest", "add", "add", "add", "add", "add"]
+[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
+Output
+[null, 4, 5, 5, 8, 8]
+
+Explanation
+KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
+kthLargest.add(3);   // return 4
+kthLargest.add(5);   // return 5
+kthLargest.add(10);  // return 5
+kthLargest.add(9);   // return 8
+kthLargest.add(4);   // return 8
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= 104
  • +
  • 0 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • -104 <= val <= 104
  • +
  • At most 104 calls will be made to add.
  • +
  • It is guaranteed that there will be at least k elements in the array when you search for the kth element.
  • +
+
\ No newline at end of file diff --git a/0704-binary-search/0704-binary-search.cpp b/0704-binary-search/0704-binary-search.cpp new file mode 100644 index 00000000..fda7754e --- /dev/null +++ b/0704-binary-search/0704-binary-search.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int search(vector& nums, int target) { + + int start = 0, end = nums.size()-1; + + while(start <= end) + { + int mid = start + (end - start)/2; + + if(nums[mid] == target) + return mid; + else if(nums[mid] > target) + end = mid - 1; + else + start = mid + 1; + } + + return -1; + + } +}; \ No newline at end of file diff --git a/0704-binary-search/README.md b/0704-binary-search/README.md new file mode 100644 index 00000000..2a0b6637 --- /dev/null +++ b/0704-binary-search/README.md @@ -0,0 +1,29 @@ +

704. Binary Search

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [-1,0,3,5,9,12], target = 9
+Output: 4
+Explanation: 9 exists in nums and its index is 4
+
+ +

Example 2:

+ +
Input: nums = [-1,0,3,5,9,12], target = 2
+Output: -1
+Explanation: 2 does not exist in nums so return -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 < nums[i], target < 104
  • +
  • All the integers in nums are unique.
  • +
  • nums is sorted in ascending order.
  • +
+
\ No newline at end of file diff --git a/0705-design-hashset/0705-design-hashset.cpp b/0705-design-hashset/0705-design-hashset.cpp new file mode 100644 index 00000000..f8bc114b --- /dev/null +++ b/0705-design-hashset/0705-design-hashset.cpp @@ -0,0 +1,62 @@ +class MyHashSet { +public: + + vector> hash; + int size = 10001; + + MyHashSet() { + hash.resize(size); + } + + void add(int key) { + + int idx = key % size; + + for(auto& itr : hash[idx]) + { + if(itr == key) + { + return; + } + } + + hash[idx].push_back(key); + } + + void remove(int key) { + + int idx = key % size; + + for(auto itr = hash[idx].begin(); itr != hash[idx].end(); ++itr) + { + if(*itr == key) + { + hash[idx].erase(itr); + return; + } + } + + } + + bool contains(int key) { + + int idx = key % size; + + for(auto& itr : hash[idx]) + { + if(itr == key) + { + return true; + } + } + return false; + } +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet* obj = new MyHashSet(); + * obj->add(key); + * obj->remove(key); + * bool param_3 = obj->contains(key); + */ \ No newline at end of file diff --git a/0705-design-hashset/NOTES.md b/0705-design-hashset/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0705-design-hashset/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0705-design-hashset/README.md b/0705-design-hashset/README.md new file mode 100644 index 00000000..4c189349 --- /dev/null +++ b/0705-design-hashset/README.md @@ -0,0 +1,38 @@ +

705. Design HashSet

Easy


Design a HashSet without using any built-in hash table libraries.

+ +

Implement MyHashSet class:

+ +
    +
  • void add(key) Inserts the value key into the HashSet.
  • +
  • bool contains(key) Returns whether the value key exists in the HashSet or not.
  • +
  • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
+[[], [1], [2], [1], [3], [2], [2], [2], [2]]
+Output
+[null, null, null, true, false, null, true, null, false]
+
+Explanation
+MyHashSet myHashSet = new MyHashSet();
+myHashSet.add(1);      // set = [1]
+myHashSet.add(2);      // set = [1, 2]
+myHashSet.contains(1); // return True
+myHashSet.contains(3); // return False, (not found)
+myHashSet.add(2);      // set = [1, 2]
+myHashSet.contains(2); // return True
+myHashSet.remove(2);   // set = [1]
+myHashSet.contains(2); // return False, (already removed)
+ +

 

+

Constraints:

+ +
    +
  • 0 <= key <= 106
  • +
  • At most 104 calls will be made to add, remove, and contains.
  • +
+
\ No newline at end of file diff --git a/0706-design-hashmap/0706-design-hashmap.cpp b/0706-design-hashmap/0706-design-hashmap.cpp new file mode 100644 index 00000000..d991530d --- /dev/null +++ b/0706-design-hashmap/0706-design-hashmap.cpp @@ -0,0 +1,63 @@ +class MyHashMap { +public: + + vector> > hash; + int size = 10001; + + MyHashMap() { + hash.resize(size); + } + + void put(int key, int value) { + int idx = key % size; + + for(auto& [k, val] : hash[idx]) + { + if(k == key) + { + val = value; + return; + } + } + + hash[idx].push_back({key, value}); + } + + int get(int key) { + + int idx = key % size; + + if(hash[idx].empty()) + return -1; + + for(auto& [k, val] : hash[idx]) + { + if(k == key) + return val; + } + + return -1; + } + + void remove(int key) { + + int idx = key % size; + + for(auto itr = hash[idx].begin(); itr != hash[idx].end(); ++itr) + { + if(itr->first == key) + { + hash[idx].erase(itr); + return; + } + } + } +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap* obj = new MyHashMap(); + * obj->put(key,value); + * int param_2 = obj->get(key); + * obj->remove(key); + */ \ No newline at end of file diff --git a/0706-design-hashmap/README.md b/0706-design-hashmap/README.md new file mode 100644 index 00000000..830381e2 --- /dev/null +++ b/0706-design-hashmap/README.md @@ -0,0 +1,40 @@ +

706. Design HashMap

Easy


Design a HashMap without using any built-in hash table libraries.

+ +

Implement the MyHashMap class:

+ +
    +
  • MyHashMap() initializes the object with an empty map.
  • +
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
  • +
  • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • +
  • void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
+[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
+Output
+[null, null, null, 1, -1, null, 1, null, -1]
+
+Explanation
+MyHashMap myHashMap = new MyHashMap();
+myHashMap.put(1, 1); // The map is now [[1,1]]
+myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
+myHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]
+myHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
+myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
+myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
+myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
+myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= key, value <= 106
  • +
  • At most 104 calls will be made to put, get, and remove.
  • +
+
\ No newline at end of file diff --git a/0712-minimum-ascii-delete-sum-for-two-strings/0712-minimum-ascii-delete-sum-for-two-strings.cpp b/0712-minimum-ascii-delete-sum-for-two-strings/0712-minimum-ascii-delete-sum-for-two-strings.cpp new file mode 100644 index 00000000..679cb5b9 --- /dev/null +++ b/0712-minimum-ascii-delete-sum-for-two-strings/0712-minimum-ascii-delete-sum-for-two-strings.cpp @@ -0,0 +1,53 @@ +class Solution { + +private: + int helper(int i, int j, int n, int m, string& s1, string& s2, vector>& dp) + { + if(i == n and j == m) + return 0; + if(i == n) + { + int deleteS2 = 0; + + for(int k = j; k < m; ++k) + { + deleteS2 += s2[k]; + } + + return deleteS2; + } + + if(j == m) + { + int deleteS1 = 0; + + for(int k = i; k < n; ++k) + { + deleteS1 += s1[k]; + } + + return deleteS1; + } + + if(dp[i][j] != -1) + return dp[i][j]; + + if(s1[i] == s2[j]) + return dp[i][j] = helper(i+1, j+1, n, m, s1, s2, dp); + else + { + return dp[i][j] = min(s1[i] + helper(i+1, j, n, m, s1, s2, dp), s2[j] + helper(i, j+1, n, m, s1, s2, dp)); + } + } + +public: + int minimumDeleteSum(string s1, string s2) { + + int n = s1.size(), m = s2.size(); + + vector> dp(n+1, vector(m+1, -1)); + + return helper(0, 0, n, m, s1, s2, dp); + + } +}; \ No newline at end of file diff --git a/0712-minimum-ascii-delete-sum-for-two-strings/NOTES.md b/0712-minimum-ascii-delete-sum-for-two-strings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0712-minimum-ascii-delete-sum-for-two-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0712-minimum-ascii-delete-sum-for-two-strings/README.md b/0712-minimum-ascii-delete-sum-for-two-strings/README.md new file mode 100644 index 00000000..4bc11e8d --- /dev/null +++ b/0712-minimum-ascii-delete-sum-for-two-strings/README.md @@ -0,0 +1,31 @@ +

712. Minimum ASCII Delete Sum for Two Strings

Medium


Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.

+ +

 

+

Example 1:

+ +
Input: s1 = "sea", s2 = "eat"
+Output: 231
+Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
+Deleting "t" from "eat" adds 116 to the sum.
+At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
+
+ +

Example 2:

+ +
Input: s1 = "delete", s2 = "leet"
+Output: 403
+Explanation: Deleting "dee" from "delete" to turn the string into "let",
+adds 100[d] + 101[e] + 101[e] to the sum.
+Deleting "e" from "leet" adds 101[e] to the sum.
+At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
+If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s1.length, s2.length <= 1000
  • +
  • s1 and s2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0713-subarray-product-less-than-k/0713-subarray-product-less-than-k.cpp b/0713-subarray-product-less-than-k/0713-subarray-product-less-than-k.cpp new file mode 100644 index 00000000..fd352156 --- /dev/null +++ b/0713-subarray-product-less-than-k/0713-subarray-product-less-than-k.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + + int n = nums.size(); + + int i = 0, j = 0; + + long long prod = 1, cnt = 0; + + if(k == 0 or k == 1) + return 0; + + while(j < n) + { + prod *= nums[j]; + + while(prod >= k) + { + prod /= nums[i++]; + } + + if(prod < k) + cnt += (j - i + 1); + + ++j; + } + + return cnt; + + } +}; \ No newline at end of file diff --git a/0713-subarray-product-less-than-k/NOTES.md b/0713-subarray-product-less-than-k/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0713-subarray-product-less-than-k/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0713-subarray-product-less-than-k/README.md b/0713-subarray-product-less-than-k/README.md new file mode 100644 index 00000000..92b81e11 --- /dev/null +++ b/0713-subarray-product-less-than-k/README.md @@ -0,0 +1,27 @@ +

713. Subarray Product Less Than K

Medium


Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

+ +

 

+

Example 1:

+ +
Input: nums = [10,5,2,6], k = 100
+Output: 8
+Explanation: The 8 subarrays that have product less than 100 are:
+[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
+Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3], k = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • 1 <= nums[i] <= 1000
  • +
  • 0 <= k <= 106
  • +
+
\ No newline at end of file diff --git a/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.cpp b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.cpp new file mode 100644 index 00000000..ed8980a0 --- /dev/null +++ b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.cpp @@ -0,0 +1,32 @@ +class Solution { + +private: + int helper(int idx, bool buy, int n, vector& prices, int fee, vector>& dp) + { + if(idx == n) + return 0; + + if(dp[idx][buy] != -1) + return dp[idx][buy]; + + int take = INT_MIN, take2 = INT_MIN; + + if(!buy) + take = max(-prices[idx] + helper(idx+1, !buy, n, prices, fee, dp), helper(idx+1, buy, n, prices, fee, dp)); + else + take2 = max(prices[idx] - fee + helper(idx+1, !buy, n, prices, fee, dp), helper(idx+1, buy, n, prices, fee, dp)); + + return dp[idx][buy] = max({take, take2}); + } + +public: + int maxProfit(vector& prices, int fee) { + + int n = prices.size(); + + vector> dp(n, vector(2, -1)); + + return helper(0, 0, n, prices, fee, dp); + + } +}; \ No newline at end of file diff --git a/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/NOTES.md b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/README.md b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/README.md new file mode 100644 index 00000000..c93f20ad --- /dev/null +++ b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee/README.md @@ -0,0 +1,34 @@ +

714. Best Time to Buy and Sell Stock with Transaction Fee

Medium


You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
Input: prices = [1,3,2,8,4,9], fee = 2
+Output: 8
+Explanation: The maximum profit can be achieved by:
+- Buying at prices[0] = 1
+- Selling at prices[3] = 8
+- Buying at prices[4] = 4
+- Selling at prices[5] = 9
+The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
+
+ +

Example 2:

+ +
Input: prices = [1,3,7,5,10,3], fee = 3
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 5 * 104
  • +
  • 1 <= prices[i] < 5 * 104
  • +
  • 0 <= fee < 5 * 104
  • +
+
\ No newline at end of file diff --git a/0719-find-k-th-smallest-pair-distance/0719-find-k-th-smallest-pair-distance.cpp b/0719-find-k-th-smallest-pair-distance/0719-find-k-th-smallest-pair-distance.cpp new file mode 100644 index 00000000..af0b24dc --- /dev/null +++ b/0719-find-k-th-smallest-pair-distance/0719-find-k-th-smallest-pair-distance.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + + int n = nums.size(), N = 1000000; + vector cnt(N, 0); + + for (int i = 0; i < n; i++) { + for (int j = i+1; j < n; j++) + cnt[abs(nums[i]-nums[j])]++; + } + + for (int i = 0; i < N; i++) { + if (cnt[i] >= k) return i; + k -= cnt[i]; + } + + return 0; + } +}; \ No newline at end of file diff --git a/0719-find-k-th-smallest-pair-distance/NOTES.md b/0719-find-k-th-smallest-pair-distance/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0719-find-k-th-smallest-pair-distance/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0719-find-k-th-smallest-pair-distance/README.md b/0719-find-k-th-smallest-pair-distance/README.md new file mode 100644 index 00000000..cdd3d60c --- /dev/null +++ b/0719-find-k-th-smallest-pair-distance/README.md @@ -0,0 +1,38 @@ +

719. Find K-th Smallest Pair Distance

Hard


The distance of a pair of integers a and b is defined as the absolute difference between a and b.

+ +

Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,1], k = 1
+Output: 0
+Explanation: Here are all the pairs:
+(1,3) -> 2
+(1,1) -> 0
+(3,1) -> 2
+Then the 1st smallest distance pair is (1,1), and its distance is 0.
+
+ +

Example 2:

+ +
Input: nums = [1,1,1], k = 2
+Output: 0
+
+ +

Example 3:

+ +
Input: nums = [1,6,1], k = 3
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 2 <= n <= 104
  • +
  • 0 <= nums[i] <= 106
  • +
  • 1 <= k <= n * (n - 1) / 2
  • +
+
\ No newline at end of file diff --git a/0720-longest-word-in-dictionary/0720-longest-word-in-dictionary.cpp b/0720-longest-word-in-dictionary/0720-longest-word-in-dictionary.cpp new file mode 100644 index 00000000..c2e2fdd0 --- /dev/null +++ b/0720-longest-word-in-dictionary/0720-longest-word-in-dictionary.cpp @@ -0,0 +1,224 @@ +class Node +{ + +public: + Node *child[26] = {nullptr}; + bool isWord = false; + int cntEndWith = 0; + int cntPrefix = 0; + + bool containsKey(char ch) + { + return (child[ch - 'a'] != nullptr); + } + + void put(char ch, Node *node) + { + child[ch - 'a'] = node; + } + + Node *get(char ch) + { + return child[ch - 'a']; + } + + void setEnd() + { + isWord = true; + } + + void remEnd() + { + isWord = false; + } + + bool isEnd() + { + return isWord; + } + + void increaseEnd() + { + ++cntEndWith; + } + + void increasePrefix() + { + ++cntPrefix; + } + + void deleteEnd() + { + --cntEndWith; + } + + void reducePrefix() + { + --cntPrefix; + } + + int getEnd() + { + return cntEndWith; + } + + int getPrefix() + { + return cntPrefix; + } +}; + +class Trie +{ + +private: + Node *root; + +public: + Trie() + { + root = new Node(); + } + + // insert string into trie data structure + void insert(string &word) + { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (!temp->containsKey(word[i])) + temp->put(word[i], new Node()); + temp = temp->get(word[i]); + temp->increasePrefix(); + } + temp->increaseEnd(); + temp->setEnd(); + } + + // if given word exist + bool search(string &word) + { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (!temp->containsKey(word[i])) + return false; + temp = temp->get(word[i]); + } + return temp->isEnd(); + } + + // if word with given prefix exist + bool startsWith(string &prefix) + { + Node *temp = root; + for (int i = 0; i < prefix.size(); ++i) + { + if (!temp->containsKey(prefix[i])) + return false; + temp = temp->get(prefix[i]); + } + return true; + } + + // check if all prefixes exist + bool checkIfAllPrefixesExists(string &word) + { + Node *temp = root; + bool ok = true; + for (int i = 0; i < word.size(); ++i) + { + if (temp->containsKey(word[i])) + { + temp = temp->get(word[i]); + ok = ok & temp->isEnd(); + } + else + return false; + } + return ok; + } + + // count frequency of given word + int countWordsEqualTo(string &word) + { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (temp->containsKey(word[i])) + temp = temp->get(word[i]); + else + return 0; + } + return temp->getEnd(); + } + + // count words contains same given Prefix + int countWordsStartingWith(string &word) + { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (temp->containsKey(word[i])) + temp = temp->get(word[i]); + else + return 0; + } + return temp->getPrefix(); + } + + // erase word + // assuming that word exists + void erase(string &word) + { + Node *temp = root; + for (int i = 0; i < word.size(); ++i) + { + if (temp->containsKey(word[i])) + { + temp = temp->get(word[i]); + temp->reducePrefix(); + } + else + return; + } + temp->deleteEnd(); + + // if no more count of word exist then set isWord to false word not exist + if (temp->getEnd() == 0) + temp->remEnd(); + } +}; + +// Trie *obj = new Trie(); +// obj->insert(word); +// obj->search(word); // is exist +// obj->startsWith(word); // prefix exist +// obj->checkIfAllPrefixesExists(word) // all prefixes of string +// obj->countWordsEqualTo(word); // freq of word +// obj->countWordsStartingWith(str) // freq of prefix +// obj->erase(word); + + +class Solution { +public: + string longestWord(vector& words) { + Trie *obj = new Trie(); + + for(auto word : words) + obj->insert(word); + + string ans = ""; + for(auto word : words) + { + if(obj->checkIfAllPrefixesExists(word)) + { + if(ans.size() < word.size()) + ans = word; + else if(ans.size() == word.size() and word < ans) + ans = word; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/0720-longest-word-in-dictionary/NOTES.md b/0720-longest-word-in-dictionary/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0720-longest-word-in-dictionary/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0721-accounts-merge/0721-accounts-merge.cpp b/0721-accounts-merge/0721-accounts-merge.cpp new file mode 100644 index 00000000..f9b6740f --- /dev/null +++ b/0721-accounts-merge/0721-accounts-merge.cpp @@ -0,0 +1,136 @@ +class DSU{ + + private: + + vector rank, parent, size; + + public: + + DSU(int n) + { + rank.resize(n+1, 0); + parent.resize(n+1); + size.resize(n+1, 1); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(parent[u] == u) + return u; + + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + vector> accountsMerge(vector>& accounts) { + + int n = accounts.size(); + + unordered_map mp; + + DSU dsu(n); + + for(int i = 0; i < n; ++i) + { + for(int j = 1; j < accounts[i].size(); ++j) + { + string mail = accounts[i][j]; + + if(mp.find(mail) == mp.end()) + { + mp.insert({mail, i}); + } + else + { + dsu.unionBySize(i, mp[mail]); + } + } + } + + vector merge[n]; + + for(auto itr : mp) + { + string mail = itr.first; + int idx = dsu.findParent(itr.second); + + merge[idx].push_back(mail); + } + + + vector> ans; + + for(int i = 0; i < n; ++i) + { + vector temp; + + sort(merge[i].begin(),merge[i].end()); + + if(!merge[i].empty()) + { + temp.push_back(accounts[i][0]); + + for(auto itr : merge[i]) + temp.push_back(itr); + + ans.push_back(temp); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0721-accounts-merge/NOTES.md b/0721-accounts-merge/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0721-accounts-merge/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0721-accounts-merge/README.md b/0721-accounts-merge/README.md new file mode 100644 index 00000000..3304916c --- /dev/null +++ b/0721-accounts-merge/README.md @@ -0,0 +1,35 @@ +

721. Accounts Merge

Medium


Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

+ +

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

+ +

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

+ +

 

+

Example 1:

+ +
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
+Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
+Explanation:
+The first and second John's are the same person as they have the common email "johnsmith@mail.com".
+The third John and Mary are different people as none of their email addresses are used by other accounts.
+We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
+['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
+
+ +

Example 2:

+ +
Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
+Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= accounts.length <= 1000
  • +
  • 2 <= accounts[i].length <= 10
  • +
  • 1 <= accounts[i][j].length <= 30
  • +
  • accounts[i][0] consists of English letters.
  • +
  • accounts[i][j] (for j > 0) is a valid email.
  • +
+
\ No newline at end of file diff --git a/0725-split-linked-list-in-parts/0725-split-linked-list-in-parts.cpp b/0725-split-linked-list-in-parts/0725-split-linked-list-in-parts.cpp new file mode 100644 index 00000000..73036cf3 --- /dev/null +++ b/0725-split-linked-list-in-parts/0725-split-linked-list-in-parts.cpp @@ -0,0 +1,54 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + vector splitListToParts(ListNode* head, int k) { + + vector result(k, nullptr); + + if(!head) + return result; + + int length = 0; + + ListNode* curr = head; + + while(curr) + { + ++length; + curr = curr->next; + } + + int eachPartitionLength = length / k; + int extraNodes = length % k; + + curr = head; + + ListNode* prev = nullptr; + + for(int i = 0; i < k; ++i) + { + result[i] = curr; + + for(int count = 1; count <= eachPartitionLength + (extraNodes > 0 ? 1 : 0); ++count) + { + prev = curr; + curr = curr->next; + } + + prev->next = nullptr; + --extraNodes; + } + + return result; + + } +}; \ No newline at end of file diff --git a/0725-split-linked-list-in-parts/NOTES.md b/0725-split-linked-list-in-parts/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0725-split-linked-list-in-parts/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0725-split-linked-list-in-parts/README.md b/0725-split-linked-list-in-parts/README.md new file mode 100644 index 00000000..45b55207 --- /dev/null +++ b/0725-split-linked-list-in-parts/README.md @@ -0,0 +1,35 @@ +

725. Split Linked List in Parts

Medium


Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

+ +

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

+ +

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

+ +

Return an array of the k parts.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3], k = 5
+Output: [[1],[2],[3],[],[]]
+Explanation:
+The first element output[0] has output[0].val = 1, output[0].next = null.
+The last element output[4] is null, but its string representation as a ListNode is [].
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
+Output: [[1,2,3,4],[5,6,7],[8,9,10]]
+Explanation:
+The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 1000].
  • +
  • 0 <= Node.val <= 1000
  • +
  • 1 <= k <= 50
  • +
+
\ No newline at end of file diff --git a/0735-asteroid-collision/0735-asteroid-collision.cpp b/0735-asteroid-collision/0735-asteroid-collision.cpp new file mode 100644 index 00000000..8cff6a6e --- /dev/null +++ b/0735-asteroid-collision/0735-asteroid-collision.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + vector asteroidCollision(vector& asteroids) { + + int n = asteroids.size(); + stack st; + vector ans; + + for(int i = 0; i 0) + st.push(asteroids[i]); + else + { + while(!st.empty() and st.top() > 0 and abs(asteroids[i]) > st.top()) + st.pop(); + if(!st.empty() and st.top() > 0 and st.top() == abs(asteroids[i])) + { + st.pop(); + continue; + } + if(!st.empty() and st.top() > 0 and asteroids[i] < 0) + continue; + st.push(asteroids[i]); + } + } + } + + while(!st.empty()) + { + ans.push_back(st.top()); + st.pop(); + } + + reverse(ans.begin(),ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/0735-asteroid-collision/NOTES.md b/0735-asteroid-collision/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0735-asteroid-collision/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0735-asteroid-collision/README.md b/0735-asteroid-collision/README.md new file mode 100644 index 00000000..2c3aa096 --- /dev/null +++ b/0735-asteroid-collision/README.md @@ -0,0 +1,37 @@ +

735. Asteroid Collision

Medium


We are given an array asteroids of integers representing asteroids in a row.

+ +

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

+ +

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

+ +

 

+

Example 1:

+ +
Input: asteroids = [5,10,-5]
+Output: [5,10]
+Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
+
+ +

Example 2:

+ +
Input: asteroids = [8,-8]
+Output: []
+Explanation: The 8 and -8 collide exploding each other.
+
+ +

Example 3:

+ +
Input: asteroids = [10,2,-5]
+Output: [10]
+Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= asteroids.length <= 104
  • +
  • -1000 <= asteroids[i] <= 1000
  • +
  • asteroids[i] != 0
  • +
+
\ No newline at end of file diff --git a/0739-daily-temperatures/0739-daily-temperatures.cpp b/0739-daily-temperatures/0739-daily-temperatures.cpp new file mode 100644 index 00000000..d8b2a9c3 --- /dev/null +++ b/0739-daily-temperatures/0739-daily-temperatures.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + + int n = temperatures.size(); + vector res(n,0); + // next_greater decreasin stack + + stack> st; + + for(int i = 0; i st.top().first) + { + pair here = st.top(); + st.pop(); + res[here.second] = i - here.second; + } + st.push({temperatures[i],i}); + } + + return res; + } +}; \ No newline at end of file diff --git a/0739-daily-temperatures/NOTES.md b/0739-daily-temperatures/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0739-daily-temperatures/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0739-daily-temperatures/README.md b/0739-daily-temperatures/README.md new file mode 100644 index 00000000..cb144a23 --- /dev/null +++ b/0739-daily-temperatures/README.md @@ -0,0 +1,21 @@ +

739. Daily Temperatures

Medium


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

+ +

 

+

Example 1:

+
Input: temperatures = [73,74,75,71,69,72,76,73]
+Output: [1,1,4,2,1,1,0,0]
+

Example 2:

+
Input: temperatures = [30,40,50,60]
+Output: [1,1,1,0]
+

Example 3:

+
Input: temperatures = [30,60,90]
+Output: [1,1,0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= temperatures.length <= 105
  • +
  • 30 <= temperatures[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0743-network-delay-time/0743-network-delay-time.cpp b/0743-network-delay-time/0743-network-delay-time.cpp new file mode 100644 index 00000000..0a8f688c --- /dev/null +++ b/0743-network-delay-time/0743-network-delay-time.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + + void dijkstra(vector > adj[], int& ans, int n, int k ) + { + vector visited(n+1,false); + vector dist(n+1,1e9); + + priority_queue , vector > , greater > > pq; + + pq.push({0,k}); + dist[k] = 0; + + while(!pq.empty()) + { + int curr = pq.top().second; + pq.pop(); + + if(visited[curr]) continue; + + visited[curr] = true; + + for(auto child : adj[curr]) + { + int child_v = child.first; + int wt = child.second; + + if(dist[curr] + wt < dist[child_v]) + { + dist[child_v] = dist[curr] + wt; + pq.push({dist[child_v], child_v}); + } + } + } + + ans = *max_element(dist.begin()+1,dist.end()); + + } + + + int networkDelayTime(vector>& times, int n, int k) { + + vector> adj[n+1]; + + for(auto itr : times) + adj[itr[0]].push_back({itr[1],itr[2]}); + + int ans = 1e9; + dijkstra(adj,ans, n, k); + + return ans == 1e9 ? -1 : ans; + } +}; \ No newline at end of file diff --git a/0743-network-delay-time/README.md b/0743-network-delay-time/README.md new file mode 100644 index 00000000..b8bd8fc8 --- /dev/null +++ b/0743-network-delay-time/README.md @@ -0,0 +1,36 @@ +

743. Network Delay Time

Medium


You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.

+ +

We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

+ +

 

+

Example 1:

+ +
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
+Output: 2
+
+ +

Example 2:

+ +
Input: times = [[1,2,1]], n = 2, k = 1
+Output: 1
+
+ +

Example 3:

+ +
Input: times = [[1,2,1]], n = 2, k = 2
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= n <= 100
  • +
  • 1 <= times.length <= 6000
  • +
  • times[i].length == 3
  • +
  • 1 <= ui, vi <= n
  • +
  • ui != vi
  • +
  • 0 <= wi <= 100
  • +
  • All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
  • +
+
\ No newline at end of file diff --git a/0744-find-smallest-letter-greater-than-target/README.md b/0744-find-smallest-letter-greater-than-target/README.md new file mode 100644 index 00000000..e84b96c5 --- /dev/null +++ b/0744-find-smallest-letter-greater-than-target/README.md @@ -0,0 +1,37 @@ +

744. Find Smallest Letter Greater Than Target

Easy


You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.

+ +

Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.

+ +

 

+

Example 1:

+ +
Input: letters = ["c","f","j"], target = "a"
+Output: "c"
+Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
+
+ +

Example 2:

+ +
Input: letters = ["c","f","j"], target = "c"
+Output: "f"
+Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.
+
+ +

Example 3:

+ +
Input: letters = ["x","x","y","y"], target = "z"
+Output: "x"
+Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= letters.length <= 104
  • +
  • letters[i] is a lowercase English letter.
  • +
  • letters is sorted in non-decreasing order.
  • +
  • letters contains at least two different characters.
  • +
  • target is a lowercase English letter.
  • +
+
\ No newline at end of file diff --git a/0746-min-cost-climbing-stairs/0746-min-cost-climbing-stairs.cpp b/0746-min-cost-climbing-stairs/0746-min-cost-climbing-stairs.cpp new file mode 100644 index 00000000..f2dbaf0d --- /dev/null +++ b/0746-min-cost-climbing-stairs/0746-min-cost-climbing-stairs.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + + int helper(int idx, int n, vector& cost, vector& dp) + { + if(idx >= n) + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int oneStep = cost[idx] + helper(idx+1, n, cost, dp); + int twoStep = cost[idx] + helper(idx+2, n, cost, dp); + + return dp[idx] = min(oneStep, twoStep); + } + + int minCostClimbingStairs(vector& cost) { + + int n = cost.size(); + + vector dp(n+1, -1); + + return min(helper(0, n, cost, dp), helper(1, n, cost, dp)); + + } +}; \ No newline at end of file diff --git a/0746-min-cost-climbing-stairs/NOTES.md b/0746-min-cost-climbing-stairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0746-min-cost-climbing-stairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0746-min-cost-climbing-stairs/README.md b/0746-min-cost-climbing-stairs/README.md new file mode 100644 index 00000000..c810b720 --- /dev/null +++ b/0746-min-cost-climbing-stairs/README.md @@ -0,0 +1,38 @@ +

746. Min Cost Climbing Stairs

Easy


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

+ +

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

+ +

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

+ +

 

+

Example 1:

+ +
Input: cost = [10,15,20]
+Output: 15
+Explanation: You will start at index 1.
+- Pay 15 and climb two steps to reach the top.
+The total cost is 15.
+
+ +

Example 2:

+ +
Input: cost = [1,100,1,1,1,100,1,1,100,1]
+Output: 6
+Explanation: You will start at index 0.
+- Pay 1 and climb two steps to reach index 2.
+- Pay 1 and climb two steps to reach index 4.
+- Pay 1 and climb two steps to reach index 6.
+- Pay 1 and climb one step to reach index 7.
+- Pay 1 and climb two steps to reach index 9.
+- Pay 1 and climb one step to reach the top.
+The total cost is 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= cost.length <= 1000
  • +
  • 0 <= cost[i] <= 999
  • +
+
\ No newline at end of file diff --git a/0752-open-the-lock/0752-open-the-lock.cpp b/0752-open-the-lock/0752-open-the-lock.cpp new file mode 100644 index 00000000..b7539355 --- /dev/null +++ b/0752-open-the-lock/0752-open-the-lock.cpp @@ -0,0 +1,72 @@ +class Solution { +public: + + string forward(string curr, int idx) + { + if(curr[idx] == '9') + curr[idx] = '0'; + else + ++curr[idx]; + return curr; + } + + string backward(string curr, int idx) + { + if(curr[idx] == '0') + curr[idx] = '9'; + else + --curr[idx]; + return curr; + } + + int openLock(vector& deadends, string target) { + + set st(deadends.begin(), deadends.end()); + + set visited; + + queue q; + + if(!st.count("0000")) + { + q.push("0000"); + visited.insert("0000"); + } + + int steps = 0; + + while(!q.empty()) + { + int size = q.size(); + + for(int i = 0; i < size; ++i) + { + string curr = q.front(); + q.pop(); + + if(curr == target) + return steps; + + for(int i = 0; i < 4; ++i) + { + string f = forward(curr, i); + string s = backward(curr, i); + + if(!st.count(f) and !visited.count(f)) + { + q.push(f); + visited.insert(f); + } + if(!st.count(s) and !visited.count(s)) + { + q.push(s); + visited.insert(s); + } + } + } + ++steps; + } + + return -1; + } +}; \ No newline at end of file diff --git a/0752-open-the-lock/README.md b/0752-open-the-lock/README.md new file mode 100644 index 00000000..36cb276f --- /dev/null +++ b/0752-open-the-lock/README.md @@ -0,0 +1,44 @@ +

752. Open the Lock

Medium


You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

+ +

The lock initially starts at '0000', a string representing the state of the 4 wheels.

+ +

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

+ +

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

+ +

 

+

Example 1:

+ +
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
+Output: 6
+Explanation: 
+A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
+Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
+because the wheels of the lock become stuck after the display becomes the dead end "0102".
+
+ +

Example 2:

+ +
Input: deadends = ["8888"], target = "0009"
+Output: 1
+Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
+
+ +

Example 3:

+ +
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
+Output: -1
+Explanation: We cannot reach the target without getting stuck.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= deadends.length <= 500
  • +
  • deadends[i].length == 4
  • +
  • target.length == 4
  • +
  • target will not be in the list deadends.
  • +
  • target and deadends[i] consist of digits only.
  • +
+
\ No newline at end of file diff --git a/0767-reorganize-string/0767-reorganize-string.cpp b/0767-reorganize-string/0767-reorganize-string.cpp new file mode 100644 index 00000000..1eeac192 --- /dev/null +++ b/0767-reorganize-string/0767-reorganize-string.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + string reorganizeString(string s) { + + int n = s.size(); + + vector freq(26, 0); + + int maxFreq = 0; + + char maxFreqCharacter; + + for(auto& ch : s) + { + ++freq[ch - 'a']; + + if(freq[ch-'a'] > (n+1)/2) + return ""; + + if(freq[ch-'a'] > maxFreq) + { + maxFreq = freq[ch-'a']; + maxFreqCharacter = ch; + } + } + + int i = 0; + + string ans(n,' '); + + while(freq[maxFreqCharacter - 'a'] > 0) + { + ans[i] = maxFreqCharacter; + + --freq[maxFreqCharacter - 'a']; + + i += 2; + } + + for(char ch = 'a'; ch <= 'z'; ++ch) + { + while(freq[ch - 'a'] > 0) + { + if(i >= n) + i = 1; + + ans[i] = ch; + + --freq[ch - 'a']; + i += 2; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0767-reorganize-string/NOTES.md b/0767-reorganize-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0767-reorganize-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0767-reorganize-string/README.md b/0767-reorganize-string/README.md new file mode 100644 index 00000000..5ae1df96 --- /dev/null +++ b/0767-reorganize-string/README.md @@ -0,0 +1,20 @@ +

767. Reorganize String

Medium


Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

+ +

Return any possible rearrangement of s or return "" if not possible.

+ +

 

+

Example 1:

+
Input: s = "aab"
+Output: "aba"
+

Example 2:

+
Input: s = "aaab"
+Output: ""
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 500
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0783-minimum-distance-between-bst-nodes/0783-minimum-distance-between-bst-nodes.cpp b/0783-minimum-distance-between-bst-nodes/0783-minimum-distance-between-bst-nodes.cpp new file mode 100644 index 00000000..aad64551 --- /dev/null +++ b/0783-minimum-distance-between-bst-nodes/0783-minimum-distance-between-bst-nodes.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, int& diff, int& pre) + { + if(root) + { + helper(root->left,diff,pre); + if(pre != -1) + { + diff = min(diff, abs(root->val - pre)); + } + + pre = root->val; + + helper(root->right,diff,pre); + } + } + + int minDiffInBST(TreeNode* root) { + + int diff = INT_MAX, pre = -1; + helper(root,diff,pre); + return diff; + + } +}; + diff --git a/0783-minimum-distance-between-bst-nodes/NOTES.md b/0783-minimum-distance-between-bst-nodes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0783-minimum-distance-between-bst-nodes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0783-minimum-distance-between-bst-nodes/README.md b/0783-minimum-distance-between-bst-nodes/README.md new file mode 100644 index 00000000..ad1e472e --- /dev/null +++ b/0783-minimum-distance-between-bst-nodes/README.md @@ -0,0 +1,26 @@ +

783. Minimum Distance Between BST Nodes

Easy


Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

+ +

 

+

Example 1:

+ +
Input: root = [4,2,6,1,3]
+Output: 1
+
+ +

Example 2:

+ +
Input: root = [1,0,48,null,null,12,49]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 100].
  • +
  • 0 <= Node.val <= 105
  • +
+ +

 

+

Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/

+
\ No newline at end of file diff --git a/0785-is-graph-bipartite/0785-is-graph-bipartite.cpp b/0785-is-graph-bipartite/0785-is-graph-bipartite.cpp new file mode 100644 index 00000000..4c41acad --- /dev/null +++ b/0785-is-graph-bipartite/0785-is-graph-bipartite.cpp @@ -0,0 +1,40 @@ +class Solution { +private: + bool check(int sv, int col, vector>& graph, vector& color, vector& visited) + { + color[sv] = col; + visited[sv] = true; + + for(auto itr : graph[sv]) + { + if(!visited[itr]) + { + if(!check(itr, col ^ 1, graph, color, visited)) + return false; + } + else if(color[sv] == color[itr]) + return false; + } + + return true; + } + +public: + bool isBipartite(vector>& graph) { + + int n = graph.size(); + + vector visited(n+1, false); + + vector color(n+1,-1); + + for(int i = 0; i < n; ++i) + { + if(!visited[i] and !check(i, 0, graph,color, visited)) + return false; + } + + return true; + + } +}; \ No newline at end of file diff --git a/0785-is-graph-bipartite/NOTES.md b/0785-is-graph-bipartite/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0785-is-graph-bipartite/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0786-k-th-smallest-prime-fraction/0786-k-th-smallest-prime-fraction.cpp b/0786-k-th-smallest-prime-fraction/0786-k-th-smallest-prime-fraction.cpp new file mode 100644 index 00000000..7c02db31 --- /dev/null +++ b/0786-k-th-smallest-prime-fraction/0786-k-th-smallest-prime-fraction.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector kthSmallestPrimeFraction(vector& arr, int k) { + + vector>> res; + + int n = arr.size(); + + for(int i = 0; i < n; ++i) + { + for(int j = n-1; j >= 0; --j) + { + if(i != j) + { + res.push_back({((double)arr[i]/(double)arr[j]),{arr[i], arr[j]}}); + } + } + } + + sort(res.begin(), res.end()); + + return {res[k-1].second.first, res[k-1].second.second}; + } +}; \ No newline at end of file diff --git a/0786-k-th-smallest-prime-fraction/NOTES.md b/0786-k-th-smallest-prime-fraction/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0786-k-th-smallest-prime-fraction/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0787-cheapest-flights-within-k-stops/0787-cheapest-flights-within-k-stops.cpp b/0787-cheapest-flights-within-k-stops/0787-cheapest-flights-within-k-stops.cpp new file mode 100644 index 00000000..2a806abc --- /dev/null +++ b/0787-cheapest-flights-within-k-stops/0787-cheapest-flights-within-k-stops.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + + vector> adj[n]; + + for(auto itr : flights){ + adj[itr[0]].push_back({itr[1],itr[2]}); + } + + vector dist(n,1e9); + + queue> > q; + + q.push({0,{src,0}}); + dist[src] = 0; + + // stops node cost + + while(!q.empty()){ + + auto curr = q.front(); + q.pop(); + + int stops = curr.first; + int node = curr.second.first; + int cost = curr.second.second; + + for(auto itr : adj[node]) + { + // itr is pair of adjNode and cost + if(stops > k) + continue; + + if(stops <= k and cost + itr.second <= dist[itr.first]) + { + dist[itr.first] = cost + itr.second; + q.push({stops+1,{itr.first,cost + itr.second}}); + } + } + } + + + if(dist[dst] == 1e9) + return -1; + + return dist[dst]; + + } +}; \ No newline at end of file diff --git a/0787-cheapest-flights-within-k-stops/NOTES.md b/0787-cheapest-flights-within-k-stops/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0787-cheapest-flights-within-k-stops/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0787-cheapest-flights-within-k-stops/README.md b/0787-cheapest-flights-within-k-stops/README.md new file mode 100644 index 00000000..9bd2c685 --- /dev/null +++ b/0787-cheapest-flights-within-k-stops/README.md @@ -0,0 +1,48 @@ +

787. Cheapest Flights Within K Stops

Medium


There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.

+ +

You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

+ +

 

+

Example 1:

+ +
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
+Output: 700
+Explanation:
+The graph is shown above.
+The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
+Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
+
+ +

Example 2:

+ +
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
+Output: 200
+Explanation:
+The graph is shown above.
+The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
+
+ +

Example 3:

+ +
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
+Output: 500
+Explanation:
+The graph is shown above.
+The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 0 <= flights.length <= (n * (n - 1) / 2)
  • +
  • flights[i].length == 3
  • +
  • 0 <= fromi, toi < n
  • +
  • fromi != toi
  • +
  • 1 <= pricei <= 104
  • +
  • There will not be any multiple flights between two cities.
  • +
  • 0 <= src, dst, k < n
  • +
  • src != dst
  • +
+
\ No newline at end of file diff --git a/0790-domino-and-tromino-tiling/0790-domino-and-tromino-tiling.cpp b/0790-domino-and-tromino-tiling/0790-domino-and-tromino-tiling.cpp new file mode 100644 index 00000000..21a87ddb --- /dev/null +++ b/0790-domino-and-tromino-tiling/0790-domino-and-tromino-tiling.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + const int MOD = 1e9+7; + int dp[1001][2]{}; + int numTilings(int n) { + return solve(0, n, false); + } + long solve(int i, int n, bool previousGap) { + if(i > n) return 0; + if(i == n) return !previousGap; + if(dp[i][previousGap]) return dp[i][previousGap]; + if(previousGap) + return dp[i][previousGap] = (solve(i+1, n, false) + solve(i+1, n, true)) % MOD; + return dp[i][previousGap] = (solve(i+1, n, false) + solve(i+2, n, false) + 2*solve(i+2, n, true)) % MOD; + } +}; \ No newline at end of file diff --git a/0790-domino-and-tromino-tiling/README.md b/0790-domino-and-tromino-tiling/README.md new file mode 100644 index 00000000..0071e07e --- /dev/null +++ b/0790-domino-and-tromino-tiling/README.md @@ -0,0 +1,27 @@ +

790. Domino and Tromino Tiling

Medium


You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.

+ +

Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.

+ +

In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 5
+Explanation: The five different ways are show above.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/0791-custom-sort-string/0791-custom-sort-string.cpp b/0791-custom-sort-string/0791-custom-sort-string.cpp new file mode 100644 index 00000000..7124d4f8 --- /dev/null +++ b/0791-custom-sort-string/0791-custom-sort-string.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string customSortString(string order, string s) { + + map mp; + + for(int i = 0; i < order.size(); ++i) + { + if(mp.find(order[i]) == mp.end()) + mp[order[i]] = i; + } + + sort(s.begin(), s.end(),[&](const auto& a, const auto& b){ + return mp[a] < mp[b]; + }); + + return s; + + } +}; \ No newline at end of file diff --git a/0791-custom-sort-string/NOTES.md b/0791-custom-sort-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0791-custom-sort-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0791-custom-sort-string/README.md b/0791-custom-sort-string/README.md new file mode 100644 index 00000000..df4199fe --- /dev/null +++ b/0791-custom-sort-string/README.md @@ -0,0 +1,41 @@ +

791. Custom Sort String

Medium


You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

+ +

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

+ +

Return any permutation of s that satisfies this property.

+ +

 

+

Example 1:

+ +
+

Input: order = "cba", s = "abcd"

+ +

Output: "cbad"

+ +

Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".

+ +

Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

+
+ +

Example 2:

+ +
+

Input: order = "bcafg", s = "abcd"

+ +

Output: "bcad"

+ +

Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.

+ +

Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= order.length <= 26
  • +
  • 1 <= s.length <= 200
  • +
  • order and s consist of lowercase English letters.
  • +
  • All the characters of order are unique.
  • +
+
\ No newline at end of file diff --git a/0797-all-paths-from-source-to-target/0797-all-paths-from-source-to-target.cpp b/0797-all-paths-from-source-to-target/0797-all-paths-from-source-to-target.cpp new file mode 100644 index 00000000..fea94b39 --- /dev/null +++ b/0797-all-paths-from-source-to-target/0797-all-paths-from-source-to-target.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + + void dfs(int sv, vector>& graph, vector>&res, vector& ds) + { + ds.push_back(sv); + + if(sv == graph.size()-1) + res.push_back(ds); + + for(auto itr : graph[sv]) + { + dfs(itr,graph,res,ds); + } + ds.pop_back(); + } + + vector> allPathsSourceTarget(vector>& graph) { + + int n = graph.size(); + vector ds; + vector> res; + + dfs(0,graph,res,ds); + + return res; + } +}; \ No newline at end of file diff --git a/0797-all-paths-from-source-to-target/README.md b/0797-all-paths-from-source-to-target/README.md new file mode 100644 index 00000000..1adf12c2 --- /dev/null +++ b/0797-all-paths-from-source-to-target/README.md @@ -0,0 +1,30 @@ +

797. All Paths From Source to Target

Medium


Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

+ +

The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2],[3],[3],[]]
+Output: [[0,1,3],[0,2,3]]
+Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
+
+ +

Example 2:

+ +
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
+Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 2 <= n <= 15
  • +
  • 0 <= graph[i][j] < n
  • +
  • graph[i][j] != i (i.e., there will be no self-loops).
  • +
  • All the elements of graph[i] are unique.
  • +
  • The input graph is guaranteed to be a DAG.
  • +
+
\ No newline at end of file diff --git a/0802-find-eventual-safe-states/0802-find-eventual-safe-states.cpp b/0802-find-eventual-safe-states/0802-find-eventual-safe-states.cpp new file mode 100644 index 00000000..01856737 --- /dev/null +++ b/0802-find-eventual-safe-states/0802-find-eventual-safe-states.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + vector eventualSafeNodes(vector>& graph) { + + int n = graph.size(); + + vector adj[n+1]; + + for(int i = 0; i < n; ++i) + { + for(auto itr : graph[i]) + adj[itr].push_back(i); + + } + + + vector indegree(n, 0); + + for(int i = 0; i < n; ++i) + { + for(auto itr : adj[i]) + ++indegree[itr]; + } + + queue q; + + for(int i = 0; i < n; ++i) + { + if(indegree[i] == 0) + q.push(i); + } + + vector safe; + + while(!q.empty()) + { + int curr = q.front(); + q.pop(); + + safe.push_back(curr); + + for(auto itr : adj[curr]) + { + --indegree[itr]; + + if(indegree[itr] == 0) + q.push(itr); + } + } + + sort(safe.begin(),safe.end()); + + return safe; + + } +}; \ No newline at end of file diff --git a/0802-find-eventual-safe-states/NOTES.md b/0802-find-eventual-safe-states/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0802-find-eventual-safe-states/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0802-find-eventual-safe-states/README.md b/0802-find-eventual-safe-states/README.md new file mode 100644 index 00000000..45fa72c3 --- /dev/null +++ b/0802-find-eventual-safe-states/README.md @@ -0,0 +1,36 @@ +

802. Find Eventual Safe States

Medium


There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].

+ +

A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).

+ +

Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

+ +

 

+

Example 1:

+Illustration of graph +
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
+Output: [2,4,5,6]
+Explanation: The given graph is shown above.
+Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
+Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
+ +

Example 2:

+ +
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
+Output: [4]
+Explanation:
+Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 1 <= n <= 104
  • +
  • 0 <= graph[i].length <= n
  • +
  • 0 <= graph[i][j] <= n - 1
  • +
  • graph[i] is sorted in a strictly increasing order.
  • +
  • The graph may contain self-loops.
  • +
  • The number of edges in the graph will be in the range [1, 4 * 104].
  • +
+
\ No newline at end of file diff --git a/0808-soup-servings/README.md b/0808-soup-servings/README.md new file mode 100644 index 00000000..d4e862af --- /dev/null +++ b/0808-soup-servings/README.md @@ -0,0 +1,39 @@ +

808. Soup Servings

Medium


There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:

+ +
    +
  1. Serve 100 ml of soup A and 0 ml of soup B,
  2. +
  3. Serve 75 ml of soup A and 25 ml of soup B,
  4. +
  5. Serve 50 ml of soup A and 50 ml of soup B, and
  6. +
  7. Serve 25 ml of soup A and 75 ml of soup B.
  8. +
+ +

When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.

+ +

Note that we do not have an operation where all 100 ml's of soup B are used first.

+ +

Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.

+ +

 

+

Example 1:

+ +
Input: n = 50
+Output: 0.62500
+Explanation: If we choose the first two operations, A will become empty first.
+For the third operation, A and B will become empty at the same time.
+For the fourth operation, B will become empty first.
+So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
+
+ +

Example 2:

+ +
Input: n = 100
+Output: 0.71875
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 109
  • +
+
\ No newline at end of file diff --git a/0823-binary-trees-with-factors/0823-binary-trees-with-factors.cpp b/0823-binary-trees-with-factors/0823-binary-trees-with-factors.cpp new file mode 100644 index 00000000..d2d96ba0 --- /dev/null +++ b/0823-binary-trees-with-factors/0823-binary-trees-with-factors.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + + const int mod = 1e9+7; + + int numFactoredBinaryTrees(vector& arr) { + + int n = arr.size(); + + unordered_map mp; + + for(auto& itr : arr) + ++mp[itr]; + + sort(arr.begin(), arr.end()); + + int ans = 0; + + for(int i = 1; i < n; ++i) + { + for(int j = 0; j < i; ++j) + { + if(arr[i] % arr[j] == 0) + { + long long count = (mp[arr[j]] * 1LL * mp[arr[i]/arr[j]]) % mod; + mp[arr[i]] = (mp[arr[i]] % mod + count)% mod; + } + } + } + + for(auto& itr : mp) + { + ans = (ans + itr.second) % mod; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0823-binary-trees-with-factors/NOTES.md b/0823-binary-trees-with-factors/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0823-binary-trees-with-factors/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0823-binary-trees-with-factors/README.md b/0823-binary-trees-with-factors/README.md new file mode 100644 index 00000000..af1c0af6 --- /dev/null +++ b/0823-binary-trees-with-factors/README.md @@ -0,0 +1,28 @@ +

823. Binary Trees With Factors

Medium


Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.

+ +

We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.

+ +

Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: arr = [2,4]
+Output: 3
+Explanation: We can make these trees: [2], [4], [4, 2, 2]
+ +

Example 2:

+ +
Input: arr = [2,4,5,10]
+Output: 7
+Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • 2 <= arr[i] <= 109
  • +
  • All the values of arr are unique.
  • +
+
\ No newline at end of file diff --git a/0823. Binary Trees With Factors.cpp b/0823. Binary Trees With Factors.cpp new file mode 100644 index 00000000..80674a71 --- /dev/null +++ b/0823. Binary Trees With Factors.cpp @@ -0,0 +1,48 @@ +// 823.✅ Binary Trees With Factors + +class Solution +{ +public: + int numFactoredBinaryTrees(vector &arr) + { + + int n = arr.size(); + + long long int mod = 1e9 + 7; + + map mp; + + long long int sum = 0; + + sort(arr.begin(), arr.end()); + + for (int i = 0; i < n; ++i) + mp.insert({arr[i], 1}); + + for (int i = 0; i < n; ++i) + { + long long int count = 0; + + auto itr1 = mp.find(arr[i]); + + for (int j = 0; j < i; ++j) + { + if (arr[i] % arr[j] == 0) + { + if (mp[arr[i] / arr[j]]) + { + count += mp[arr[j]] % mod * mp[arr[i] / arr[j]] % mod; + } + } + } + mp[arr[i]] += count; + } + + for (auto itr : mp) + { + sum += itr.second; + } + + return sum % mod; + } +}; \ No newline at end of file diff --git a/0826-most-profit-assigning-work/0826-most-profit-assigning-work.cpp b/0826-most-profit-assigning-work/0826-most-profit-assigning-work.cpp new file mode 100644 index 00000000..700d6e14 --- /dev/null +++ b/0826-most-profit-assigning-work/0826-most-profit-assigning-work.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { + + int n = profit.size(); + vector> vp; + + for(int i = 0; i < n; ++i) + vp.push_back({difficulty[i],profit[i]}); + + sort(vp.begin(),vp.end()); + long long ans = 0; + + for(auto itr : worker) + { + int maxi = 0; + for(auto x : vp) + { + if(itr >= x.first) + maxi = max(maxi,x.second); + else + break; + } + ans += maxi; + } + + return (int)ans; + + } +}; \ No newline at end of file diff --git a/0826-most-profit-assigning-work/NOTES.md b/0826-most-profit-assigning-work/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0826-most-profit-assigning-work/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0826-most-profit-assigning-work/README.md b/0826-most-profit-assigning-work/README.md new file mode 100644 index 00000000..150af98d --- /dev/null +++ b/0826-most-profit-assigning-work/README.md @@ -0,0 +1,40 @@ +

826. Most Profit Assigning Work

Medium


You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:

+ +
    +
  • difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
  • +
  • worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
  • +
+ +

Every worker can be assigned at most one job, but one job can be completed multiple times.

+ +
    +
  • For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
  • +
+ +

Return the maximum profit we can achieve after assigning the workers to the jobs.

+ +

 

+

Example 1:

+ +
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
+Output: 100
+Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
+
+ +

Example 2:

+ +
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • n == difficulty.length
  • +
  • n == profit.length
  • +
  • m == worker.length
  • +
  • 1 <= n, m <= 104
  • +
  • 1 <= difficulty[i], profit[i], worker[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0827-making-a-large-island/0827-making-a-large-island.cpp b/0827-making-a-large-island/0827-making-a-large-island.cpp new file mode 100644 index 00000000..79b5e3d4 --- /dev/null +++ b/0827-making-a-large-island/0827-making-a-large-island.cpp @@ -0,0 +1,145 @@ +class Solution { +public: + + class DSU{ + public: + vector parent, size, rank; + public: + DSU(int n) + { + parent.resize(n+1); + size.resize(n+1, 1); + rank.resize(n+1, 0); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + return u; + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + parent[parU] = parV; + else if(rank[parV] > rank[parU]) + parent[parV] = parU; + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } + }; + + int largestIsland(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + DSU dsu((n*m) + 1); + + vector dx = {-1, 0, +1, 0}; + vector dy = {0, -1, 0, +1}; + + auto isValid = [&](int x, int y) + { + return (x >= 0 and y >= 0 and x < n and y < m); + }; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(grid[i][j] == 0) + continue; + + for(int k = 0; k < 4; ++k) + { + int newx = dx[k] + i; + int newy = dy[k] + j; + + if(isValid(newx, newy) and grid[newx][newy]) + { + int node = (i * m) + j; + int adjNode = (newx * m) + newy; + + if(!dsu.isSame(node, adjNode)) + dsu.unionBySize(node, adjNode); + } + } + } + } + + int maxi = -1; + + unordered_set visited; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(grid[i][j] == 0) + { + for(int k = 0; k < 4; ++k) + { + int newx = dx[k] + i; + int newy = dy[k] + j; + + if(isValid(newx, newy) and grid[newx][newy]) + { + visited.insert(dsu.findParent((newx*m) + newy)); + } + } + + int curr = 0; + + for(auto& ele : visited) + curr += dsu.size[ele]; + + visited.clear(); + + maxi = max(maxi, curr + 1); + } + } + } + + + return (maxi == -1 ? (n * m) : maxi); + } +}; \ No newline at end of file diff --git a/0827-making-a-large-island/NOTES.md b/0827-making-a-large-island/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0827-making-a-large-island/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0827-making-a-large-island/README.md b/0827-making-a-large-island/README.md new file mode 100644 index 00000000..930714d9 --- /dev/null +++ b/0827-making-a-large-island/README.md @@ -0,0 +1,36 @@ +

827. Making A Large Island

Hard


You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

+ +

Return the size of the largest island in grid after applying this operation.

+ +

An island is a 4-directionally connected group of 1s.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,0],[0,1]]
+Output: 3
+Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
+
+ +

Example 2:

+ +
Input: grid = [[1,1],[1,0]]
+Output: 4
+Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
+ +

Example 3:

+ +
Input: grid = [[1,1],[1,1]]
+Output: 4
+Explanation: Can't change any 0 to 1, only one island with area = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= n <= 500
  • +
  • grid[i][j] is either 0 or 1.
  • +
\ No newline at end of file diff --git a/0834-sum-of-distances-in-tree/0834-sum-of-distances-in-tree.cpp b/0834-sum-of-distances-in-tree/0834-sum-of-distances-in-tree.cpp new file mode 100644 index 00000000..022e61d1 --- /dev/null +++ b/0834-sum-of-distances-in-tree/0834-sum-of-distances-in-tree.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector> v; + vector counter, res; + + void dfs(int i, int p = -1) { + for(auto u : v[i]) { + if(u == p) continue; + dfs(u, i); + counter[i] += counter[u]; + res[i] += res[u] + counter[u]; + } + counter[i] += 1; + } + + void dfs2(int i, int n, int p = -1) { + for(auto u : v[i]) { + if(u == p) continue; + res[u] = res[i] - counter[u] + n - counter[u]; + dfs2(u, n, i); + } + } + + vector sumOfDistancesInTree(int n, vector>& edges) { + v.resize(n); + for(int i = 0; i < n - 1; i++) { + int a = edges[i][0]; + int b = edges[i][1]; + v[a].push_back(b); + v[b].push_back(a); + } + res.resize(n); + counter.resize(n); + dfs(0); + dfs2(0, n); + return res; + } +}; \ No newline at end of file diff --git a/0834-sum-of-distances-in-tree/NOTES.md b/0834-sum-of-distances-in-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0834-sum-of-distances-in-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0834-sum-of-distances-in-tree/README.md b/0834-sum-of-distances-in-tree/README.md new file mode 100644 index 00000000..1393c3ed --- /dev/null +++ b/0834-sum-of-distances-in-tree/README.md @@ -0,0 +1,41 @@ +

834. Sum of Distances in Tree

Hard


There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

+ +

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

+ +

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

+ +

 

+

Example 1:

+ +
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
+Output: [8,12,6,10,10,10]
+Explanation: The tree is shown above.
+We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
+equals 1 + 1 + 2 + 2 + 2 = 8.
+Hence, answer[0] = 8, and so on.
+
+ +

Example 2:

+ +
Input: n = 1, edges = []
+Output: [0]
+
+ +

Example 3:

+ +
Input: n = 2, edges = [[1,0]]
+Output: [1,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 3 * 104
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • The given input represents a valid tree.
  • +
+
\ No newline at end of file diff --git a/0837-new-21-game/README.md b/0837-new-21-game/README.md new file mode 100644 index 00000000..eae53092 --- /dev/null +++ b/0837-new-21-game/README.md @@ -0,0 +1,40 @@ +

837. New 21 Game

Medium


Alice plays the following game, loosely based on the card game "21".

+ +

Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.

+ +

Alice stops drawing numbers when she gets k or more points.

+ +

Return the probability that Alice has n or fewer points.

+ +

Answers within 10-5 of the actual answer are considered accepted.

+ +

 

+

Example 1:

+ +
Input: n = 10, k = 1, maxPts = 10
+Output: 1.00000
+Explanation: Alice gets a single card, then stops.
+
+ +

Example 2:

+ +
Input: n = 6, k = 1, maxPts = 10
+Output: 0.60000
+Explanation: Alice gets a single card, then stops.
+In 6 out of 10 possibilities, she is at or below 6 points.
+
+ +

Example 3:

+ +
Input: n = 21, k = 17, maxPts = 10
+Output: 0.73278
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= k <= n <= 104
  • +
  • 1 <= maxPts <= 104
  • +
+
\ No newline at end of file diff --git a/0839-similar-string-groups/0839-similar-string-groups.cpp b/0839-similar-string-groups/0839-similar-string-groups.cpp new file mode 100644 index 00000000..4c225422 --- /dev/null +++ b/0839-similar-string-groups/0839-similar-string-groups.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + + int numSimilarGroups(vector& strs) { + + int n = strs.size(); + + vector visited(n,0); + + int cnt = 0; + + auto isSimilar = [&](string& a, string& b) + { + int n = a.size(), m = b.size(); + int c = 0; + if(n != m) + return false; + + for(int i = 0; i dfs = [&](int sv) { + visited[sv] = true; + + for(int i = 0; i isSimilar = [&](string a, string b) +{ +}; +​ \ No newline at end of file diff --git a/0839-similar-string-groups/README.md b/0839-similar-string-groups/README.md new file mode 100644 index 00000000..1406f862 --- /dev/null +++ b/0839-similar-string-groups/README.md @@ -0,0 +1,31 @@ +

839. Similar String Groups

Hard


Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.

+ +

For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".

+ +

Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}.  Notice that "tars" and "arts" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

+ +

We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

+ +

 

+

Example 1:

+ +
Input: strs = ["tars","rats","arts","star"]
+Output: 2
+
+ +

Example 2:

+ +
Input: strs = ["omv","ovm"]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 300
  • +
  • 1 <= strs[i].length <= 300
  • +
  • strs[i] consists of lowercase letters only.
  • +
  • All words in strs have the same length and are anagrams of each other.
  • +
+
\ No newline at end of file diff --git a/0840-magic-squares-in-grid/0840-magic-squares-in-grid.cpp b/0840-magic-squares-in-grid/0840-magic-squares-in-grid.cpp new file mode 100644 index 00000000..3cfd5c6a --- /dev/null +++ b/0840-magic-squares-in-grid/0840-magic-squares-in-grid.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + + int checkMatrix(vector>& mat) + { + + int diagSumA = 0, diagSumB = 0, end = 2; + map mp; + vector freq(10, 0); + + for(int i = 0; i < mat.size(); ++i) + { + int sum = 0; + for(int j = 0; j < mat[0].size(); ++j) + { + if(mat[i][j] >= 0 and mat[i][j] <= 9) + ++freq[mat[i][j]]; + sum += mat[i][j]; + if(i == j) + diagSumA += mat[i][j]; + if(j == end) + { + diagSumB += mat[i][j]; + --end; + } + } + ++mp[sum]; + } + + for(int j = 0; j < mat[0].size(); ++j) + { + int sum = 0; + for(int i = 0; i < mat.size(); ++i) + sum += mat[i][j]; + ++mp[sum]; + } + + for(int i = 1; i <= 9; ++i) + { + if(freq[i] == 0) + return 0; + } + + ++mp[diagSumA]; + ++mp[diagSumB]; + + return mp.size() == 1; + } + + int numMagicSquaresInside(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + vector> mat; + + if(i + 3 > n or j + 3 > m) + break; + for(int k = i; k < i + 3; ++k) + { + vector row; + for(int l = j; l < j + 3; ++l) + row.push_back(grid[k][l]); + mat.push_back(row); + } + + if(checkMatrix(mat)) + ++ans; + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0840-magic-squares-in-grid/NOTES.md b/0840-magic-squares-in-grid/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0840-magic-squares-in-grid/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0840-magic-squares-in-grid/README.md b/0840-magic-squares-in-grid/README.md new file mode 100644 index 00000000..06ddc8d2 --- /dev/null +++ b/0840-magic-squares-in-grid/README.md @@ -0,0 +1,35 @@ +

840. Magic Squares In Grid

Medium


A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

+ +

Given a row x col grid of integers, how many 3 x 3 contiguous magic square subgrids are there?

+ +

Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.

+ +

 

+

Example 1:

+ +
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
+Output: 1
+Explanation: 
+The following subgrid is a 3 x 3 magic square:
+
+while this one is not:
+
+In total, there is only one magic square inside the given grid.
+
+ +

Example 2:

+ +
Input: grid = [[8]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • row == grid.length
  • +
  • col == grid[i].length
  • +
  • 1 <= row, col <= 10
  • +
  • 0 <= grid[i][j] <= 15
  • +
+
\ No newline at end of file diff --git a/0841-keys-and-rooms/0841-keys-and-rooms.cpp b/0841-keys-and-rooms/0841-keys-and-rooms.cpp new file mode 100644 index 00000000..cc195490 --- /dev/null +++ b/0841-keys-and-rooms/0841-keys-and-rooms.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool canVisitAllRooms(vector>& rooms) { + + int n = rooms.size(); + vector visited(n,false); + + queue q; + q.push(0); + + while(!q.empty()) + { + int curr = q.front(); + visited[curr] = true; + q.pop(); + for(auto itr : rooms[curr]) + { + if(!visited[itr]) + q.push(itr); + } + } + + for(int i = 0; i841. Keys and Rooms

Medium


There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

+ +

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

+ +

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: rooms = [[1],[2],[3],[]]
+Output: true
+Explanation: 
+We visit room 0 and pick up key 1.
+We then visit room 1 and pick up key 2.
+We then visit room 2 and pick up key 3.
+We then visit room 3.
+Since we were able to visit every room, we return true.
+
+ +

Example 2:

+ +
Input: rooms = [[1,3],[3,0,1],[2],[0]]
+Output: false
+Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
+
+ +

 

+

Constraints:

+ +
    +
  • n == rooms.length
  • +
  • 2 <= n <= 1000
  • +
  • 0 <= rooms[i].length <= 1000
  • +
  • 1 <= sum(rooms[i].length) <= 3000
  • +
  • 0 <= rooms[i][j] < n
  • +
  • All the values of rooms[i] are unique.
  • +
+
\ No newline at end of file diff --git a/0844-backspace-string-compare/0844-backspace-string-compare.cpp b/0844-backspace-string-compare/0844-backspace-string-compare.cpp new file mode 100644 index 00000000..0e7ac67b --- /dev/null +++ b/0844-backspace-string-compare/0844-backspace-string-compare.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + bool backspaceCompare(string s, string t) { + + string one, two; + + for(auto& itr : s) + { + if(itr == '#') + { + if(!one.empty()) + one.pop_back(); + } + else + one.push_back(itr); + } + + for(auto& itr : t) + { + if(itr == '#') + { + if(!two.empty()) + two.pop_back(); + } + else + two.push_back(itr); + } + + return one == two; + + } +}; \ No newline at end of file diff --git a/0844-backspace-string-compare/NOTES.md b/0844-backspace-string-compare/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0844-backspace-string-compare/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0846-hand-of-straights/0846-hand-of-straights.cpp b/0846-hand-of-straights/0846-hand-of-straights.cpp new file mode 100644 index 00000000..a0c9450b --- /dev/null +++ b/0846-hand-of-straights/0846-hand-of-straights.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + + int n = hand.size(); + + if(n % groupSize != 0) + return false; + + int step = n / groupSize; + + map mp; + + for(auto& ele : hand) + ++mp[ele]; + + while(step--) + { + int k = 0, prev = -1; + + if(mp.size() < groupSize) + return false; + + for(auto& ele : mp) + { + ++k; + + if(prev == -1) + prev = ele.first; + else + { + if(prev + 1 != ele.first) + return false; + } + + prev = ele.first; + + --ele.second; + + if(ele.second == 0) + mp.erase(ele.first); // remove + + if(k == groupSize) + break; + } + } + + return true; + + } +}; \ No newline at end of file diff --git a/0846-hand-of-straights/NOTES.md b/0846-hand-of-straights/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0846-hand-of-straights/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0846-hand-of-straights/README.md b/0846-hand-of-straights/README.md new file mode 100644 index 00000000..fe6ec095 --- /dev/null +++ b/0846-hand-of-straights/README.md @@ -0,0 +1,32 @@ +

846. Hand of Straights

Medium


Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

+ +

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
+Output: true
+Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
+
+ +

Example 2:

+ +
Input: hand = [1,2,3,4,5], groupSize = 4
+Output: false
+Explanation: Alice's hand can not be rearranged into groups of 4.
+
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= hand.length <= 104
  • +
  • 0 <= hand[i] <= 109
  • +
  • 1 <= groupSize <= hand.length
  • +
+ +

 

+

Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/

+
\ No newline at end of file diff --git a/0847-shortest-path-visiting-all-nodes/0847-shortest-path-visiting-all-nodes.cpp b/0847-shortest-path-visiting-all-nodes/0847-shortest-path-visiting-all-nodes.cpp new file mode 100644 index 00000000..a9571d67 --- /dev/null +++ b/0847-shortest-path-visiting-all-nodes/0847-shortest-path-visiting-all-nodes.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + int shortestPathLength(vector>& graph) { + + int n = graph.size(); + + if(n == 1) + return 0; + + queue > q; + + set > visited; + + int allVisited = (1 << n) - 1; + + for(int i = 0; i < n; ++i) + { + int mask = 1 << i; + + q.push({i, mask}); + + visited.insert({i, mask}); + } + + int path = 0; + + while(!q.empty()) + { + int size = q.size(); + + ++path; + + while(size--) + { + auto curr = q.front(); + q.pop(); + + int node = curr.first; + int mask = curr.second; + + for(auto& adjNode : graph[node]) + { + int newMask = mask | (1 << adjNode); + + if(newMask == allVisited) + return path; + + if(!visited.count({adjNode, newMask})) + { + q.push({adjNode, newMask}); + visited.insert({adjNode, newMask}); + } + } + } + } + + return -1; + + } +}; \ No newline at end of file diff --git a/0847-shortest-path-visiting-all-nodes/README.md b/0847-shortest-path-visiting-all-nodes/README.md new file mode 100644 index 00000000..16ac110c --- /dev/null +++ b/0847-shortest-path-visiting-all-nodes/README.md @@ -0,0 +1,31 @@ +

847. Shortest Path Visiting All Nodes

Hard


You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.

+ +

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2,3],[0],[0],[0]]
+Output: 4
+Explanation: One possible path is [1,0,2,0,3]
+
+ +

Example 2:

+ +
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
+Output: 4
+Explanation: One possible path is [0,1,4,2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 1 <= n <= 12
  • +
  • 0 <= graph[i].length < n
  • +
  • graph[i] does not contain i.
  • +
  • If graph[a] contains b, then graph[b] contains a.
  • +
  • The input graph is always connected.
  • +
+
\ No newline at end of file diff --git a/0852-peak-index-in-a-mountain-array/0852-peak-index-in-a-mountain-array.cpp b/0852-peak-index-in-a-mountain-array/0852-peak-index-in-a-mountain-array.cpp new file mode 100644 index 00000000..369ec8de --- /dev/null +++ b/0852-peak-index-in-a-mountain-array/0852-peak-index-in-a-mountain-array.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int peakIndexInMountainArray(vector& arr) { + + int n = arr.size(); + + int start = 0, end = n-1; + + while(start <= end) + { + int mid = (start + end) >> 1; + + if(arr[mid] < arr[mid+1]) + start = mid+1; + else + end = mid-1; + } + + return start; + + } +}; \ No newline at end of file diff --git a/0852-peak-index-in-a-mountain-array/NOTES.md b/0852-peak-index-in-a-mountain-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0852-peak-index-in-a-mountain-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0852-peak-index-in-a-mountain-array/README.md b/0852-peak-index-in-a-mountain-array/README.md new file mode 100644 index 00000000..e6e7ee11 --- /dev/null +++ b/0852-peak-index-in-a-mountain-array/README.md @@ -0,0 +1,44 @@ +

852. Peak Index in a Mountain Array

Medium


An array arr a mountain if the following properties hold:

+ +
    +
  • arr.length >= 3
  • +
  • There exists some i with 0 < i < arr.length - 1 such that: +
      +
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • +
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • +
    +
  • +
+ +

Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

+ +

You must solve it in O(log(arr.length)) time complexity.

+ +

 

+

Example 1:

+ +
Input: arr = [0,1,0]
+Output: 1
+
+ +

Example 2:

+ +
Input: arr = [0,2,1,0]
+Output: 1
+
+ +

Example 3:

+ +
Input: arr = [0,10,5,2]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= arr.length <= 105
  • +
  • 0 <= arr[i] <= 106
  • +
  • arr is guaranteed to be a mountain array.
  • +
+
\ No newline at end of file diff --git a/0857-minimum-cost-to-hire-k-workers/0857-minimum-cost-to-hire-k-workers.cpp b/0857-minimum-cost-to-hire-k-workers/0857-minimum-cost-to-hire-k-workers.cpp new file mode 100644 index 00000000..38566929 --- /dev/null +++ b/0857-minimum-cost-to-hire-k-workers/0857-minimum-cost-to-hire-k-workers.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + double mincostToHireWorkers(vector& quality, vector& wage, int k) { + vector> v; + int n=quality.size(); + for(int i=0;i pq; + + double ans=DBL_MAX; + int q=0; + for(int i=0;iv[i].second){ + q -= pq.top(); + pq.pop(); + + pq.push(v[i].second); + q += v[i].second; + } + } + if(pq.size()==k){ + double cost = q*v[i].first; + if(ans > cost) ans=cost; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/0857-minimum-cost-to-hire-k-workers/NOTES.md b/0857-minimum-cost-to-hire-k-workers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0857-minimum-cost-to-hire-k-workers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0857-minimum-cost-to-hire-k-workers/README.md b/0857-minimum-cost-to-hire-k-workers/README.md new file mode 100644 index 00000000..d251e14b --- /dev/null +++ b/0857-minimum-cost-to-hire-k-workers/README.md @@ -0,0 +1,35 @@ +

857. Minimum Cost to Hire K Workers

Hard


There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.

+ +

We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:

+ +
    +
  1. Every worker in the paid group must be paid at least their minimum wage expectation.
  2. +
  3. In the group, each worker's pay must be directly proportional to their quality. This means if a worker’s quality is double that of another worker in the group, then they must be paid twice as much as the other worker.
  4. +
+ +

Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.

+ +

 

+

Example 1:

+ +
Input: quality = [10,20,5], wage = [70,50,30], k = 2
+Output: 105.00000
+Explanation: We pay 70 to 0th worker and 35 to 2nd worker.
+
+ +

Example 2:

+ +
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3
+Output: 30.66667
+Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.
+
+ +

 

+

Constraints:

+ +
    +
  • n == quality.length == wage.length
  • +
  • 1 <= k <= n <= 104
  • +
  • 1 <= quality[i], wage[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0858. Mirror Reflection.cpp b/0858. Mirror Reflection.cpp new file mode 100644 index 00000000..3bcadbf0 --- /dev/null +++ b/0858. Mirror Reflection.cpp @@ -0,0 +1,15 @@ +// 858.✅ Mirror Reflection + +class Solution +{ +public: + int mirrorReflection(int p, int q) + { + while (p % 2 == 0 && q % 2 == 0) + { + p /= 2; + q /= 2; + } + return 1 - p % 2 + q % 2; + } +}; \ No newline at end of file diff --git a/0859-buddy-strings/0859-buddy-strings.cpp b/0859-buddy-strings/0859-buddy-strings.cpp new file mode 100644 index 00000000..c42ee33a --- /dev/null +++ b/0859-buddy-strings/0859-buddy-strings.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + bool buddyStrings(string s, string goal) { + + int n = s.size(), m = goal.size(); + + if(n != m) + return false; + + int cnt = 0, have = 0; + + unordered_map mp, mp2; + + for(int i = 0; i < n; ++i) + { + if(s[i] != goal[i]) + ++cnt; + + ++mp[s[i]]; + + ++mp2[goal[i]]; + + have = max(have, mp[s[i]]); + } + + for(auto itr : mp) + { + if(mp[itr.first] != mp2[itr.first]) + return false; + } + + return cnt == 2 or (cnt == 0 and have > 1); + + } +}; \ No newline at end of file diff --git a/0859-buddy-strings/NOTES.md b/0859-buddy-strings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0859-buddy-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0859-buddy-strings/README.md b/0859-buddy-strings/README.md new file mode 100644 index 00000000..09c932fb --- /dev/null +++ b/0859-buddy-strings/README.md @@ -0,0 +1,38 @@ +

859. Buddy Strings

Easy


Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

+ +

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

+ +
    +
  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
  • +
+ +

 

+

Example 1:

+ +
Input: s = "ab", goal = "ba"
+Output: true
+Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
+
+ +

Example 2:

+ +
Input: s = "ab", goal = "ab"
+Output: false
+Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
+
+ +

Example 3:

+ +
Input: s = "aa", goal = "aa"
+Output: true
+Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, goal.length <= 2 * 104
  • +
  • s and goal consist of lowercase letters.
  • +
+
\ No newline at end of file diff --git a/0860-lemonade-change/0860-lemonade-change.cpp b/0860-lemonade-change/0860-lemonade-change.cpp new file mode 100644 index 00000000..630ace19 --- /dev/null +++ b/0860-lemonade-change/0860-lemonade-change.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + bool lemonadeChange(vector& bills) { + + map mp; + + for(auto& ele : bills) + { + int rem = ele - 5; + + if(rem) + { + while(mp[10] and rem >= 10) + { + --mp[10]; + rem -= 10; + } + + while(mp[5] and rem) + { + --mp[5]; + rem -= 5; + } + } + + if(rem > 0) + return false; + + ++mp[ele]; + } + + return true; + + } +}; \ No newline at end of file diff --git a/0860-lemonade-change/NOTES.md b/0860-lemonade-change/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0860-lemonade-change/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0860-lemonade-change/README.md b/0860-lemonade-change/README.md new file mode 100644 index 00000000..d3a40735 --- /dev/null +++ b/0860-lemonade-change/README.md @@ -0,0 +1,37 @@ +

860. Lemonade Change

Easy


At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.

+ +

Note that you do not have any change in hand at first.

+ +

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: bills = [5,5,5,10,20]
+Output: true
+Explanation: 
+From the first 3 customers, we collect three $5 bills in order.
+From the fourth customer, we collect a $10 bill and give back a $5.
+From the fifth customer, we give a $10 bill and a $5 bill.
+Since all customers got correct change, we output true.
+
+ +

Example 2:

+ +
Input: bills = [5,5,10,10,20]
+Output: false
+Explanation: 
+From the first two customers in order, we collect two $5 bills.
+For the next two customers in order, we collect a $10 bill and give back a $5 bill.
+For the last customer, we can not give the change of $15 back because we only have two $10 bills.
+Since not every customer received the correct change, the answer is false.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bills.length <= 105
  • +
  • bills[i] is either 5, 10, or 20.
  • +
+
\ No newline at end of file diff --git a/0863-all-nodes-distance-k-in-binary-tree/0863-all-nodes-distance-k-in-binary-tree.cpp b/0863-all-nodes-distance-k-in-binary-tree/0863-all-nodes-distance-k-in-binary-tree.cpp new file mode 100644 index 00000000..41ad77e8 --- /dev/null +++ b/0863-all-nodes-distance-k-in-binary-tree/0863-all-nodes-distance-k-in-binary-tree.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + void dfs(TreeNode* root, unordered_map& m) { + if(!root) return; + if(root->left) { + m.insert({root->left, root}); + } + if(root->right) { + m.insert({root->right, root}); + } + dfs(root->left, m); + dfs(root->right, m); + } +public: + vector distanceK(TreeNode* root, TreeNode* target, int k) { + unordered_map m; //{current, parent} + queue q; + dfs(root, m); + q.push(target); + vector res; + unordered_map visited; + while(!q.empty()) { + int len = q.size(); + while(len--) { + TreeNode* curr = q.front(); q.pop(); + if(!k) res.push_back(curr->val); + visited[curr] = true; + if(curr->left && !visited[curr->left]) { + q.push(curr->left); + } + if(curr->right && !visited[curr->right]) { + q.push(curr->right); + } + if(m.find(curr) != m.end() && visited[m[curr]] == false) { + q.push(m[curr]); + } + } + k--; + if(k < 0) break; + } + return res; + } +}; \ No newline at end of file diff --git a/0863-all-nodes-distance-k-in-binary-tree/NOTES.md b/0863-all-nodes-distance-k-in-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0863-all-nodes-distance-k-in-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0864-shortest-path-to-get-all-keys/0864-shortest-path-to-get-all-keys.cpp b/0864-shortest-path-to-get-all-keys/0864-shortest-path-to-get-all-keys.cpp new file mode 100644 index 00000000..c482cecd --- /dev/null +++ b/0864-shortest-path-to-get-all-keys/0864-shortest-path-to-get-all-keys.cpp @@ -0,0 +1,70 @@ +class Solution { +public: + int shortestPathAllKeys(vector& grid) { + + int m=grid.size(), n=m?grid[0].size():0; + + if(!m || !n) return 0; + + int path=0, K=0; + + + vector dirs={0,-1,0,1,0}; + + vector>> visited(m,vector>(n,vector(64,0))); + + queue> q; + + for(int i=0;i='A' && grid[i][j]<='F') K++; //total alpha number + } + } + while(!q.empty()) + { + int size=q.size(); + + for(int i=0;i=m || y<0 || y>=n || grid[x][y]=='#') continue; + + if(grid[x][y]>='a' && grid[x][y]<='f'){ + + k=carry|(1<<(grid[x][y]-'a')); + } + else if(grid[x][y]>='A' && grid[x][y]<='F'){ + + if(!(carry & (1<<(grid[x][y]-'A')))) continue; + } + if(!visited[x][y][k]){ + visited[x][y][k]=1; + q.push({x*n+y,k}); + } + } + } + path++; + } + return -1; +} +}; \ No newline at end of file diff --git a/0864-shortest-path-to-get-all-keys/README.md b/0864-shortest-path-to-get-all-keys/README.md new file mode 100644 index 00000000..e49301b3 --- /dev/null +++ b/0864-shortest-path-to-get-all-keys/README.md @@ -0,0 +1,51 @@ +

864. Shortest Path to Get All Keys

Hard


You are given an m x n grid grid where:

+ +
    +
  • '.' is an empty cell.
  • +
  • '#' is a wall.
  • +
  • '@' is the starting point.
  • +
  • Lowercase letters represent keys.
  • +
  • Uppercase letters represent locks.
  • +
+ +

You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.

+ +

If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.

+ +

For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

+ +

Return the lowest number of moves to acquire all keys. If it is impossible, return -1.

+ +

 

+

Example 1:

+ +
Input: grid = ["@.a..","###.#","b.A.B"]
+Output: 8
+Explanation: Note that the goal is to obtain all the keys not to open all the locks.
+
+ +

Example 2:

+ +
Input: grid = ["@..aA","..B#.","....b"]
+Output: 6
+
+ +

Example 3:

+ +
Input: grid = ["@Aa"]
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 30
  • +
  • grid[i][j] is either an English letter, '.', '#', or '@'.
  • +
  • The number of keys in the grid is in the range [1, 6].
  • +
  • Each key in the grid is unique.
  • +
  • Each key in the grid has a matching lock.
  • +
+
\ No newline at end of file diff --git a/0867-transpose-matrix/0867-transpose-matrix.cpp b/0867-transpose-matrix/0867-transpose-matrix.cpp new file mode 100644 index 00000000..b24a5239 --- /dev/null +++ b/0867-transpose-matrix/0867-transpose-matrix.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector> transpose(vector>& matrix) { + + vector> ans; + + int n = matrix[0].size(), m = matrix.size(); + + for(int i = 0; i < n; ++i) + { + vector curr; + for(int j = 0; j < m; ++j) + { + curr.push_back(matrix[j][i]); + } + ans.push_back(curr); + } + return ans; + } +}; \ No newline at end of file diff --git a/0867-transpose-matrix/NOTES.md b/0867-transpose-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0867-transpose-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0867-transpose-matrix/README.md b/0867-transpose-matrix/README.md new file mode 100644 index 00000000..8eaf9eef --- /dev/null +++ b/0867-transpose-matrix/README.md @@ -0,0 +1,30 @@ +

867. Transpose Matrix

Easy


Given a 2D integer array matrix, return the transpose of matrix.

+ +

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

+ +

+ +

 

+

Example 1:

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

Example 2:

+ +
Input: matrix = [[1,2,3],[4,5,6]]
+Output: [[1,4],[2,5],[3,6]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 1000
  • +
  • 1 <= m * n <= 105
  • +
  • -109 <= matrix[i][j] <= 109
  • +
+
\ No newline at end of file diff --git a/0872-leaf-similar-trees/README.md b/0872-leaf-similar-trees/README.md new file mode 100644 index 00000000..71da5fe7 --- /dev/null +++ b/0872-leaf-similar-trees/README.md @@ -0,0 +1,31 @@ +

872. Leaf-Similar Trees

Easy


Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

+ +

+ +

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

+ +

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

+ +

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

+ +

 

+

Example 1:

+ +
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
+Output: true
+
+ +

Example 2:

+ +
Input: root1 = [1,2,3], root2 = [1,3,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each tree will be in the range [1, 200].
  • +
  • Both of the given trees will have values in the range [0, 200].
  • +
+
\ No newline at end of file diff --git a/0875-koko-eating-bananas/0875-koko-eating-bananas.cpp b/0875-koko-eating-bananas/0875-koko-eating-bananas.cpp new file mode 100644 index 00000000..79c84b65 --- /dev/null +++ b/0875-koko-eating-bananas/0875-koko-eating-bananas.cpp @@ -0,0 +1,39 @@ +#define ll long long int +class Solution { +public: + + ll check(vector& piles, int mid, int h) + { + int take = 0; + for(int i = 0; i& piles, int h) { + + ll low = 1; + ll high = accumulate(piles.begin(),piles.end(),0LL); + int ans = 0; + + while(low <= high) + { + ll mid = low + (high - low)/2; + if(check(piles,mid,h)) + { + high = mid-1; + ans = mid; + } + else + low = mid + 1; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0875-koko-eating-bananas/NOTES.md b/0875-koko-eating-bananas/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0875-koko-eating-bananas/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0875-koko-eating-bananas/README.md b/0875-koko-eating-bananas/README.md new file mode 100644 index 00000000..c6eea5f5 --- /dev/null +++ b/0875-koko-eating-bananas/README.md @@ -0,0 +1,36 @@ +

875. Koko Eating Bananas

Medium


Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

+ +

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

+ +

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

+ +

Return the minimum integer k such that she can eat all the bananas within h hours.

+ +

 

+

Example 1:

+ +
Input: piles = [3,6,7,11], h = 8
+Output: 4
+
+ +

Example 2:

+ +
Input: piles = [30,11,23,4,20], h = 5
+Output: 30
+
+ +

Example 3:

+ +
Input: piles = [30,11,23,4,20], h = 6
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= piles.length <= 104
  • +
  • piles.length <= h <= 109
  • +
  • 1 <= piles[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.cpp b/0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.cpp new file mode 100644 index 00000000..71c8ab29 --- /dev/null +++ b/0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.cpp @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + + ListNode* fast = head, *slow = head; + + while(fast and fast->next) + { + slow = slow->next; + fast = fast->next->next; + } + + return slow; + } +}; \ No newline at end of file diff --git a/0876-middle-of-the-linked-list/README.md b/0876-middle-of-the-linked-list/README.md new file mode 100644 index 00000000..bb08722c --- /dev/null +++ b/0876-middle-of-the-linked-list/README.md @@ -0,0 +1,27 @@ +

876. Middle of the Linked List

Easy


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

+ +

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

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [3,4,5]
+Explanation: The middle node of the list is node 3.
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5,6]
+Output: [4,5,6]
+Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 100].
  • +
  • 1 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/0879-profitable-schemes/0879-profitable-schemes.cpp b/0879-profitable-schemes/0879-profitable-schemes.cpp new file mode 100644 index 00000000..ed871928 --- /dev/null +++ b/0879-profitable-schemes/0879-profitable-schemes.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int dp[101][101][101]; + const int mod = 1e9 + 7; + int help(int idx, int members, int pro, int n, int minProfit, vector &group, vector &profit) + { + if (idx == group.size()) + return pro >= minProfit; + + if (dp[idx][members][pro] != -1) + return dp[idx][members][pro]; + + int take = 0; + if (members + group[idx] <= n) + take = help(idx + 1, members + group[idx], min(minProfit, pro + profit[idx]), n, minProfit, group, profit); + + int nottake = help(idx + 1, members, pro, n, minProfit, group, profit); + return dp[idx][members][pro] = ((long)take + (long)nottake) % mod; + } + int profitableSchemes(int n, int minProfit, vector &group, vector &profit) + { + memset(dp, -1, sizeof(dp)); + return help(0, 0, 0, n, minProfit, group, profit); + } +}; \ No newline at end of file diff --git a/0879-profitable-schemes/README.md b/0879-profitable-schemes/README.md new file mode 100644 index 00000000..175aaf7f --- /dev/null +++ b/0879-profitable-schemes/README.md @@ -0,0 +1,33 @@ +

879. Profitable Schemes

Hard


There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.

+ +

Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.

+ +

Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
+Output: 2
+Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
+In total, there are 2 schemes.
+ +

Example 2:

+ +
Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
+Output: 7
+Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
+There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 0 <= minProfit <= 100
  • +
  • 1 <= group.length <= 100
  • +
  • 1 <= group[i] <= 100
  • +
  • profit.length == group.length
  • +
  • 0 <= profit[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0880-decoded-string-at-index/0880-decoded-string-at-index.cpp b/0880-decoded-string-at-index/0880-decoded-string-at-index.cpp new file mode 100644 index 00000000..09875315 --- /dev/null +++ b/0880-decoded-string-at-index/0880-decoded-string-at-index.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string decodeAtIndex(string s, int k) { + + int n = s.size(); + + long long totalLength = 0; + + for(int i = 0; i < n; ++i) + { + if(isalpha(s[i])) + ++totalLength; + else + totalLength = totalLength * (s[i] - '0'); + } + + for(int i = n-1; i >= 0; --i) + { + k = k % totalLength; + if(k == 0 and isalpha(s[i])) + return string(1, s[i]); + if(isalpha(s[i])) + totalLength -= 1; + else + totalLength /= (s[i] - '0'); + } + + return ""; + } +}; \ No newline at end of file diff --git a/0880-decoded-string-at-index/README.md b/0880-decoded-string-at-index/README.md new file mode 100644 index 00000000..2831eaa7 --- /dev/null +++ b/0880-decoded-string-at-index/README.md @@ -0,0 +1,46 @@ +

880. Decoded String at Index

Medium


You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:

+ +
    +
  • If the character read is a letter, that letter is written onto the tape.
  • +
  • If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.
  • +
+ +

Given an integer k, return the kth letter (1-indexed) in the decoded string.

+ +

 

+

Example 1:

+ +
Input: s = "leet2code3", k = 10
+Output: "o"
+Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
+The 10th letter in the string is "o".
+
+ +

Example 2:

+ +
Input: s = "ha22", k = 5
+Output: "h"
+Explanation: The decoded string is "hahahaha".
+The 5th letter is "h".
+
+ +

Example 3:

+ +
Input: s = "a2345678999999999999999", k = 1
+Output: "a"
+Explanation: The decoded string is "a" repeated 8301530446056247680 times.
+The 1st letter is "a".
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 100
  • +
  • s consists of lowercase English letters and digits 2 through 9.
  • +
  • s starts with a letter.
  • +
  • 1 <= k <= 109
  • +
  • It is guaranteed that k is less than or equal to the length of the decoded string.
  • +
  • The decoded string is guaranteed to have less than 263 letters.
  • +
+
\ No newline at end of file diff --git a/0881-boats-to-save-people/0881-boats-to-save-people.cpp b/0881-boats-to-save-people/0881-boats-to-save-people.cpp new file mode 100644 index 00000000..9bdda773 --- /dev/null +++ b/0881-boats-to-save-people/0881-boats-to-save-people.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int numRescueBoats(vector& people, int limit) { + + int cnt = 0; + + sort(people.begin(),people.end()); + + int n = people.size(); + int start = 0, end = n-1; + + while(start <= end) + { + if(people[start] + people[end] <= limit) + { + ++start, --end; + } + else + --end; + ++cnt; + } + + return cnt; + } +}; \ No newline at end of file diff --git a/0881-boats-to-save-people/NOTES.md b/0881-boats-to-save-people/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0881-boats-to-save-people/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0885-spiral-matrix-iii/0885-spiral-matrix-iii.cpp b/0885-spiral-matrix-iii/0885-spiral-matrix-iii.cpp new file mode 100644 index 00000000..78e13cb1 --- /dev/null +++ b/0885-spiral-matrix-iii/0885-spiral-matrix-iii.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + vector> spiralMatrixIII(int rows, int cols, int rStart, int cStart) { + + vector> res; + int step = 1, ctr = 0; + + auto isValid = [&]() + { + return (rStart >= 0 and rStart < rows and cStart >= 0 and cStart < cols); + }; + + while(ctr < rows * cols) + { + for(int i = 0; i < step; ++i) + { + if(isValid()) + res.push_back({rStart, cStart}), ++ctr; + ++cStart; + } + + for(int i = 0; i < step; ++i) + { + if(isValid()) + res.push_back({rStart, cStart}), ++ctr; + ++rStart; + } + + ++step; + + for(int i = 0; i < step; ++i) + { + if(isValid()) + res.push_back({rStart, cStart}), ++ctr; + --cStart; + } + + for(int i = 0; i < step; ++i) + { + if(isValid()) + res.push_back({rStart, cStart}), ++ctr; + --rStart; + } + + ++step; + } + + return res; + } +}; \ No newline at end of file diff --git a/0885-spiral-matrix-iii/README.md b/0885-spiral-matrix-iii/README.md new file mode 100644 index 00000000..721d4ed3 --- /dev/null +++ b/0885-spiral-matrix-iii/README.md @@ -0,0 +1,28 @@ +

885. Spiral Matrix III

Medium


You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

+ +

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

+ +

Return an array of coordinates representing the positions of the grid in the order you visited them.

+ +

 

+

Example 1:

+ +
Input: rows = 1, cols = 4, rStart = 0, cStart = 0
+Output: [[0,0],[0,1],[0,2],[0,3]]
+
+ +

Example 2:

+ +
Input: rows = 5, cols = 6, rStart = 1, cStart = 4
+Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= rows, cols <= 100
  • +
  • 0 <= rStart < rows
  • +
  • 0 <= cStart < cols
  • +
+
\ No newline at end of file diff --git a/0886-possible-bipartition/0886-possible-bipartition.cpp b/0886-possible-bipartition/0886-possible-bipartition.cpp new file mode 100644 index 00000000..13e2d8fb --- /dev/null +++ b/0886-possible-bipartition/0886-possible-bipartition.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + bool possibleBipartition(int n, vector>& dislikes) { + vector color(n+1,0); + vector adj[n+1]; + for(int i=0;i q; + q.push(i); + while(!q.empty()){ + int node=q.front(); + q.pop(); + for(int child:adj[node]){ + if(color[child]==color[node])return false; + if(!color[child]){ + q.push(child); + color[child]=-1*color[node]; + } + } + } + } + } + + return true; + } +}; \ No newline at end of file diff --git a/0886-possible-bipartition/README.md b/0886-possible-bipartition/README.md new file mode 100644 index 00000000..50c984c4 --- /dev/null +++ b/0886-possible-bipartition/README.md @@ -0,0 +1,36 @@ +

886. Possible Bipartition

Medium


We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.

+ +

Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

+ +

 

+

Example 1:

+ +
Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
+Output: true
+Explanation: group1 [1,4] and group2 [2,3].
+
+ +

Example 2:

+ +
Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
+Output: false
+
+ +

Example 3:

+ +
Input: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2000
  • +
  • 0 <= dislikes.length <= 104
  • +
  • dislikes[i].length == 2
  • +
  • 1 <= dislikes[i][j] <= n
  • +
  • ai < bi
  • +
  • All the pairs of dislikes are unique.
  • +
+
\ No newline at end of file diff --git a/0890. Find and Replace Pattern.cpp b/0890. Find and Replace Pattern.cpp new file mode 100644 index 00000000..1822e4ef --- /dev/null +++ b/0890. Find and Replace Pattern.cpp @@ -0,0 +1,46 @@ +// 890.✅ Find and Replace Pattern + +class Solution +{ +public: + vector found_Pattern(string pattern) + { + if (pattern.size() == 0) + return {}; + + vector v; + int ind = 0; + unordered_map mp; + for (int i = 0; i < pattern.size(); ++i) + { + if (mp.find(pattern[i]) == mp.end()) + { + mp.insert({pattern[i], ind++}); + v.push_back(mp[pattern[i]]); + } + else + { + v.push_back(mp[pattern[i]]); + } + } + return v; + } + vector findAndReplacePattern(vector &words, string pattern) + { + + vector v = found_Pattern(pattern); + + int n = words.size(); + vector ans; + + for (int i = 0; i < n; ++i) + { + vector pattern_word = found_Pattern(words[i]); + + if (v == pattern_word) + ans.push_back(words[i]); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0894-all-possible-full-binary-trees/README.md b/0894-all-possible-full-binary-trees/README.md new file mode 100644 index 00000000..6a00abbe --- /dev/null +++ b/0894-all-possible-full-binary-trees/README.md @@ -0,0 +1,26 @@ +

894. All Possible Full Binary Trees

Medium


Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.

+ +

Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.

+ +

A full binary tree is a binary tree where each node has exactly 0 or 2 children.

+ +

 

+

Example 1:

+ +
Input: n = 7
+Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
+
+ +

Example 2:

+ +
Input: n = 3
+Output: [[0,0,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 20
  • +
+
\ No newline at end of file diff --git a/0904-fruit-into-baskets/0904-fruit-into-baskets.cpp b/0904-fruit-into-baskets/0904-fruit-into-baskets.cpp new file mode 100644 index 00000000..8139d7d2 --- /dev/null +++ b/0904-fruit-into-baskets/0904-fruit-into-baskets.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int totalFruit(vector& fruits) { + + map mp; + int i = 0, j = 0, n = fruits.size(), k = 2; + int ans = 0; + + while(j < n) + { + ++mp[fruits[j]]; + if(mp.size() <= k) + { + ans = max(ans, j - i + 1); + } + else + { + while(mp.size() > k) + { + --mp[fruits[i]]; + if(mp[fruits[i]] == 0) + mp.erase(fruits[i]); + ++i; + } + } + ++j; + + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0904-fruit-into-baskets/NOTES.md b/0904-fruit-into-baskets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0904-fruit-into-baskets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0904-fruit-into-baskets/README.md b/0904-fruit-into-baskets/README.md new file mode 100644 index 00000000..d8e708d4 --- /dev/null +++ b/0904-fruit-into-baskets/README.md @@ -0,0 +1,44 @@ +

904. Fruit Into Baskets

Medium


You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.

+ +

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

+ +
    +
  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • +
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • +
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
  • +
+ +

Given the integer array fruits, return the maximum number of fruits you can pick.

+ +

 

+

Example 1:

+ +
Input: fruits = [1,2,1]
+Output: 3
+Explanation: We can pick from all 3 trees.
+
+ +

Example 2:

+ +
Input: fruits = [0,1,2,2]
+Output: 3
+Explanation: We can pick from trees [1,2,2].
+If we had started at the first tree, we would only pick from trees [0,1].
+
+ +

Example 3:

+ +
Input: fruits = [1,2,3,2,2]
+Output: 4
+Explanation: We can pick from trees [2,3,2,2].
+If we had started at the first tree, we would only pick from trees [1,2].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= fruits.length <= 105
  • +
  • 0 <= fruits[i] < fruits.length
  • +
+
\ No newline at end of file diff --git a/0907-sum-of-subarray-minimums/0907-sum-of-subarray-minimums.cpp b/0907-sum-of-subarray-minimums/0907-sum-of-subarray-minimums.cpp new file mode 100644 index 00000000..a9cbb15f --- /dev/null +++ b/0907-sum-of-subarray-minimums/0907-sum-of-subarray-minimums.cpp @@ -0,0 +1,103 @@ +class Solution { +public: + int sumSubarrayMins(vector& arr) { + + int n = arr.size(); + long long ans = 0; + long long mod = (int) 1e9+7; + + vector next_smaller(n), prev_smaller(n); + stack st1, st2; + + for(int i = 0; i arr[i]) + { + next_smaller[st1.top()] = i - st1.top() - 1; + st1.pop(); + } + st1.push(i); + } + + for(int i = n-1; i>= 0; --i){ + while(!st2.empty() and arr[st2.top()] >= arr[i]) + { + prev_smaller[st2.top()] = st2.top() - i - 1; + st2.pop(); + } + st2.push(i); + } + + for(int i= 0; i& arr) { + + int n = arr.size(); + long long ans = 0; + int mod = 1e9 + 7; + + + for(int i = 0; i < n; ++i) + { + int mini = INT_MAX; + for(int j = i; j < n; ++j){ + if(arr[j] < mini) + { + mini = arr[j]; + ans += arr[j]; + ans %= mod; + } + else + { + ans += mini; + ans %= mod; + } + } + } + return ans%mod; + } +}; + +*/ + +/* + O(n^3) + + class Solution { + public: + int sumSubarrayMins(vector& arr) { + int sum =0 ,n = arr.size(); + for(int i=0;i& arr) { +int n = arr.size(); +long long ans = 0; +long long mod = (int) 1e9+7; +vector next_smaller(n), prev_smaller(n); +stack st1, st2; +for(int i = 0; i arr[i]) +{ +next_smaller[st1.top()] = i - st1.top() - 1; +st1.pop(); +} +st1.push(i); \ No newline at end of file diff --git a/0907-sum-of-subarray-minimums/README.md b/0907-sum-of-subarray-minimums/README.md new file mode 100644 index 00000000..95fd00a1 --- /dev/null +++ b/0907-sum-of-subarray-minimums/README.md @@ -0,0 +1,27 @@ +

907. Sum of Subarray Minimums

Medium


Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: arr = [3,1,2,4]
+Output: 17
+Explanation: 
+Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
+Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
+Sum is 17.
+
+ +

Example 2:

+ +
Input: arr = [11,81,94,43,3]
+Output: 444
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 3 * 104
  • +
  • 1 <= arr[i] <= 3 * 104
  • +
+
\ No newline at end of file diff --git a/0909-snakes-and-ladders/0909-snakes-and-ladders.cpp b/0909-snakes-and-ladders/0909-snakes-and-ladders.cpp new file mode 100644 index 00000000..787089f9 --- /dev/null +++ b/0909-snakes-and-ladders/0909-snakes-and-ladders.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + vector findcordinates(int pos,int n){ + vectortemp; + int r=n-(pos-1)/n-1; + int c=(pos-1)%n; + if(r%2==n%2){ + return temp={r,n-1-c}; + }else{ + return temp={r,c}; + } + } + + + int snakesAndLadders(vector>& board) { + int n= board.size(); + queueq; + vector>visited( n , vector(n, false)); + int ans=0; + q.push(1); + visited[n-1][0]=true; + while(!q.empty()){ + int size=q.size(); + + for(int i=0;in*n) break; + vectorpos=findcordinates(front+k,n); + int r=pos[0]; + int c=pos[1]; + if(visited[r][c]==true) continue; + visited[r][c]=true; + if(board[r][c]!=-1){ + q.push(board[r][c]); + }else{ + q.push(front+k); + } + + } + } + ans++; + } + return -1; + } +}; diff --git a/0909-snakes-and-ladders/NOTES.md b/0909-snakes-and-ladders/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0909-snakes-and-ladders/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0912-sort-an-array/0912-sort-an-array.cpp b/0912-sort-an-array/0912-sort-an-array.cpp new file mode 100644 index 00000000..d01e3134 --- /dev/null +++ b/0912-sort-an-array/0912-sort-an-array.cpp @@ -0,0 +1,71 @@ +class Solution { +public: + + void merge(int beg, int end, int mid, vector&a) + { + int i, j, k; + int n1 = mid - beg + 1; + int n2 = end - mid; + + int LeftArray[n1], RightArray[n2]; + + + for (int i = 0; i < n1; i++) + LeftArray[i] = a[beg + i]; + for (int j = 0; j < n2; j++) + RightArray[j] = a[mid + 1 + j]; + + i = 0; + j = 0; + k = beg; + + while (i < n1 && j < n2) + { + if(LeftArray[i] <= RightArray[j]) + { + a[k] = LeftArray[i]; + i++; + } + else + { + a[k] = RightArray[j]; + j++; + } + k++; + } + while (i& nums) + { + if(i < j) + { + int mid = i + (j-i)/2; + mergeSort(i,mid,nums); + mergeSort(mid+1,j, nums); + merge(i,j,mid,nums); + } + } + + vector sortArray(vector& nums) { + + int n = nums.size(); + + mergeSort(0,n-1,nums); + + return nums; + + } +}; \ No newline at end of file diff --git a/0912-sort-an-array/NOTES.md b/0912-sort-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0912-sort-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0912-sort-an-array/README.md b/0912-sort-an-array/README.md new file mode 100644 index 00000000..9b50c617 --- /dev/null +++ b/0912-sort-an-array/README.md @@ -0,0 +1,27 @@ +

912. Sort an Array

Medium


Given an array of integers nums, sort the array in ascending order and return it.

+ +

You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

+ +

 

+

Example 1:

+ +
Input: nums = [5,2,3,1]
+Output: [1,2,3,5]
+Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
+
+ +

Example 2:

+ +
Input: nums = [5,1,1,2,0,0]
+Output: [0,0,1,1,2,5]
+Explanation: Note that the values of nums are not necessairly unique.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -5 * 104 <= nums[i] <= 5 * 104
  • +
+
\ No newline at end of file diff --git a/0916. Word Subsets.cpp b/0916. Word Subsets.cpp new file mode 100644 index 00000000..06d5eef2 --- /dev/null +++ b/0916. Word Subsets.cpp @@ -0,0 +1,98 @@ +// 916. Word Subsets + +class Solution +{ +public: + bool check(unordered_map m, unordered_map mp, string str) + { + for (int i = 0; i < str.size(); ++i) + { + if (mp[str[i]] < m[str[i]]) + return false; + } + return true; + } + + vector wordSubsets(vector &words1, vector &words2) + { + + vector ans; + + unordered_map m; + for (auto itr : words2) + { + unordered_map m1; + for (auto x : itr) + { + ++m1[x]; + m[x] = max(m[x], m1[x]); + } + } + + string str = ""; + for (auto itr : m) + { + for (int i = 0; i < itr.second; ++i) + str += itr.first; + } + + cout << str; + + // unordered_map mp = generate(str); + + for (int i = 0; i < words1.size(); ++i) + { + unordered_map mp; + for (auto itr : words1[i]) + ++mp[itr]; + + if (check(m, mp, str)) + ans.push_back(words1[i]); + } + + return ans; + } +}; + +class Solution +{ +public: + vector wordSubsets(vector &words1, vector &words2) + { + + vector freq(26, 0); + + for (auto itr : words2) + { + vector temp(26, 0); + for (auto x : itr) + { + ++temp[x - 'a']; + freq[x - 'a'] = max(temp[x - 'a'], freq[x - 'a']); + } + } + + vector ans; + + for (auto itr : words1) + { + vector temp(26, 0); + for (auto x : itr) + ++temp[x - 'a']; + + bool flag = true; + + for (int i = 0; i < 26; ++i) + { + if (freq[i] > temp[i]) + { + flag = false; + break; + } + } + if (flag) + ans.push_back(itr); + } + return ans; + } +}; diff --git a/0918-maximum-sum-circular-subarray/0918-maximum-sum-circular-subarray.cpp b/0918-maximum-sum-circular-subarray/0918-maximum-sum-circular-subarray.cpp new file mode 100644 index 00000000..4b5928cf --- /dev/null +++ b/0918-maximum-sum-circular-subarray/0918-maximum-sum-circular-subarray.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + + int currSum = 0, maxSum = INT_MIN, currSum2 = 0, minSum = INT_MAX; + int totSum =0 ; + int n = nums.size(); + + for(int i = 0; i 0) + currSum2 = 0; + } + + return (maxSum > 0 ? max(maxSum, totSum - minSum) : maxSum); + + } +}; \ No newline at end of file diff --git a/0918-maximum-sum-circular-subarray/NOTES.md b/0918-maximum-sum-circular-subarray/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0918-maximum-sum-circular-subarray/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0920-number-of-music-playlists/0920-number-of-music-playlists.cpp b/0920-number-of-music-playlists/0920-number-of-music-playlists.cpp new file mode 100644 index 00000000..61bc1a30 --- /dev/null +++ b/0920-number-of-music-playlists/0920-number-of-music-playlists.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int mod = 1e9 + 7; + + long long int helper(int n, int k, int goal, vector< vector< int>> &dp) + { + if(n==0 and goal==0) + return 1; + + if(n==0 || goal==0) + return 0; + + if(dp[n][goal]!=-1) + return dp[n][goal]; + + long long int a = (helper(n-1, k, goal-1, dp)*n); + + long long int b = (helper(n, k, goal-1, dp)*(max(n-k, 0))); + + return dp[n][goal] = (a+b)%mod; + } + int numMusicPlaylists(int n, int goal, int k) + { + vector< vector< int>> dp(n+1, vector(goal+1, -1)); + + return helper(n,k,goal, dp); + } +}; \ No newline at end of file diff --git a/0920-number-of-music-playlists/NOTES.md b/0920-number-of-music-playlists/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0920-number-of-music-playlists/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0920-number-of-music-playlists/README.md b/0920-number-of-music-playlists/README.md new file mode 100644 index 00000000..6d344821 --- /dev/null +++ b/0920-number-of-music-playlists/README.md @@ -0,0 +1,37 @@ +

920. Number of Music Playlists

Hard


Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:

+ +
    +
  • Every song is played at least once.
  • +
  • A song can only be played again only if k other songs have been played.
  • +
+ +

Given n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.

+

 

+

Example 1:

+ +
Input: n = 3, goal = 3, k = 1
+Output: 6
+Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].
+
+ +

Example 2:

+ +
Input: n = 2, goal = 3, k = 0
+Output: 6
+Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].
+
+ +

Example 3:

+ +
Input: n = 2, goal = 3, k = 1
+Output: 2
+Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= k < n <= goal <= 100
  • +
+
\ No newline at end of file diff --git a/0926-flip-string-to-monotone-increasing/0926-flip-string-to-monotone-increasing.cpp b/0926-flip-string-to-monotone-increasing/0926-flip-string-to-monotone-increasing.cpp new file mode 100644 index 00000000..6eafea45 --- /dev/null +++ b/0926-flip-string-to-monotone-increasing/0926-flip-string-to-monotone-increasing.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minFlipsMonoIncr(string s) { + { + int count_flip = 0, count_one = 0; + for (auto i : s) + { + if (i == '1') + count_one++; + else{ + count_flip++; + count_flip = min(count_flip, count_one); + } + } + return count_flip; + } + } +}; \ No newline at end of file diff --git a/0926-flip-string-to-monotone-increasing/README.md b/0926-flip-string-to-monotone-increasing/README.md new file mode 100644 index 00000000..191b2d8f --- /dev/null +++ b/0926-flip-string-to-monotone-increasing/README.md @@ -0,0 +1,36 @@ +

926. Flip String to Monotone Increasing

Medium


A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).

+ +

You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.

+ +

Return the minimum number of flips to make s monotone increasing.

+ +

 

+

Example 1:

+ +
Input: s = "00110"
+Output: 1
+Explanation: We flip the last digit to get 00111.
+
+ +

Example 2:

+ +
Input: s = "010110"
+Output: 2
+Explanation: We flip to get 011111, or alternatively 000111.
+
+ +

Example 3:

+ +
Input: s = "00011000"
+Output: 2
+Explanation: We flip to get 00000000.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/0930-binary-subarrays-with-sum/0930-binary-subarrays-with-sum.cpp b/0930-binary-subarrays-with-sum/0930-binary-subarrays-with-sum.cpp new file mode 100644 index 00000000..d9a7b100 --- /dev/null +++ b/0930-binary-subarrays-with-sum/0930-binary-subarrays-with-sum.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + + int ans = 0, n = nums.size(); + + map mp; + mp.insert({0, 1}); + + int sum = 0; + + for(int j = 0; j < n; ++j) + { + sum += nums[j]; + if(mp.find(sum - goal) != mp.end()) + { + ans += mp[sum - goal]; + } + + ++mp[sum]; + } + + return ans; + } +}; diff --git a/0930-binary-subarrays-with-sum/NOTES.md b/0930-binary-subarrays-with-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0930-binary-subarrays-with-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0930-binary-subarrays-with-sum/README.md b/0930-binary-subarrays-with-sum/README.md new file mode 100644 index 00000000..63710621 --- /dev/null +++ b/0930-binary-subarrays-with-sum/README.md @@ -0,0 +1,30 @@ +

930. Binary Subarrays With Sum

Medium


Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

+ +

A subarray is a contiguous part of the array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,0,1,0,1], goal = 2
+Output: 4
+Explanation: The 4 subarrays are bolded and underlined below:
+[1,0,1,0,1]
+[1,0,1,0,1]
+[1,0,1,0,1]
+[1,0,1,0,1]
+
+ +

Example 2:

+ +
Input: nums = [0,0,0,0,0], goal = 0
+Output: 15
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • nums[i] is either 0 or 1.
  • +
  • 0 <= goal <= nums.length
  • +
\ No newline at end of file diff --git a/0931-minimum-falling-path-sum/0931-minimum-falling-path-sum.cpp b/0931-minimum-falling-path-sum/0931-minimum-falling-path-sum.cpp new file mode 100644 index 00000000..f480dd49 --- /dev/null +++ b/0931-minimum-falling-path-sum/0931-minimum-falling-path-sum.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minFallingPathSum(vector>& A) { + int m = A.size(); + vector> t(m, vector(m)); + + for(int col = 0; col931. Minimum Falling Path Sum

Medium


Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

+ +

A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).

+ +

 

+

Example 1:

+ +
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
+Output: 13
+Explanation: There are two falling paths with a minimum sum as shown.
+
+ +

Example 2:

+ +
Input: matrix = [[-19,57],[-40,-5]]
+Output: -59
+Explanation: The falling path with a minimum sum is shown.
+
+ +

 

+

Constraints:

+ +
    +
  • n == matrix.length == matrix[i].length
  • +
  • 1 <= n <= 100
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/0934-shortest-bridge/0934-shortest-bridge.cpp b/0934-shortest-bridge/0934-shortest-bridge.cpp new file mode 100644 index 00000000..068f8b80 --- /dev/null +++ b/0934-shortest-bridge/0934-shortest-bridge.cpp @@ -0,0 +1,97 @@ +class Solution { + +private: + + vector dx = {-1, 0, 0, 1}; + vector dy = {0, -1, 1, 0}; + + void dfs(int x, int y, int n, int m, vector>& grid, vector>& visited, int track) + { + + visited[x][y] = track; + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and grid[newx][newy] == 1 and !visited[newx][newy]) + { + dfs(newx, newy, n, n, grid, visited, track); + } + } + } + +public: + int shortestBridge(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector> visited(n, vector(m, 0)); + + int track = 1; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1 and !visited[i][j]) + { + ++track; + dfs(i, j, n, m, grid, visited, track); + } + } + } + + queue, int>> q; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(visited[i][j] == 2) + q.push({{i,j}, 0}); + } + } + + int ans = 1e9; + + // for(auto itr : visited) + // { + // for(auto x : itr) + // cout<= 0 and newy >= 0 and newx < n and newy < m and visited[newx][newy] == 3) + { + // cout<= 0 and newy >= 0 and newx < n and newy < m and visited[newx][newy] == 0) + { + visited[newx][newy] = true; + q.push({{newx,newy}, step + 1}); + } + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0934-shortest-bridge/NOTES.md b/0934-shortest-bridge/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0934-shortest-bridge/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0934-shortest-bridge/README.md b/0934-shortest-bridge/README.md new file mode 100644 index 00000000..91de5946 --- /dev/null +++ b/0934-shortest-bridge/README.md @@ -0,0 +1,37 @@ +

934. Shortest Bridge

Medium


You are given an n x n binary matrix grid where 1 represents land and 0 represents water.

+ +

An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.

+ +

You may change 0's to 1's to connect the two islands to form one island.

+ +

Return the smallest number of 0's you must flip to connect the two islands.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1],[1,0]]
+Output: 1
+
+ +

Example 2:

+ +
Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
+Output: 2
+
+ +

Example 3:

+ +
Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 2 <= n <= 100
  • +
  • grid[i][j] is either 0 or 1.
  • +
  • There are exactly two islands in grid.
  • +
+
\ No newline at end of file diff --git a/0938-range-sum-of-bst/0938-range-sum-of-bst.cpp b/0938-range-sum-of-bst/0938-range-sum-of-bst.cpp new file mode 100644 index 00000000..235bfc29 --- /dev/null +++ b/0938-range-sum-of-bst/0938-range-sum-of-bst.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int rangeSumBST(TreeNode* root, int low, int high) { + + if(!root) + return 0; + + if(root->val < low) + return rangeSumBST(root->right, low, high); + + if(root->val > high) + return rangeSumBST(root->left, low, high); + + return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); + } +}; \ No newline at end of file diff --git a/0938-range-sum-of-bst/NOTES.md b/0938-range-sum-of-bst/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0938-range-sum-of-bst/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0938-range-sum-of-bst/README.md b/0938-range-sum-of-bst/README.md new file mode 100644 index 00000000..25f2c7e6 --- /dev/null +++ b/0938-range-sum-of-bst/README.md @@ -0,0 +1,27 @@ +

938. Range Sum of BST

Easy


Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

+ +

 

+

Example 1:

+ +
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
+Output: 32
+Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
+
+ +

Example 2:

+ +
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
+Output: 23
+Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 2 * 104].
  • +
  • 1 <= Node.val <= 105
  • +
  • 1 <= low <= high <= 105
  • +
  • All Node.val are unique.
  • +
+
\ No newline at end of file diff --git a/0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.cpp b/0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.cpp new file mode 100644 index 00000000..b1a44086 --- /dev/null +++ b/0944-delete-columns-to-make-sorted/0944-delete-columns-to-make-sorted.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minDeletionSize(vector& strs) { + + int ans = 0; + for(int col = 0; col < strs[0].size(); ++col) + { + for(int row = 1; row < strs.size(); ++row) + { + if(strs[row-1][col] > strs[row][col]) + { + ++ans; + break; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/0944-delete-columns-to-make-sorted/NOTES.md b/0944-delete-columns-to-make-sorted/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0944-delete-columns-to-make-sorted/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0944-delete-columns-to-make-sorted/README.md b/0944-delete-columns-to-make-sorted/README.md new file mode 100644 index 00000000..8fb9e242 --- /dev/null +++ b/0944-delete-columns-to-make-sorted/README.md @@ -0,0 +1,56 @@ +

944. Delete Columns to Make Sorted

Easy


You are given an array of n strings strs, all of the same length.

+ +

The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as:

+ +
abc
+bce
+cae
+
+ +

You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.

+ +

Return the number of columns that you will delete.

+ +

 

+

Example 1:

+ +
Input: strs = ["cba","daf","ghi"]
+Output: 1
+Explanation: The grid looks as follows:
+  cba
+  daf
+  ghi
+Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
+
+ +

Example 2:

+ +
Input: strs = ["a","b"]
+Output: 0
+Explanation: The grid looks as follows:
+  a
+  b
+Column 0 is the only column and is sorted, so you will not delete any columns.
+
+ +

Example 3:

+ +
Input: strs = ["zyx","wvu","tsr"]
+Output: 3
+Explanation: The grid looks as follows:
+  zyx
+  wvu
+  tsr
+All 3 columns are not sorted, so you will delete all 3.
+
+ +

 

+

Constraints:

+ +
    +
  • n == strs.length
  • +
  • 1 <= n <= 100
  • +
  • 1 <= strs[i].length <= 1000
  • +
  • strs[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0945-minimum-increment-to-make-array-unique/0945-minimum-increment-to-make-array-unique.cpp b/0945-minimum-increment-to-make-array-unique/0945-minimum-increment-to-make-array-unique.cpp new file mode 100644 index 00000000..c46746a6 --- /dev/null +++ b/0945-minimum-increment-to-make-array-unique/0945-minimum-increment-to-make-array-unique.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minIncrementForUnique(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + int ans = 0; + + for(int i = 1; i < n; ++i) + { + if(nums[i-1] >= nums[i]) + { + ans += (nums[i-1] - nums[i] + 1); + nums[i] = nums[i-1] + 1; + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0945-minimum-increment-to-make-array-unique/NOTES.md b/0945-minimum-increment-to-make-array-unique/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0945-minimum-increment-to-make-array-unique/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0945-minimum-increment-to-make-array-unique/README.md b/0945-minimum-increment-to-make-array-unique/README.md new file mode 100644 index 00000000..b81b99e4 --- /dev/null +++ b/0945-minimum-increment-to-make-array-unique/README.md @@ -0,0 +1,30 @@ +

945. Minimum Increment to Make Array Unique

Medium


You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.

+ +

Return the minimum number of moves to make every value in nums unique.

+ +

The test cases are generated so that the answer fits in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,2]
+Output: 1
+Explanation: After 1 move, the array could be [1, 2, 3].
+
+ +

Example 2:

+ +
Input: nums = [3,2,1,2,1,7]
+Output: 6
+Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
+It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0946-validate-stack-sequences/0946-validate-stack-sequences.cpp b/0946-validate-stack-sequences/0946-validate-stack-sequences.cpp new file mode 100644 index 00000000..11e8f431 --- /dev/null +++ b/0946-validate-stack-sequences/0946-validate-stack-sequences.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + bool validateStackSequences(vector& pushed, vector& popped) { + + + stack st; + int n = pushed.size(); + int k = 0; + + st.push(pushed[0]); + + for(int i =1 ; i946. Validate Stack Sequences

Medium


Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
+Output: true
+Explanation: We might do the following sequence:
+push(1), push(2), push(3), push(4),
+pop() -> 4,
+push(5),
+pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
+
+ +

Example 2:

+ +
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
+Output: false
+Explanation: 1 cannot be popped before 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pushed.length <= 1000
  • +
  • 0 <= pushed[i] <= 1000
  • +
  • All the elements of pushed are unique.
  • +
  • popped.length == pushed.length
  • +
  • popped is a permutation of pushed.
  • +
+
\ No newline at end of file diff --git a/0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.cpp b/0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.cpp new file mode 100644 index 00000000..361361b5 --- /dev/null +++ b/0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.cpp @@ -0,0 +1,111 @@ +class DSU{ + private: + vector rank, parent, size; + public: + DSU(int n) + { + rank.resize(n+1, 0); + parent.resize(n+1); + size.resize(n+1, 1); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(parent[u] == u) + return u; + + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else{ + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + int removeStones(vector>& stones) { + + int n = stones.size(); + + int maxRow = 0, maxCol = 0; + + for(auto itr : stones) + { + maxRow = max(maxRow, itr[0]); + maxCol = max(maxCol, itr[1]); + } + + DSU dsu(maxRow + maxCol + 1); + + unordered_map mp; + + for(auto itr : stones) + { + int row = itr[0]; + int col = itr[1] + maxRow + 1; + + dsu.unionBySize(row, col); + + mp[row] = 1; + mp[col] = 1; + } + + int cnt = 0; + + for(auto itr : mp) + { + if(itr.first == dsu.findParent(itr.first)) + ++cnt; + } + + return n - cnt; + + } +}; \ No newline at end of file diff --git a/0947-most-stones-removed-with-same-row-or-column/NOTES.md b/0947-most-stones-removed-with-same-row-or-column/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0947-most-stones-removed-with-same-row-or-column/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0947-most-stones-removed-with-same-row-or-column/README.md b/0947-most-stones-removed-with-same-row-or-column/README.md new file mode 100644 index 00000000..3c4401fb --- /dev/null +++ b/0947-most-stones-removed-with-same-row-or-column/README.md @@ -0,0 +1,47 @@ +

947. Most Stones Removed with Same Row or Column

Medium


On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

+ +

A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.

+ +

Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

+ +

 

+

Example 1:

+ +
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
+Output: 5
+Explanation: One way to remove 5 stones is as follows:
+1. Remove stone [2,2] because it shares the same row as [2,1].
+2. Remove stone [2,1] because it shares the same column as [0,1].
+3. Remove stone [1,2] because it shares the same row as [1,0].
+4. Remove stone [1,0] because it shares the same column as [0,0].
+5. Remove stone [0,1] because it shares the same row as [0,0].
+Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.
+
+ +

Example 2:

+ +
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
+Output: 3
+Explanation: One way to make 3 moves is as follows:
+1. Remove stone [2,2] because it shares the same row as [2,0].
+2. Remove stone [2,0] because it shares the same column as [0,0].
+3. Remove stone [0,2] because it shares the same row as [0,0].
+Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.
+
+ +

Example 3:

+ +
Input: stones = [[0,0]]
+Output: 0
+Explanation: [0,0] is the only stone on the plane, so you cannot remove it.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= stones.length <= 1000
  • +
  • 0 <= xi, yi <= 104
  • +
  • No two stones are at the same coordinate point.
  • +
+
\ No newline at end of file diff --git a/0948-bag-of-tokens/0948-bag-of-tokens.cpp b/0948-bag-of-tokens/0948-bag-of-tokens.cpp new file mode 100644 index 00000000..b1fbb888 --- /dev/null +++ b/0948-bag-of-tokens/0948-bag-of-tokens.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int bagOfTokensScore(vector& tokens, int power) { + + int start = 0, end = tokens.size()-1; + int score = 0, maxScore = 0; + + sort(tokens.begin(), tokens.end()); + + while(start <= end) + { + if(power >= tokens[start]) + { + ++score; + maxScore = max(maxScore, score); + power -= tokens[start++]; + } + else if(score > 0) + { + power += tokens[end--]; + --score; + } + else + break; + } + + return maxScore; + } +}; \ No newline at end of file diff --git a/0948-bag-of-tokens/NOTES.md b/0948-bag-of-tokens/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0948-bag-of-tokens/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0948-bag-of-tokens/README.md b/0948-bag-of-tokens/README.md new file mode 100644 index 00000000..968d02c5 --- /dev/null +++ b/0948-bag-of-tokens/README.md @@ -0,0 +1,106 @@ +

948. Bag of Tokens

Medium


You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.

+ +

Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):

+ +
    +
  • Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.
  • +
  • Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score.
  • +
+ +

Return the maximum possible score you can achieve after playing any number of tokens.

+ +

 

+

Example 1:

+ +
+

Input: tokens = [100], power = 50

+ +

Output: 0

+ +

Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).

+
+ +

Example 2:

+ +
+

Input: tokens = [200,100], power = 150

+ +

Output: 1

+ +

Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.

+ +

There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.

+
+ +

Example 3:

+ +
+

Input: tokens = [100,200,300,400], power = 200

+ +

Output: 2

+ +

Explanation: Play the tokens in this order to get a score of 2:

+ +
    +
  1. Play token0 (100) face-up, reducing power to 100 and increasing score to 1.
  2. +
  3. Play token3 (400) face-down, increasing power to 500 and reducing score to 0.
  4. +
  5. Play token1 (200) face-up, reducing power to 300 and increasing score to 1.
  6. +
  7. Play token2 (300) face-up, reducing power to 0 and increasing score to 2.
  8. +
+ +

The maximum score achievable is 2.

+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= tokens.length <= 1000
  • +
  • 0 <= tokens[i], power < 104
  • +
+
\ No newline at end of file diff --git a/0950-reveal-cards-in-increasing-order/0950-reveal-cards-in-increasing-order.cpp b/0950-reveal-cards-in-increasing-order/0950-reveal-cards-in-increasing-order.cpp new file mode 100644 index 00000000..5c3092eb --- /dev/null +++ b/0950-reveal-cards-in-increasing-order/0950-reveal-cards-in-increasing-order.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector deckRevealedIncreasing(vector& deck) { + sort(deck.rbegin(), deck.rend()); + deque d; + d.push_back(deck[0]); + for (int i = 1; i < deck.size(); i++) { + d.push_front(d.back()); + d.pop_back(); + d.push_front(deck[i]); + } + vector res(d.begin(), d.end()); + return res; + } +}; \ No newline at end of file diff --git a/0950-reveal-cards-in-increasing-order/NOTES.md b/0950-reveal-cards-in-increasing-order/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0950-reveal-cards-in-increasing-order/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0950-reveal-cards-in-increasing-order/README.md b/0950-reveal-cards-in-increasing-order/README.md new file mode 100644 index 00000000..8fd4c765 --- /dev/null +++ b/0950-reveal-cards-in-increasing-order/README.md @@ -0,0 +1,49 @@ +

950. Reveal Cards In Increasing Order

Medium


You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].

+ +

You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.

+ +

You will do the following steps repeatedly until all cards are revealed:

+ +
    +
  1. Take the top card of the deck, reveal it, and take it out of the deck.
  2. +
  3. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
  4. +
  5. If there are still unrevealed cards, go back to step 1. Otherwise, stop.
  6. +
+ +

Return an ordering of the deck that would reveal the cards in increasing order.

+ +

Note that the first entry in the answer is considered to be the top of the deck.

+ +

 

+

Example 1:

+ +
Input: deck = [17,13,11,2,3,5,7]
+Output: [2,13,3,11,5,17,7]
+Explanation: 
+We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.
+After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
+We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
+We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
+We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
+We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
+We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
+We reveal 13, and move 17 to the bottom.  The deck is now [17].
+We reveal 17.
+Since all the cards revealed are in increasing order, the answer is correct.
+
+ +

Example 2:

+ +
Input: deck = [1,1000]
+Output: [1,1000]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= deck.length <= 1000
  • +
  • 1 <= deck[i] <= 106
  • +
  • All the values of deck are unique.
  • +
+
\ No newline at end of file diff --git a/0953-verifying-an-alien-dictionary/0953-verifying-an-alien-dictionary.cpp b/0953-verifying-an-alien-dictionary/0953-verifying-an-alien-dictionary.cpp new file mode 100644 index 00000000..d102c35c --- /dev/null +++ b/0953-verifying-an-alien-dictionary/0953-verifying-an-alien-dictionary.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + bool helper(string& a, string& b, map& mp) + { + int i = 0, j = 0; + + while(i < a.size() and j < b.size()) + { + if(a[i] != b[i]) + { + if(mp[a[i]] > mp[b[i]]) + return false; + else + return true; + } + ++i, ++j; + } + if(a.size() > b.size()) + return false; + return true; + } + + bool isAlienSorted(vector& words, string order) { + + map mp; + for(int i = 0; i < order.size(); ++i) + mp.insert({order[i],i+1}); + + for(int i = 0; i < words.size()-1; ++i) + { + if(!helper(words[i], words[i+1], mp)) + return false; + } + return true; + } +}; \ No newline at end of file diff --git a/0953-verifying-an-alien-dictionary/NOTES.md b/0953-verifying-an-alien-dictionary/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0953-verifying-an-alien-dictionary/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0953-verifying-an-alien-dictionary/README.md b/0953-verifying-an-alien-dictionary/README.md new file mode 100644 index 00000000..c8bab49a --- /dev/null +++ b/0953-verifying-an-alien-dictionary/README.md @@ -0,0 +1,36 @@ +

953. Verifying an Alien Dictionary

Easy


In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

+ +

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.

+ +

 

+

Example 1:

+ +
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
+Output: true
+Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
+
+ +

Example 2:

+ +
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
+Output: false
+Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
+
+ +

Example 3:

+ +
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
+Output: false
+Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 20
  • +
  • order.length == 26
  • +
  • All characters in words[i] and order are English lowercase letters.
  • +
+
\ No newline at end of file diff --git a/0955-delete-columns-to-make-sorted-ii/0955-delete-columns-to-make-sorted-ii.cpp b/0955-delete-columns-to-make-sorted-ii/0955-delete-columns-to-make-sorted-ii.cpp new file mode 100644 index 00000000..fd90fcc2 --- /dev/null +++ b/0955-delete-columns-to-make-sorted-ii/0955-delete-columns-to-make-sorted-ii.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minDeletionSize(vector& strs) { + + int n = strs.size(); + int m = strs[0].size(); + + unordered_set used; + + for(int i = 1; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(used.count(j) > 0 or strs[i-1][j] == strs[i][j]) + continue; + if(strs[i-1][j] > strs[i][j]) + { + used.insert(j); + i = 0; + } + + break; + } + } + + return used.size(); + } +}; \ No newline at end of file diff --git a/0955-delete-columns-to-make-sorted-ii/NOTES.md b/0955-delete-columns-to-make-sorted-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0955-delete-columns-to-make-sorted-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0955-delete-columns-to-make-sorted-ii/README.md b/0955-delete-columns-to-make-sorted-ii/README.md new file mode 100644 index 00000000..6e9342e7 --- /dev/null +++ b/0955-delete-columns-to-make-sorted-ii/README.md @@ -0,0 +1,46 @@ +

955. Delete Columns to Make Sorted II

Medium


You are given an array of n strings strs, all of the same length.

+ +

We may choose any deletion indices, and we delete all the characters in those indices for each string.

+ +

For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].

+ +

Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.

+ +

 

+

Example 1:

+ +
Input: strs = ["ca","bb","ac"]
+Output: 1
+Explanation: 
+After deleting the first column, strs = ["a", "b", "c"].
+Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
+We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
+
+ +

Example 2:

+ +
Input: strs = ["xc","yb","za"]
+Output: 0
+Explanation: 
+strs is already in lexicographic order, so we do not need to delete anything.
+Note that the rows of strs are not necessarily in lexicographic order:
+i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)
+
+ +

Example 3:

+ +
Input: strs = ["zyx","wvu","tsr"]
+Output: 3
+Explanation: We have to delete every column.
+
+ +

 

+

Constraints:

+ +
    +
  • n == strs.length
  • +
  • 1 <= n <= 100
  • +
  • 1 <= strs[i].length <= 100
  • +
  • strs[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0956-tallest-billboard/0956-tallest-billboard.cpp b/0956-tallest-billboard/0956-tallest-billboard.cpp new file mode 100644 index 00000000..13b1211d --- /dev/null +++ b/0956-tallest-billboard/0956-tallest-billboard.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int helper(int s1,int i,vector&r, vector>& dp){ + + if(i>=r.size()){ + if(s1)return INT_MIN; + return 0; + } + + if(dp[i].count(s1)){ + return dp[i][s1]; + } + + int ans = helper(s1,i+1,r,dp); + + ans = max(ans,r[i] + helper(s1-r[i],i+1,r,dp)); + + ans = max(ans,helper(s1+r[i],i+1,r,dp)); + + return dp[i][s1]=ans; + } + int tallestBillboard(vector& r) { + int n=r.size(); + + vector> dp(n+1); + + return helper(0,0,r,dp); + } +}; \ No newline at end of file diff --git a/0956-tallest-billboard/README.md b/0956-tallest-billboard/README.md new file mode 100644 index 00000000..7cd40f31 --- /dev/null +++ b/0956-tallest-billboard/README.md @@ -0,0 +1,37 @@ +

956. Tallest Billboard

Hard


You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.

+ +

You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.

+ +

Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.

+ +

 

+

Example 1:

+ +
Input: rods = [1,2,3,6]
+Output: 6
+Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
+
+ +

Example 2:

+ +
Input: rods = [1,2,3,4,5,6]
+Output: 10
+Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
+
+ +

Example 3:

+ +
Input: rods = [1,2]
+Output: 0
+Explanation: The billboard cannot be supported, so we return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= rods.length <= 20
  • +
  • 1 <= rods[i] <= 1000
  • +
  • sum(rods[i]) <= 5000
  • +
+
\ No newline at end of file diff --git a/0959-regions-cut-by-slashes/0959-regions-cut-by-slashes.cpp b/0959-regions-cut-by-slashes/0959-regions-cut-by-slashes.cpp new file mode 100644 index 00000000..614e2c88 --- /dev/null +++ b/0959-regions-cut-by-slashes/0959-regions-cut-by-slashes.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int regionsBySlashes(vector& grid) { + + int n = grid.size(); + int m = grid[0].size(); + int cnt = 0; + + vector> mat(n*3, vector(m*3, 0)); + vector> visited = mat; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == '/') + { + mat[i*3][j*3+2] = 1; + mat[i*3+1][j*3+1] = 1; + mat[i*3+2][j*3] = 1; + } + else if(grid[i][j] == '\\') + { + mat[i*3][j*3] = 1; + mat[i*3+1][j*3+1] = 1; + mat[i*3+2][j*3+2] = 1; + } + } + } + + function dfs = [&](int i, int j) + { + if(i < 0 or j < 0 or i >= n*3 or j >= m*3 or visited[i][j] or mat[i][j] == 1) + return; + visited[i][j] = 1; + dfs(i-1, j); + dfs(i, j+1); + dfs(i+1, j); + dfs(i, j-1); + }; + + for(int i = 0; i < n*3; ++i) + { + for(int j = 0; j < m*3; ++j) + { + if(!visited[i][j] and mat[i][j] == 0) + { + ++cnt; + dfs(i, j); + } + } + } + + return cnt; + } +}; \ No newline at end of file diff --git a/0959-regions-cut-by-slashes/NOTES.md b/0959-regions-cut-by-slashes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0959-regions-cut-by-slashes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0959-regions-cut-by-slashes/README.md b/0959-regions-cut-by-slashes/README.md new file mode 100644 index 00000000..fc2c5d3b --- /dev/null +++ b/0959-regions-cut-by-slashes/README.md @@ -0,0 +1,35 @@ +

959. Regions Cut By Slashes

Medium


An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.

+ +

Given the grid grid represented as a string array, return the number of regions.

+ +

Note that backslash characters are escaped, so a '\' is represented as '\\'.

+ +

 

+

Example 1:

+ +
Input: grid = [" /","/ "]
+Output: 2
+
+ +

Example 2:

+ +
Input: grid = [" /","  "]
+Output: 1
+
+ +

Example 3:

+ +
Input: grid = ["/\\","\\/"]
+Output: 5
+Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 1 <= n <= 30
  • +
  • grid[i][j] is either '/', '\', or ' '.
  • +
+
\ No newline at end of file diff --git a/0974-subarray-sums-divisible-by-k/0974-subarray-sums-divisible-by-k.cpp b/0974-subarray-sums-divisible-by-k/0974-subarray-sums-divisible-by-k.cpp new file mode 100644 index 00000000..429752aa --- /dev/null +++ b/0974-subarray-sums-divisible-by-k/0974-subarray-sums-divisible-by-k.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int subarraysDivByK(vector& nums, int k) { + + int n = nums.size(), sum = 0; + + vector v(k,0); + + for(int i = 0; i < n; ++i) + { + sum += (nums[i]%k + k)%k; + ++v[sum%k]; + } + + int ans = v[0]; + + for(auto itr : v) + ans += (itr * (itr-1))/2; + + return ans; + + } +}; \ No newline at end of file diff --git a/0974-subarray-sums-divisible-by-k/NOTES.md b/0974-subarray-sums-divisible-by-k/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0974-subarray-sums-divisible-by-k/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0974-subarray-sums-divisible-by-k/README.md b/0974-subarray-sums-divisible-by-k/README.md new file mode 100644 index 00000000..af732be7 --- /dev/null +++ b/0974-subarray-sums-divisible-by-k/README.md @@ -0,0 +1,28 @@ +

974. Subarray Sums Divisible by K

Medium


Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.

+ +

A subarray is a contiguous part of an array.

+ +

 

+

Example 1:

+ +
Input: nums = [4,5,0,-2,-3,1], k = 5
+Output: 7
+Explanation: There are 7 subarrays with a sum divisible by k = 5:
+[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
+
+ +

Example 2:

+ +
Input: nums = [5], k = 9
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • 2 <= k <= 104
  • +
+
\ No newline at end of file diff --git a/0977-squares-of-a-sorted-array/0977-squares-of-a-sorted-array.cpp b/0977-squares-of-a-sorted-array/0977-squares-of-a-sorted-array.cpp new file mode 100644 index 00000000..b31ae1e2 --- /dev/null +++ b/0977-squares-of-a-sorted-array/0977-squares-of-a-sorted-array.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector sortedSquares(vector& nums) { + + int n = nums.size(); + vector squares(n); + + int i = 0, j = n-1, k = n-1; + + while(k >= 0) + { + if(abs(nums[i]) > abs(nums[j])) + { + squares[k] = nums[i] * nums[i]; + ++i; + } + else + { + squares[k] = nums[j] * nums[j]; + --j; + } + --k; + } + + return squares; + } +}; \ No newline at end of file diff --git a/0977-squares-of-a-sorted-array/NOTES.md b/0977-squares-of-a-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0977-squares-of-a-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0977-squares-of-a-sorted-array/README.md b/0977-squares-of-a-sorted-array/README.md new file mode 100644 index 00000000..9e0b7c42 --- /dev/null +++ b/0977-squares-of-a-sorted-array/README.md @@ -0,0 +1,28 @@ +

977. Squares of a Sorted Array

Easy


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

+ +

 

+

Example 1:

+ +
Input: nums = [-4,-1,0,3,10]
+Output: [0,1,9,16,100]
+Explanation: After squaring, the array becomes [16,1,0,9,100].
+After sorting, it becomes [0,1,9,16,100].
+
+ +

Example 2:

+ +
Input: nums = [-7,-3,2,3,11]
+Output: [4,9,9,49,121]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in non-decreasing order.
  • +
+ +

 

+Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
\ No newline at end of file diff --git a/0979-distribute-coins-in-binary-tree/0979-distribute-coins-in-binary-tree.cpp b/0979-distribute-coins-in-binary-tree/0979-distribute-coins-in-binary-tree.cpp new file mode 100644 index 00000000..a8764161 --- /dev/null +++ b/0979-distribute-coins-in-binary-tree/0979-distribute-coins-in-binary-tree.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int helper(TreeNode* root, int& moves) + { + if(!root) + return 0; + + int left = helper(root->left, moves); + int right = helper(root->right, moves); + + moves += (abs(left) + abs(right)); + + return (left + right + root->val - 1); + } + + int distributeCoins(TreeNode* root) { + + int moves = 0; + + helper(root, moves); + + return moves; + + } +}; \ No newline at end of file diff --git a/0979-distribute-coins-in-binary-tree/README.md b/0979-distribute-coins-in-binary-tree/README.md new file mode 100644 index 00000000..e7b0415a --- /dev/null +++ b/0979-distribute-coins-in-binary-tree/README.md @@ -0,0 +1,31 @@ +

979. Distribute Coins in Binary Tree

Medium


You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.

+ +

In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.

+ +

Return the minimum number of moves required to make every node have exactly one coin.

+ +

 

+

Example 1:

+ +
Input: root = [3,0,0]
+Output: 2
+Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
+
+ +

Example 2:

+ +
Input: root = [0,3,0]
+Output: 3
+Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is n.
  • +
  • 1 <= n <= 100
  • +
  • 0 <= Node.val <= n
  • +
  • The sum of all Node.val is n.
  • +
+
\ No newline at end of file diff --git a/0980-unique-paths-iii/0980-unique-paths-iii.cpp b/0980-unique-paths-iii/0980-unique-paths-iii.cpp new file mode 100644 index 00000000..15919935 --- /dev/null +++ b/0980-unique-paths-iii/0980-unique-paths-iii.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int res = 0, empty = 1; + void dfs(vector>& grid, int x, int y, int count) { + if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == -1) return; + + if (grid[x][y] == 2) { + if(empty == count) res++; + return; + } + + grid[x][y] = -1; + + dfs(grid, x+1, y, count+1); + dfs(grid, x-1, y, count+1); + dfs(grid, x, y+1, count+1); + dfs(grid, x, y-1, count+1); + + grid[x][y] = 0; + + } + + int uniquePathsIII(vector>& grid) { + int start_x, start_y; + for (int i = 0; i < grid.size(); i++) { + for (int j = 0; j < grid[0].size(); j++) { + if (grid[i][j] == 1) start_x = i, start_y = j; + else if (grid[i][j] == 0) empty++; + } + } + + dfs(grid, start_x, start_y, 0); + return res; + } +}; \ No newline at end of file diff --git a/0980-unique-paths-iii/NOTES.md b/0980-unique-paths-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0980-unique-paths-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0980-unique-paths-iii/README.md b/0980-unique-paths-iii/README.md new file mode 100644 index 00000000..b89c7c9b --- /dev/null +++ b/0980-unique-paths-iii/README.md @@ -0,0 +1,52 @@ +

980. Unique Paths III

Hard


You are given an m x n integer array grid where grid[i][j] could be:

+ +
    +
  • 1 representing the starting square. There is exactly one starting square.
  • +
  • 2 representing the ending square. There is exactly one ending square.
  • +
  • 0 representing empty squares we can walk over.
  • +
  • -1 representing obstacles that we cannot walk over.
  • +
+ +

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
+Output: 2
+Explanation: We have the following two paths: 
+1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
+2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
+
+ +

Example 2:

+ +
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
+Output: 4
+Explanation: We have the following four paths: 
+1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
+2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
+3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
+4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
+
+ +

Example 3:

+ +
Input: grid = [[0,1],[2,0]]
+Output: 0
+Explanation: There is no path that walks over every empty square exactly once.
+Note that the starting and ending square can be anywhere in the grid.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 20
  • +
  • 1 <= m * n <= 20
  • +
  • -1 <= grid[i][j] <= 2
  • +
  • There is exactly one starting cell and one ending cell.
  • +
+
\ No newline at end of file diff --git a/0987-vertical-order-traversal-of-a-binary-tree/0987-vertical-order-traversal-of-a-binary-tree.cpp b/0987-vertical-order-traversal-of-a-binary-tree/0987-vertical-order-traversal-of-a-binary-tree.cpp new file mode 100644 index 00000000..2fa6c38d --- /dev/null +++ b/0987-vertical-order-traversal-of-a-binary-tree/0987-vertical-order-traversal-of-a-binary-tree.cpp @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + map>> mp; + + void helper(TreeNode* root, int id, int level) + { + if(root) + { + mp[id][level].insert(root->val); + helper(root->left, id-1, level + 1); + helper(root->right, id+1, level + 1); + } + } + + vector> verticalTraversal(TreeNode* root) { + + int id = 0; + helper(root, id, 0); + + vector> ans; + + for(auto&[f, s] : mp) + { + vector col; + for(auto& ms : s) + col.insert(col.end(),ms.second.begin(),ms.second.end()); + ans.push_back(col); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0987-vertical-order-traversal-of-a-binary-tree/README.md b/0987-vertical-order-traversal-of-a-binary-tree/README.md new file mode 100644 index 00000000..6ca03394 --- /dev/null +++ b/0987-vertical-order-traversal-of-a-binary-tree/README.md @@ -0,0 +1,50 @@ +

987. Vertical Order Traversal of a Binary Tree

Hard


Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

+ +

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

+ +

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

+ +

Return the vertical order traversal of the binary tree.

+ +

 

+

Example 1:

+ +
Input: root = [3,9,20,null,null,15,7]
+Output: [[9],[3,15],[20],[7]]
+Explanation:
+Column -1: Only node 9 is in this column.
+Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
+Column 1: Only node 20 is in this column.
+Column 2: Only node 7 is in this column.
+ +

Example 2:

+ +
Input: root = [1,2,3,4,5,6,7]
+Output: [[4],[2],[1,5,6],[3],[7]]
+Explanation:
+Column -2: Only node 4 is in this column.
+Column -1: Only node 2 is in this column.
+Column 0: Nodes 1, 5, and 6 are in this column.
+          1 is at the top, so it comes first.
+          5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
+Column 1: Only node 3 is in this column.
+Column 2: Only node 7 is in this column.
+
+ +

Example 3:

+ +
Input: root = [1,2,3,4,6,5,7]
+Output: [[4],[2],[1,5,6],[3],[7]]
+Explanation:
+This case is the exact same as example 2, but with nodes 5 and 6 swapped.
+Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/0988-smallest-string-starting-from-leaf/0988-smallest-string-starting-from-leaf.cpp b/0988-smallest-string-starting-from-leaf/0988-smallest-string-starting-from-leaf.cpp new file mode 100644 index 00000000..c71963a8 --- /dev/null +++ b/0988-smallest-string-starting-from-leaf/0988-smallest-string-starting-from-leaf.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + string ans = "~"; + + void helper(TreeNode* root, string curr) + { + if(!root) + return; + + if(!root->left and !root->right) + ans = min(ans, char(root->val + 'a') + curr); + + helper(root->left, char(root->val + 'a') + curr); + helper(root->right, char(root->val + 'a') + curr); + } + + string smallestFromLeaf(TreeNode* root) { + + helper(root, ""); + return ans; + + } +}; \ No newline at end of file diff --git a/0988-smallest-string-starting-from-leaf/README.md b/0988-smallest-string-starting-from-leaf/README.md new file mode 100644 index 00000000..2ba3cfed --- /dev/null +++ b/0988-smallest-string-starting-from-leaf/README.md @@ -0,0 +1,39 @@ +

988. Smallest String Starting From Leaf

Medium


You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.

+ +

Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

+ +

As a reminder, any shorter prefix of a string is lexicographically smaller.

+ +
    +
  • For example, "ab" is lexicographically smaller than "aba".
  • +
+ +

A leaf of a node is a node that has no children.

+ +

 

+

Example 1:

+ +
Input: root = [0,1,2,3,4,3,4]
+Output: "dba"
+
+ +

Example 2:

+ +
Input: root = [25,1,3,1,3,0,2]
+Output: "adz"
+
+ +

Example 3:

+ +
Input: root = [2,2,1,null,1,0,null,0]
+Output: "abc"
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 8500].
  • +
  • 0 <= Node.val <= 25
  • +
+
\ No newline at end of file diff --git a/0989-add-to-array-form-of-integer/0989-add-to-array-form-of-integer.cpp b/0989-add-to-array-form-of-integer/0989-add-to-array-form-of-integer.cpp new file mode 100644 index 00000000..85978ecf --- /dev/null +++ b/0989-add-to-array-form-of-integer/0989-add-to-array-form-of-integer.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector addToArrayForm(vector& num, int k) { + + int n = num.size(); + + for(int i = n-1; i >= 0; --i) + { + num[i] += k; + k = num[i] / 10; + num[i] = num[i] % 10; + } + + while(k > 0) + { + num.insert(num.begin(),k%10); + k /= 10; + } + + return num; + } +}; \ No newline at end of file diff --git a/0989-add-to-array-form-of-integer/NOTES.md b/0989-add-to-array-form-of-integer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0989-add-to-array-form-of-integer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0989-add-to-array-form-of-integer/README.md b/0989-add-to-array-form-of-integer/README.md new file mode 100644 index 00000000..348e12a9 --- /dev/null +++ b/0989-add-to-array-form-of-integer/README.md @@ -0,0 +1,40 @@ +

989. Add to Array-Form of Integer

Easy


The array-form of an integer num is an array representing its digits in left to right order.

+ +
    +
  • For example, for num = 1321, the array form is [1,3,2,1].
  • +
+ +

Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

+ +

 

+

Example 1:

+ +
Input: num = [1,2,0,0], k = 34
+Output: [1,2,3,4]
+Explanation: 1200 + 34 = 1234
+
+ +

Example 2:

+ +
Input: num = [2,7,4], k = 181
+Output: [4,5,5]
+Explanation: 274 + 181 = 455
+
+ +

Example 3:

+ +
Input: num = [2,1,5], k = 806
+Output: [1,0,2,1]
+Explanation: 215 + 806 = 1021
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num.length <= 104
  • +
  • 0 <= num[i] <= 9
  • +
  • num does not contain any leading zeros except for the zero itself.
  • +
  • 1 <= k <= 104
  • +
+
\ No newline at end of file diff --git a/0992-subarrays-with-k-different-integers/0992-subarrays-with-k-different-integers.cpp b/0992-subarrays-with-k-different-integers/0992-subarrays-with-k-different-integers.cpp new file mode 100644 index 00000000..b0579a54 --- /dev/null +++ b/0992-subarrays-with-k-different-integers/0992-subarrays-with-k-different-integers.cpp @@ -0,0 +1,38 @@ +class Solution { + +private: + int subarrayWithAtmost(vector& nums, int k) + { + int i = 0, j = 0, n = nums.size(); + + unordered_map mp; + + int ans = 0; + + while(j < n) + { + ++mp[nums[j]]; + + while(mp.size() > k) + { + --mp[nums[i]]; + if(mp[nums[i]] == 0) + mp.erase(nums[i]); + ++i; + } + + ans += (j - i + 1); + ++j; + } + + return ans; + } + +public: + + int subarraysWithKDistinct(vector& nums, int k) { + + return subarrayWithAtmost(nums, k) - subarrayWithAtmost(nums, k-1); + + } +}; \ No newline at end of file diff --git a/0992-subarrays-with-k-different-integers/NOTES.md b/0992-subarrays-with-k-different-integers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0992-subarrays-with-k-different-integers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0992-subarrays-with-k-different-integers/README.md b/0992-subarrays-with-k-different-integers/README.md new file mode 100644 index 00000000..cde878b8 --- /dev/null +++ b/0992-subarrays-with-k-different-integers/README.md @@ -0,0 +1,33 @@ +

992. Subarrays with K Different Integers

Hard


Given an integer array nums and an integer k, return the number of good subarrays of nums.

+ +

A good array is an array where the number of different integers in that array is exactly k.

+ +
    +
  • For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.
  • +
+ +

A subarray is a contiguous part of an array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1,2,3], k = 2
+Output: 7
+Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
+
+ +

Example 2:

+ +
Input: nums = [1,2,1,3,4], k = 3
+Output: 3
+Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • 1 <= nums[i], k <= nums.length
  • +
+
\ No newline at end of file diff --git a/0994-rotting-oranges/0994-rotting-oranges.cpp b/0994-rotting-oranges/0994-rotting-oranges.cpp new file mode 100644 index 00000000..20427f73 --- /dev/null +++ b/0994-rotting-oranges/0994-rotting-oranges.cpp @@ -0,0 +1,76 @@ +class Solution { +public: + + bool isValid (int x, int y, vector>& grid, vector>& visited) + { + int n = grid.size(); + int m = grid[0].size(); + + return(x >= 0 and y >= 0 and x < n and y < m and !visited[x][y] and grid[x][y] == 1); + } + + int orangesRotting(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + queue, int>> q; + + vector> visited(n,vector(m, false)); + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1, 0}; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 2) + { + q.push({{i,j},0}); + visited[i][j] = true; + } + } + } + + int step = 0, ans = 0; + + while(!q.empty()) + { + auto curr = q.front(); + q.pop(); + + int x = curr.first.first; + int y = curr.first.second; + step = curr.second; + + ans = max(ans, step); + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(isValid(newx, newy, grid, visited)) + { + visited[newx][newy] = true; + q.push({{newx,newy},step+1}); + grid[newx][newy] = 2; + } + } + + } + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1) + return -1; + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0994-rotting-oranges/NOTES.md b/0994-rotting-oranges/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0994-rotting-oranges/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0994-rotting-oranges/README.md b/0994-rotting-oranges/README.md new file mode 100644 index 00000000..1eb3cfc3 --- /dev/null +++ b/0994-rotting-oranges/README.md @@ -0,0 +1,43 @@ +

994. Rotting Oranges

Medium


You are given an m x n grid where each cell can have one of three values:

+ +
    +
  • 0 representing an empty cell,
  • +
  • 1 representing a fresh orange, or
  • +
  • 2 representing a rotten orange.
  • +
+ +

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

+ +

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

+ +

 

+

Example 1:

+ +
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
+Output: 4
+
+ +

Example 2:

+ +
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
+Output: -1
+Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
+
+ +

Example 3:

+ +
Input: grid = [[0,2]]
+Output: 0
+Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • grid[i][j] is 0, 1, or 2.
  • +
+
\ No newline at end of file diff --git a/0995-minimum-number-of-k-consecutive-bit-flips/0995-minimum-number-of-k-consecutive-bit-flips.cpp b/0995-minimum-number-of-k-consecutive-bit-flips/0995-minimum-number-of-k-consecutive-bit-flips.cpp new file mode 100644 index 00000000..c2bc0ee2 --- /dev/null +++ b/0995-minimum-number-of-k-consecutive-bit-flips/0995-minimum-number-of-k-consecutive-bit-flips.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int minKBitFlips(vector& nums, int k) { + + int n = nums.size(), ans = 0; + + vector> pref(n, {0, 0}); + + bool flag = true; + + for(int i = 0; i < n; ++i) + { + pref[i].second = (i-1 >= 0 ? pref[i-1].second : 0); + + if(i - k >= 0) + { + if(pref[i-k].first) + --pref[i].second; + } + + int moves = pref[i].second; + + int op = (nums[i] % 2 == 0 ? (moves % 2 == 0 ? 1 : 0) : (moves % 2 == 0 ? 0 : 1)); + + if(op){ + if(i <= n-k) + { + pref[i].first = 1; + ++ans; + } + else + flag = false; + } + + pref[i].second += op; + } + + return (flag ? ans : -1); + } +}; \ No newline at end of file diff --git a/0995-minimum-number-of-k-consecutive-bit-flips/NOTES.md b/0995-minimum-number-of-k-consecutive-bit-flips/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0995-minimum-number-of-k-consecutive-bit-flips/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0995-minimum-number-of-k-consecutive-bit-flips/README.md b/0995-minimum-number-of-k-consecutive-bit-flips/README.md new file mode 100644 index 00000000..4a559ed8 --- /dev/null +++ b/0995-minimum-number-of-k-consecutive-bit-flips/README.md @@ -0,0 +1,41 @@ +

995. Minimum Number of K Consecutive Bit Flips

Hard


You are given a binary array nums and an integer k.

+ +

A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.

+ +

Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.

+ +

A subarray is a contiguous part of an array.

+ +

 

+

Example 1:

+ +
Input: nums = [0,1,0], k = 1
+Output: 2
+Explanation: Flip nums[0], then flip nums[2].
+
+ +

Example 2:

+ +
Input: nums = [1,1,0], k = 2
+Output: -1
+Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].
+
+ +

Example 3:

+ +
Input: nums = [0,0,0,1,0,1,1,0], k = 3
+Output: 3
+Explanation: 
+Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]
+Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]
+Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/0997-find-the-town-judge/0997-find-the-town-judge.cpp b/0997-find-the-town-judge/0997-find-the-town-judge.cpp new file mode 100644 index 00000000..6b312854 --- /dev/null +++ b/0997-find-the-town-judge/0997-find-the-town-judge.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int findJudge(int n, vector>& trust) { + + if(n == 1 and trust.size() == 0) + return 1; + + vector outDegree(n+1,0), inDegree(n+1,0); + + for(auto itr : trust) + { + ++outDegree[itr[0]]; + ++inDegree[itr[1]]; + } + + for(int i = 1; i<= n; ++i) + { + if(outDegree[i] == 0 and inDegree[i] == n-1) + return i; + } + + return -1; + + } +}; \ No newline at end of file diff --git a/0997-find-the-town-judge/NOTES.md b/0997-find-the-town-judge/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0997-find-the-town-judge/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0997-find-the-town-judge/README.md b/0997-find-the-town-judge/README.md new file mode 100644 index 00000000..2927b118 --- /dev/null +++ b/0997-find-the-town-judge/README.md @@ -0,0 +1,45 @@ +

997. Find the Town Judge

Easy


In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

+ +

If the town judge exists, then:

+ +
    +
  1. The town judge trusts nobody.
  2. +
  3. Everybody (except for the town judge) trusts the town judge.
  4. +
  5. There is exactly one person that satisfies properties 1 and 2.
  6. +
+ +

You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.

+ +

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

+ +

 

+

Example 1:

+ +
Input: n = 2, trust = [[1,2]]
+Output: 2
+
+ +

Example 2:

+ +
Input: n = 3, trust = [[1,3],[2,3]]
+Output: 3
+
+ +

Example 3:

+ +
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
  • 0 <= trust.length <= 104
  • +
  • trust[i].length == 2
  • +
  • All the pairs of trust are unique.
  • +
  • ai != bi
  • +
  • 1 <= ai, bi <= n
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp new file mode 100644 index 00000000..d401154d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp @@ -0,0 +1,55 @@ +#define ll long long int + +class Solution { +public: + int maxFrequency(vector& nums, int k) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + vector pref(n+1, 0); + + for(int i = 1; i <= n; ++i) + { + pref[i] = (pref[i-1] + nums[i-1]); + } + + function calculate = [&](int targetIdx) + { + int ans = 0, val = nums[targetIdx]; + + int low = 0, high = targetIdx; + + while(low <= high) + { + int mid = (low + high) >> 1; + + int cnt = targetIdx - mid + 1; + + ll windowSum = val * 1LL * cnt; + + ll currSum = pref[targetIdx+1] - pref[mid]; + + if((windowSum - currSum) <= k) + { + ans = max(ans, cnt); + high = mid-1; + } + else + low = mid+1; + } + + return ans; + }; + + int res = 0; + + for(int i = 0; i < n; ++i) + { + res = max(res, calculate(i)); + } + + return res; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-hidden-flex-wrap-wrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondiv-styletransform-rotate180deg-svg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar.cpp new file mode 100644 index 00000000..2acce397 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int kthGrammar(int n, int k) { + + if(n == 1 and k == 1) + return 0; + + int mid = pow(2, n-1) / 2; + + if(k <= mid) + return kthGrammar(n-1, k); + else + return !kthGrammar(n-1, k-mid); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div779-k-th-symbol-in-grammar/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix.cpp new file mode 100644 index 00000000..f9a788d0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + + int n = mat.size(); + int m = mat[0].size(); + + vector ans; + + auto binarySearch = [&](vector& arr) + { + int low = 0, high = m-1; + + while(low <= high) + { + int mid = (low + high) >> 1; + + if(arr[mid] == 0) + high = mid-1; + else + low = mid+1; + } + return low; + }; + + priority_queue > pq; + + for(int i = 0; i < n; ++i) + { + int currRowOnesCount = binarySearch(mat[i]); + + pq.push({currRowOnesCount, i}); + + if(pq.size() > k) + pq.pop(); + } + + while(k--) + { + int kthStrongestIdx = pq.top().second; + pq.pop(); + + ans.push_back(kthStrongestIdx); + } + + reverse(ans.begin(), ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/README.md new file mode 100644 index 00000000..ad6781fe --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1337-the-k-weakest-rows-in-a-matrix/README.md @@ -0,0 +1,61 @@ +

Amazon
1
1337. The K Weakest Rows in a Matrix

Easy


You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

+ +

A row i is weaker than a row j if one of the following is true:

+ +
    +
  • The number of soldiers in row i is less than the number of soldiers in row j.
  • +
  • Both rows have the same number of soldiers and i < j.
  • +
+ +

Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

+ +

 

+

Example 1:

+ +
Input: mat = 
+[[1,1,0,0,0],
+ [1,1,1,1,0],
+ [1,0,0,0,0],
+ [1,1,0,0,0],
+ [1,1,1,1,1]], 
+k = 3
+Output: [2,0,3]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 2 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 2 
+- Row 4: 5 
+The rows ordered from weakest to strongest are [2,0,3,1,4].
+
+ +

Example 2:

+ +
Input: mat = 
+[[1,0,0,0],
+ [1,1,1,1],
+ [1,0,0,0],
+ [1,0,0,0]], 
+k = 2
+Output: [0,2]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 1 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 1 
+The rows ordered from weakest to strongest are [0,2,3,1].
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 2 <= n, m <= 100
  • +
  • 1 <= k <= m
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap.cpp new file mode 100644 index 00000000..81cf155a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap.cpp @@ -0,0 +1,29 @@ +class MyHashMap { +public: + + int arr[1000001]; + + MyHashMap() { + fill(arr, arr+1000001, -1); + } + + void put(int key, int value) { + arr[key] = value; + } + + int get(int key) { + return arr[key]; + } + + void remove(int key) { + arr[key] = -1; + } +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap* obj = new MyHashMap(); + * obj->put(key,value); + * int param_2 = obj->get(key); + * obj->remove(key); + */ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/README.md new file mode 100644 index 00000000..afd9c7ec --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divlinkedin-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div706-design-hashmap/README.md @@ -0,0 +1,40 @@ +

Amazon
10
Microsoft
6
LinkedIn
5
Oracle
4
Salesforce
3
Apple
3
Goldman Sachs
3
Walmart Global Tech
3
706. Design HashMap

Easy


Design a HashMap without using any built-in hash table libraries.

+ +

Implement the MyHashMap class:

+ +
    +
  • MyHashMap() initializes the object with an empty map.
  • +
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
  • +
  • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • +
  • void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
  • +
+ +

 

+

Example 1:

+ +
Input
+["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
+[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
+Output
+[null, null, null, 1, -1, null, 1, null, -1]
+
+Explanation
+MyHashMap myHashMap = new MyHashMap();
+myHashMap.put(1, 1); // The map is now [[1,1]]
+myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
+myHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]
+myHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
+myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
+myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
+myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
+myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= key, value <= 106
  • +
  • At most 104 calls will be made to put, get, and remove.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number.cpp new file mode 100644 index 00000000..981afefa --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + + int n = nums.size(); + + for(int i = 0; i < n; ++i) + { + int idx = abs(nums[i]); + + if(nums[idx] < 0) + return idx; + + nums[idx] = -nums[idx]; + } + + return n; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/README.md new file mode 100644 index 00000000..2935c464 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence16-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence11-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divqualcomm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div287-find-the-duplicate-number/README.md @@ -0,0 +1,37 @@ +

Amazon
16
Microsoft
11
Facebook
4
Uber
3
Apple
3
Google
2
Qualcomm
2
287. Find the Duplicate Number

Medium


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

You must solve the problem without modifying the array nums and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,2,2]
+Output: 2
+
+ +

Example 2:

+ +
Input: nums = [3,1,3,4,2]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem in linear runtime complexity?
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string.cpp new file mode 100644 index 00000000..776c6783 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + + int n = nums.size(); + + for(int i = 0; i < n; ++i) + { + if(nums[0][i] = nums[i][i] == '0' ? '1' : '0'); + } + + return nums[0]; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1980-find-unique-binary-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors.cpp new file mode 100644 index 00000000..d2d96ba0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + + const int mod = 1e9+7; + + int numFactoredBinaryTrees(vector& arr) { + + int n = arr.size(); + + unordered_map mp; + + for(auto& itr : arr) + ++mp[itr]; + + sort(arr.begin(), arr.end()); + + int ans = 0; + + for(int i = 1; i < n; ++i) + { + for(int j = 0; j < i; ++j) + { + if(arr[i] % arr[j] == 0) + { + long long count = (mp[arr[j]] * 1LL * mp[arr[i]/arr[j]]) % mod; + mp[arr[i]] = (mp[arr[i]] % mod + count)% mod; + } + } + } + + for(auto& itr : mp) + { + ans = (ans + itr.second) % mod; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/README.md new file mode 100644 index 00000000..7292e9fd --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div823-binary-trees-with-factors/README.md @@ -0,0 +1,28 @@ +

Amazon
2
823. Binary Trees With Factors

Medium


Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.

+ +

We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.

+ +

Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: arr = [2,4]
+Output: 3
+Explanation: We can make these trees: [2], [4], [4, 2, 2]
+ +

Example 2:

+ +
Input: arr = [2,4,5,10]
+Output: 7
+Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • 2 <= arr[i] <= 109
  • +
  • All the values of arr are unique.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain.cpp new file mode 100644 index 00000000..0eacc27d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findLongestChain(vector>& pairs) { + + int n = pairs.size(); + + sort(pairs.begin(), pairs.end(),[&](const auto& a, const auto& b){ + return a[1] < b[1]; + }); + + int count = 1; + + int curr = pairs[0][1]; + + for(int i = 1; i < n; ++i) + { + if(pairs[i][0] > curr) + { + curr = pairs[i][1]; + ++count; + } + } + + return count; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/README.md new file mode 100644 index 00000000..5270bb1c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divflipkart-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div646-maximum-length-of-pair-chain/README.md @@ -0,0 +1,32 @@ +

Amazon
2
Flipkart
2
646. Maximum Length of Pair Chain

Medium


You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

+ +

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

+ +

Return the length longest chain which can be formed.

+ +

You do not need to use up all the given intervals. You can select pairs in any order.

+ +

 

+

Example 1:

+ +
Input: pairs = [[1,2],[2,3],[3,4]]
+Output: 2
+Explanation: The longest chain is [1,2] -> [3,4].
+
+ +

Example 2:

+ +
Input: pairs = [[1,2],[7,8],[4,5]]
+Output: 3
+Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
+
+ +

 

+

Constraints:

+ +
    +
  • n == pairs.length
  • +
  • 1 <= n <= 1000
  • +
  • -1000 <= lefti < righti <= 1000
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/README.md new file mode 100644 index 00000000..158d4a8f --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence32-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence8-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcitadel-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbytedance-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvmware-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdoordash-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divde-shaw-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divquora-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div239-sliding-window-maximum/README.md @@ -0,0 +1,35 @@ +

Amazon
32
Google
8
Microsoft
6
Salesforce
6
Uber
5
Facebook
5
Adobe
4
Citadel
4
ByteDance
4
Apple
3
Twilio
3
tiktok
3
Bloomberg
2
VMware
2
Booking.com
2
DoorDash
2
DE Shaw
2
Quora
2
239. Sliding Window Maximum

Hard


You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

+ +

Return the max sliding window.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
+Output: [3,3,5,5,6,7]
+Explanation: 
+Window position                Max
+---------------               -----
+[1  3  -1] -3  5  3  6  7       3
+ 1 [3  -1  -3] 5  3  6  7       3
+ 1  3 [-1  -3  5] 3  6  7       5
+ 1  3  -1 [-3  5  3] 6  7       5
+ 1  3  -1  -3 [5  3  6] 7       6
+ 1  3  -1  -3  5 [3  6  7]      7
+
+ +

Example 2:

+ +
Input: nums = [1], k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
  • 1 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring.cpp new file mode 100644 index 00000000..b9aeff39 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + string longestPalindrome(string s) { + + int n = s.size(); + + vector> dp(n+1, vector(n+1, 0)); + + int maxLength = 0; + + string ans; + + for(int diff = 0; diff < n; ++ diff) + { + for(int i = 0, j = diff; i < n and j < n; ++i, ++j) + { + if(i == j) + { + dp[i][j] = 1; + } + else if(diff == 1 and s[i] == s[j]) + { + dp[i][j] = 2; + } + else if(diff > 1 and s[i] == s[j] and dp[i+1][j-1]) + { + dp[i][j] = dp[i+1][j-1] + 2; + } + + if(dp[i][j] > maxLength) + { + maxLength = dp[i][j]; + ans = s.substr(i, j-i+1); + } + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/README.md new file mode 100644 index 00000000..2a2b8010 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence35-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence18-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence7-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence5-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div5-longest-palindromic-substring/README.md @@ -0,0 +1,24 @@ +

Amazon
35
Microsoft
18
Google
12
Adobe
12
Facebook
7
Apple
7
Oracle
7
Bloomberg
6
Goldman Sachs
5
5. Longest Palindromic Substring

Medium


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

+ +

 

+

Example 1:

+ +
Input: s = "babad"
+Output: "bab"
+Explanation: "aba" is also a valid answer.
+
+ +

Example 2:

+ +
Input: s = "cbbd"
+Output: "bb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consist of only digits and English letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern.cpp new file mode 100644 index 00000000..ead08dec --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + bool find132pattern(vector& nums) { + + int n = nums.size(); + + vector prefMin(n); + + prefMin[0] = nums[0]; + + for(int i = 1; i < n; ++i) + prefMin[i] = min(nums[i], prefMin[i-1]); + + stack st; + + for(int i = n-1; i >= 0; --i) + { + if(nums[i] > prefMin[i]) + { + while(!st.empty() and st.top() <= prefMin[i]) + st.pop(); + if(!st.empty() and nums[i] > st.top()) + return true; + st.push(nums[i]); + } + } + + return false; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/README.md new file mode 100644 index 00000000..c0815542 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div456-132-pattern/README.md @@ -0,0 +1,35 @@ +

Amazon
4
456. 132 Pattern

Medium


Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

+ +

Return true if there is a 132 pattern in nums, otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: false
+Explanation: There is no 132 pattern in the sequence.
+
+ +

Example 2:

+ +
Input: nums = [3,1,4,2]
+Output: true
+Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
+
+ +

Example 3:

+ +
Input: nums = [-1,3,2,0]
+Output: true
+Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 2 * 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence.cpp new file mode 100644 index 00000000..d31a4cb6 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool isSubsequence(string s, string t) { + + int k = 0; + + for(int i = 0; i < t.size() and k < s.size(); ++i) + { + if(t[i] == s[k]) + ++k; + } + + return k == s.size(); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/README.md new file mode 100644 index 00000000..ff4571c0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div392-is-subsequence/README.md @@ -0,0 +1,23 @@ +

Amazon
4
Google
3
Yandex
3
Adobe
2
392. Is Subsequence

Easy


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

+ +

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

+ +

 

+

Example 1:

+
Input: s = "abc", t = "ahbgdc"
+Output: true
+

Example 2:

+
Input: s = "axc", t = "ahbgdc"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 100
  • +
  • 0 <= t.length <= 104
  • +
  • s and t consist only of lowercase English letters.
  • +
+ +

 

+Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii.cpp new file mode 100644 index 00000000..cb2c75f3 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + vector majorityElement(vector& nums) { + + int n = nums.size(); + + int count1 = 0, count2 = 0; + + int num1 = INT_MAX, num2 = INT_MAX; + + for(auto& itr : nums) + { + if(itr == num1) + { + ++count1; + } + else if(itr == num2) + { + ++count2; + } + else if(count1 == 0) + { + count1 = 1; + num1 = itr; + } + else if(count2 == 0) + { + count2 = 1; + num2 = itr; + } + else + { + --count1, --count2; + } + } + + count1 = count2 = 0; + + for(auto& itr : nums) + { + if(itr == num1) + ++count1; + else if(itr == num2) + ++count2; + } + + vector ans; + + if(count1 > n/3) + ans.push_back(num1); + if(count2 > n/3) + ans.push_back(num2); + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div229-majority-element-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs.cpp new file mode 100644 index 00000000..383cab45 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + + int n = cost.size(); + + vector dp(n+1, 0); + + for(int i = 2; i <= n; ++i) + { + int oneStep = cost[i-1] + dp[i-1]; + int twoStep = cost[i-2] + dp[i-2]; + dp[i] = min(oneStep, twoStep); + } + + return dp[n]; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/README.md new file mode 100644 index 00000000..5ca7f39b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div746-min-cost-climbing-stairs/README.md @@ -0,0 +1,38 @@ +

Amazon
5
Adobe
4
Bloomberg
2
746. Min Cost Climbing Stairs

Easy


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

+ +

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

+ +

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

+ +

 

+

Example 1:

+ +
Input: cost = [10,15,20]
+Output: 15
+Explanation: You will start at index 1.
+- Pay 15 and climb two steps to reach the top.
+The total cost is 15.
+
+ +

Example 2:

+ +
Input: cost = [1,100,1,1,1,100,1,1,100,1]
+Output: 6
+Explanation: You will start at index 0.
+- Pay 1 and climb two steps to reach index 2.
+- Pay 1 and climb two steps to reach index 4.
+- Pay 1 and climb two steps to reach index 6.
+- Pay 1 and climb one step to reach index 7.
+- Pay 1 and climb two steps to reach index 9.
+- Pay 1 and climb one step to reach the top.
+The total cost is 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= cost.length <= 1000
  • +
  • 0 <= cost[i] <= 999
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent.cpp new file mode 100644 index 00000000..08c3a3b1 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + + int i = 0, j = 0; + int n = 0, m = 0; + + while(i < word1.size() and j < word2.size()) + { + if(word1[i][n] != word2[j][m]) + return false; + + ++n, ++m; + + if(n >= word1[i].size()) n = 0, ++i; + if(m >= word2[j].size()) m = 0, ++j; + } + + return (i == word1.size() and j == word2.size()); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/README.md new file mode 100644 index 00000000..3e4a16f2 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1662-check-if-two-string-arrays-are-equivalent/README.md @@ -0,0 +1,36 @@ +

Apple
2
Facebook
1
1662. Check If Two String Arrays are Equivalent

Easy


Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

+ +

A string is represented by an array if the array elements concatenated in order forms the string.

+ +

 

+

Example 1:

+ +
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
+Output: true
+Explanation:
+word1 represents string "ab" + "c" -> "abc"
+word2 represents string "a" + "bc" -> "abc"
+The strings are the same, so return true.
+ +

Example 2:

+ +
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
+Output: false
+
+ +

Example 3:

+ +
Input: word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word1.length, word2.length <= 103
  • +
  • 1 <= word1[i].length, word2[i].length <= 103
  • +
  • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
  • +
  • word1[i] and word2[i] consist of lowercase letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points.cpp new file mode 100644 index 00000000..a4e92859 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minTimeToVisitAllPoints(vector>& points) { + + int n = points.size(); + + int t = 0; + + for(int i = 1; i < n; ++i) + { + t += max(abs(points[i][1] - points[i-1][1]), abs(points[i][0] - points[i-1][0])); + } + + return t; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/README.md new file mode 100644 index 00000000..2fd5cedb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1266-minimum-time-visiting-all-points/README.md @@ -0,0 +1,43 @@ +

Apple
3
1266. Minimum Time Visiting All Points

Easy


On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.

+ +

You can move according to these rules:

+ +
    +
  • In 1 second, you can either: + +
      +
    • move vertically by one unit,
    • +
    • move horizontally by one unit, or
    • +
    • move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
    • +
    +
  • +
  • You have to visit the points in the same order as they appear in the array.
  • +
  • You are allowed to pass through points that appear later in the order, but these do not count as visits.
  • +
+ +

 

+

Example 1:

+ +
Input: points = [[1,1],[3,4],[-1,0]]
+Output: 7
+Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]   
+Time from [1,1] to [3,4] = 3 seconds 
+Time from [3,4] to [-1,0] = 4 seconds
+Total time = 7 seconds
+ +

Example 2:

+ +
Input: points = [[3,2],[-2,2]]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • points.length == n
  • +
  • 1 <= n <= 100
  • +
  • points[i].length == 2
  • +
  • -1000 <= points[i][0], points[i][1] <= 1000
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters.cpp new file mode 100644 index 00000000..9f335b1a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + string removeDuplicateLetters(string s) { + + int n = s.size(); + + vector freq(26, 0); + + vector visited(26, 0); + + string ans; + + for(int i = 0; i < n; ++i) + { + ++freq[s[i] - 'a']; + } + + for(int i = 0; i < n; ++i) + { + while(!ans.empty() and !visited[s[i] - 'a'] and s[i] < ans.back() and freq[ans.back()-'a']) + { + visited[ans.back() - 'a'] = false; + ans.pop_back(); + } + + if(!visited[s[i] - 'a']) + { + ans += s[i]; + visited[s[i] - 'a'] = 1; + } + + --freq[s[i] - 'a']; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/README.md new file mode 100644 index 00000000..86a62d23 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsalesforce-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div316-remove-duplicate-letters/README.md @@ -0,0 +1,26 @@ +

Apple
4
Facebook
2
Amazon
2
Salesforce
2
316. Remove Duplicate Letters

Medium


Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

+ +

 

+

Example 1:

+ +
Input: s = "bcabc"
+Output: "abc"
+
+ +

Example 2:

+ +
Input: s = "cbacdcbc"
+Output: "acdb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+ +

 

+

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer.cpp new file mode 100644 index 00000000..9fdae1a4 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + + const int mod = 1e9+7; + + vector dx = {-2, -2, -1 , -1, +2, +2, +1, +1}; + vector dy = {-1, +1, -2, +2, -1, +1, -2, +2}; + + int helper(int i, int j, int n, vector>>& dp) + { + if(n == 1) + return 1; + + if(dp[i][j][n] != -1) + return dp[i][j][n]; + + int count = 0; + + for(int k = 0; k < 8; ++k) + { + int x = dx[k] + i; + int y = dy[k] + j; + + if(x >= 0 and x < 4 and y >= 0 and y < 3) + { + if(x == 3 and (y == 0 or y == 2)) + continue; + count = (count + helper(x, y, n-1, dp)) % mod; + } + } + + return dp[i][j][n] = count; + } + + int knightDialer(int n) { + + int count = 0; + + vector>> dp(4, vector>(3, vector(n+1,-1))); + + for(int i = 0; i < 4; ++i) + { + for(int j = 0; j < 3; ++j) + { + if(i == 3 and (j == 0 or j == 2)) + continue; + count = (count + helper(i,j,n,dp)) % mod; + } + } + + return count; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence10-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwilio-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divsnapchat-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div935-knight-dialer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits.cpp new file mode 100644 index 00000000..dd0d10a6 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int hammingWeight(uint32_t n) { + + int cnt = 0; + + while(n > 0) + { + if(n & 1) + ++cnt; + n >>= 1; + } + + return cnt; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbox-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcisco-divdiv-classcompanytagscontainer-tagoccurence4-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divoracle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div191-number-of-1-bits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs.cpp new file mode 100644 index 00000000..b0bb50ab --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divcapital-one-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1743-restore-the-array-from-adjacent-pairs.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + + unordered_map> adj; + unordered_map mp; + + int sv = -1; + + for(auto& itr : adjacentPairs) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + + ++mp[itr[0]]; + ++mp[itr[1]]; + } + + for(auto& [f, s] : mp) + { + if(s == 1) + sv = f; + } + + vector ans; + + unordered_set visited; + + function dfs = [&](int sv) + { + ans.push_back(sv); + visited.insert(sv); + + for(auto& itr : adj[sv]) + { + if(!visited.count(itr)) + dfs(itr); + } + }; + + cout<
Capital One
2
1743. Restore the Array From Adjacent Pairs

Medium


There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.

+ +

You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.

+ +

It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.

+ +

Return the original array nums. If there are multiple solutions, return any of them.

+ +

 

+

Example 1:

+ +
Input: adjacentPairs = [[2,1],[3,4],[3,2]]
+Output: [1,2,3,4]
+Explanation: This array has all its adjacent pairs in adjacentPairs.
+Notice that adjacentPairs[i] may not be in left-to-right order.
+
+ +

Example 2:

+ +
Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
+Output: [-2,4,1,-3]
+Explanation: There can be negative numbers.
+Another solution is [-3,1,4,-2], which would also be accepted.
+
+ +

Example 3:

+ +
Input: adjacentPairs = [[100000,-100000]]
+Output: [100000,-100000]
+
+ +

 

+

Constraints:

+ +
    +
  • nums.length == n
  • +
  • adjacentPairs.length == n - 1
  • +
  • adjacentPairs[i].length == 2
  • +
  • 2 <= n <= 105
  • +
  • -105 <= nums[i], ui, vi <= 105
  • +
  • There exists some nums that has adjacentPairs as its pairs.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game.cpp new file mode 100644 index 00000000..3385d741 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int getWinner(vector& arr, int k) { + + int n = arr.size(); + + int maxi = *max_element(arr.begin(), arr.end()); + + if(k >= arr.size()) return maxi; + + int cnt = 0; + + int winner = arr[0]; + + for(int i = 1; i < n; ++i) + { + if(winner > arr[i]) + { + ++cnt; + } + else + { + winner = arr[i]; + cnt = 1; + } + + if(cnt == k or winner == maxi) + return winner; + } + + return winner; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/README.md new file mode 100644 index 00000000..669d5500 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdirecti-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1535-find-the-winner-of-an-array-game/README.md @@ -0,0 +1,39 @@ +

Directi
1
1535. Find the Winner of an Array Game

Medium


Given an integer array arr of distinct integers and an integer k.

+ +

A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.

+ +

Return the integer which will win the game.

+ +

It is guaranteed that there will be a winner of the game.

+ +

 

+

Example 1:

+ +
Input: arr = [2,1,3,5,4,6,7], k = 2
+Output: 5
+Explanation: Let's see the rounds of the game:
+Round |       arr       | winner | win_count
+  1   | [2,1,3,5,4,6,7] | 2      | 1
+  2   | [2,3,5,4,6,7,1] | 3      | 1
+  3   | [3,5,4,6,7,1,2] | 5      | 1
+  4   | [5,4,6,7,1,2,3] | 5      | 2
+So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
+
+ +

Example 2:

+ +
Input: arr = [3,2,1], k = 10
+Output: 3
+Explanation: 3 will win the first 10 rounds consecutively.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= arr.length <= 105
  • +
  • 1 <= arr[i] <= 106
  • +
  • arr contains distinct integers.
  • +
  • 1 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager.cpp new file mode 100644 index 00000000..323ea613 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager.cpp @@ -0,0 +1,41 @@ +class SeatManager { +public: + + set st; + int counter = 1; + int N; + + SeatManager(int n) { + N = n; + } + + int reserve() { + + if(!st.empty()) + { + int least = *st.begin(); + st.erase(*st.begin()); + return least; + } + + if(counter <= N) + { + int smallestUnreserved = counter; + ++counter; + return smallestUnreserved; + } + + return -1; + } + + void unreserve(int seatNumber) { + st.insert(seatNumber); + } +}; + +/** + * Your SeatManager object will be instantiated and called as such: + * SeatManager* obj = new SeatManager(n); + * int param_1 = obj->reserve(); + * obj->unreserve(seatNumber); + */ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/README.md new file mode 100644 index 00000000..3c53089a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divdropbox-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1845-seat-reservation-manager/README.md @@ -0,0 +1,42 @@ +

Dropbox
1
1845. Seat Reservation Manager

Medium


Design a system that manages the reservation state of n seats that are numbered from 1 to n.

+ +

Implement the SeatManager class:

+ +
    +
  • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
  • +
  • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
  • +
  • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.
  • +
+ +

 

+

Example 1:

+ +
Input
+["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
+[[5], [], [], [2], [], [], [], [], [5]]
+Output
+[null, 1, 2, null, 2, 3, 4, 5, null]
+
+Explanation
+SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
+seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.
+seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
+seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].
+seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
+seatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which is 3.
+seatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is 4.
+seatManager.reserve();    // The only available seat is seat 5, so return 5.
+seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 1 <= seatNumber <= n
  • +
  • For each call to reserve, it is guaranteed that there will be at least one unreserved seat.
  • +
  • For each call to unreserve, it is guaranteed that seatNumber will be reserved.
  • +
  • At most 105 calls in total will be made to reserve and unreserve.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array.cpp new file mode 100644 index 00000000..ffa18222 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isMonotonic(vector& nums) { + + int n = nums.size(); + + bool incr = true, decr = true; + + for(int i = 1; i < n; ++i) + { + incr &= (nums[i-1] <= nums[i]); + decr &= (nums[i-1] >= nums[i]); + } + + return incr or decr; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/README.md new file mode 100644 index 00000000..cb6f2c41 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div896-monotonic-array/README.md @@ -0,0 +1,33 @@ +

Facebook
12
Amazon
2
896. Monotonic Array

Easy


An array is monotonic if it is either monotone increasing or monotone decreasing.

+ +

An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].

+ +

Given an integer array nums, return true if the given array is monotonic, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,2,3]
+Output: true
+
+ +

Example 2:

+ +
Input: nums = [6,5,4,4]
+Output: true
+
+ +

Example 3:

+ +
Input: nums = [1,3,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -105 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row.cpp new file mode 100644 index 00000000..f2f14855 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row.cpp @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector largestValues(TreeNode* root) { + + if(!root) + return {}; + + queue q; + + vector ans; + + q.push(root); + + while(!q.empty()) + { + int size = q.size(); + + int maxi = INT_MIN; + + for(int i = 0; i < size; ++i) + { + TreeNode* curr = q.front(); + q.pop(); + + maxi = max(maxi, curr->val); + + if(curr->left) + q.push(curr->left); + + if(curr->right) + q.push(curr->right); + } + + ans.push_back(maxi); + } + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence18-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div515-find-largest-value-in-each-tree-row/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes.cpp new file mode 100644 index 00000000..5549c5cf --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes.cpp @@ -0,0 +1,115 @@ +class DSU{ + private: + vector parent, size, rank; + public: + DSU(int n) + { + rank.resize(n+1, 0); + size.resize(n+1, 1); + parent.resize(n+1); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(parent[u] == u) + return u; + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } + +}; + + +class Solution { +public: + bool validateBinaryTreeNodes(int n, vector& leftChild, vector& rightChild) { + + vector indegree(n+1, 0); + + DSU dsu(n); + + for(int i = 0; i < n; ++i) + { + if(leftChild[i] != -1 and ++indegree[leftChild[i]] > 1) + return false; + if(rightChild[i] != -1 and ++indegree[rightChild[i]] > 1) + return false; + + if(leftChild[i] != -1) + { + if(dsu.findParent(i) == dsu.findParent(leftChild[i])) + return false; + else + dsu.unionByRank(i, leftChild[i]); + } + + if(rightChild[i] != -1) + { + if(dsu.findParent(i) == dsu.findParent(rightChild[i])) + return false; + else + dsu.unionByRank(i, rightChild[i]); + } + } + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + if(dsu.findParent(i) == i) + ++cnt; + } + + return cnt == 1; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/README.md new file mode 100644 index 00000000..6f7ec432 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1361-validate-binary-tree-nodes/README.md @@ -0,0 +1,34 @@ +

Facebook
2
1361. Validate Binary Tree Nodes

Medium


You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.

+ +

If node i has no left child then leftChild[i] will equal -1, similarly for the right child.

+ +

Note that the nodes have no values and that we only use the node numbers in this problem.

+ +

 

+

Example 1:

+ +
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
+Output: true
+
+ +

Example 2:

+ +
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
+Output: false
+
+ +

Example 3:

+ +
Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • n == leftChild.length == rightChild.length
  • +
  • 1 <= n <= 104
  • +
  • -1 <= leftChild[i], rightChild[i] <= n - 1
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break.cpp new file mode 100644 index 00000000..03f2b022 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + + int helper(int n, vector& dp) + { + if(n == 1) + return 1; + + if(dp[n] != -1) + return dp[n]; + + int res = 1; + + for(int i = 1; i <= n-1; ++i) + { + int prod = i * max(n - i, helper(n-i, dp)); + res = max(res, prod); + } + + return dp[n] = res; + } + + int integerBreak(int n) { + + vector dp(n+1, -1); + + return helper(n, dp); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/README.md new file mode 100644 index 00000000..929907f0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div343-integer-break/README.md @@ -0,0 +1,26 @@ +

Facebook
3
343. Integer Break

Medium


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

+ +

Return the maximum product you can get.

+ +

 

+

Example 1:

+ +
Input: n = 2
+Output: 1
+Explanation: 2 = 1 + 1, 1 × 1 = 1.
+
+ +

Example 2:

+ +
Input: n = 10
+Output: 36
+Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 58
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements.cpp new file mode 100644 index 00000000..de864305 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int largestSubmatrix(vector>& matrix) { + + int n = matrix.size(); + int m = matrix[0].size(); + + int ans = 0; + + vector> prevHeights; + + for(int row = 0; row < n; ++row) + { + vector> currHeights; + vector visited(m, false); + + for(auto& [height, col] : prevHeights) + { + if(matrix[row][col] == 1) + { + visited[col] = true; + currHeights.push_back({height+1, col}); + } + } + + for(int col = 0; col < m; ++col) + { + if(!visited[col] and matrix[row][col] == 1) + currHeights.push_back({1, col}); + } + + + for(int i = 0; i < currHeights.size(); ++i) + { + int height = currHeights[i].first; + int base = i+1; + ans = max(ans, height * base); + } + + prevHeights = currHeights; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/README.md new file mode 100644 index 00000000..258022d0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1727-largest-submatrix-with-rearrangements/README.md @@ -0,0 +1,38 @@ +

Google
1
1727. Largest Submatrix With Rearrangements

Medium


You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.

+ +

Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.

+ +

 

+

Example 1:

+ +
Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]
+Output: 4
+Explanation: You can rearrange the columns as shown above.
+The largest submatrix of 1s, in bold, has an area of 4.
+
+ +

Example 2:

+ +
Input: matrix = [[1,0,1,0,1]]
+Output: 3
+Explanation: You can rearrange the columns as shown above.
+The largest submatrix of 1s, in bold, has an area of 3.
+
+ +

Example 3:

+ +
Input: matrix = [[1,1,0],[1,0,1]]
+Output: 2
+Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m * n <= 105
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence15-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divroblox-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div792-number-of-matching-subsequences/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence15-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divroblox-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div792-number-of-matching-subsequences/README.md new file mode 100644 index 00000000..cb2c131c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence15-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divroblox-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div792-number-of-matching-subsequences/README.md @@ -0,0 +1,32 @@ +

Google
15
Roblox
2
792. Number of Matching Subsequences

Medium


Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

+ +

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

+ +
    +
  • For example, "ace" is a subsequence of "abcde".
  • +
+ +

 

+

Example 1:

+ +
Input: s = "abcde", words = ["a","bb","acd","ace"]
+Output: 3
+Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
+
+ +

Example 2:

+ +
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • 1 <= words.length <= 5000
  • +
  • 1 <= words[i].length <= 50
  • +
  • s and words[i] consist of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations.cpp new file mode 100644 index 00000000..38db9baf --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector buildArray(vector& target, int n) { + + vector ans; + + int k = 0; + + for(int i = 1; i <= n and k < target.size(); ++i) + { + if(target[k] == i) + { + ans.push_back("Push"); + ++k; + } + else + { + ans.push_back("Push"); + ans.push_back("Pop"); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/README.md new file mode 100644 index 00000000..051d4f2d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1441-build-an-array-with-stack-operations/README.md @@ -0,0 +1,64 @@ +

Google
2
1441. Build an Array With Stack Operations

Medium


You are given an integer array target and an integer n.

+ +

You have an empty stack with the two following operations:

+ +
    +
  • "Push": pushes an integer to the top of the stack.
  • +
  • "Pop": removes the integer on the top of the stack.
  • +
+ +

You also have a stream of the integers in the range [1, n].

+ +

Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:

+ +
    +
  • If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
  • +
  • If the stack is not empty, pop the integer at the top of the stack.
  • +
  • If, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.
  • +
+ +

Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.

+ +

 

+

Example 1:

+ +
Input: target = [1,3], n = 3
+Output: ["Push","Push","Pop","Push"]
+Explanation: Initially the stack s is empty. The last element is the top of the stack.
+Read 1 from the stream and push it to the stack. s = [1].
+Read 2 from the stream and push it to the stack. s = [1,2].
+Pop the integer on the top of the stack. s = [1].
+Read 3 from the stream and push it to the stack. s = [1,3].
+
+ +

Example 2:

+ +
Input: target = [1,2,3], n = 3
+Output: ["Push","Push","Push"]
+Explanation: Initially the stack s is empty. The last element is the top of the stack.
+Read 1 from the stream and push it to the stack. s = [1].
+Read 2 from the stream and push it to the stack. s = [1,2].
+Read 3 from the stream and push it to the stack. s = [1,2,3].
+
+ +

Example 3:

+ +
Input: target = [1,2], n = 4
+Output: ["Push","Push"]
+Explanation: Initially the stack s is empty. The last element is the top of the stack.
+Read 1 from the stream and push it to the stack. s = [1].
+Read 2 from the stream and push it to the stack. s = [1,2].
+Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
+The answers that read integer 3 from the stream are not accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target.length <= 100
  • +
  • 1 <= n <= 100
  • +
  • 1 <= target[i] <= n
  • +
  • target is strictly increasing.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array.cpp new file mode 100644 index 00000000..12c01f52 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minPairSum(vector& nums) { + + int n = nums.size(); + + int ans = 0; + + sort(nums.begin(), nums.end()); + + for(int i = 0; i <= n/2; ++i) + { + ans = max(ans, nums[i] + nums[n-i-1]); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1877-minimize-maximum-pair-sum-in-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero.cpp new file mode 100644 index 00000000..a5741f66 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int minOperations(vector& nums, int x) { + int tot = 0; + for(auto itr : nums) + tot += itr; + int ans = 0; + int n = nums.size(); + + if(tot == x) + return n; + + int i = 0, j = 0; + int ind = tot - x; + int sum = 0; + + while(j < n) + { + sum += nums[j]; + + while(i < j && sum > ind) + sum -= nums[i++]; + + if(sum == ind) + ans = max(ans,j - i + 1); + ++j; + } + + if(!ans) + return -1; + else + return n - ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1658-minimum-operations-to-reduce-x-to-zero/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference.cpp new file mode 100644 index 00000000..02b72711 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + char findTheDifference(string s, string t) { + + sort(t.begin(), t.end()); + sort(s.begin(), s.end()); + + int k = 0; + + for(int i = 0; i < s.size(); ++i) + { + if(s[i] == t[k]) + ++k; + else + return t[k]; + } + + return t.back(); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/README.md new file mode 100644 index 00000000..34fec164 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div389-find-the-difference/README.md @@ -0,0 +1,29 @@ +

Google
6
Amazon
3
Apple
2
389. Find the Difference

Easy


You are given two strings s and t.

+ +

String t is generated by random shuffling string s and then add one more letter at a random position.

+ +

Return the letter that was added to t.

+ +

 

+

Example 1:

+ +
Input: s = "abcd", t = "abcde"
+Output: "e"
+Explanation: 'e' is the letter that was added.
+
+ +

Example 2:

+ +
Input: s = "", t = "y"
+Output: "y"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 1000
  • +
  • t.length == s.length + 1
  • +
  • s and t consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare.cpp new file mode 100644 index 00000000..e4860bae --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + + string solve(string& str, int n) + { + int k = 0; + + for(int i = 0; i < n; ++i) + { + if(str[i] == '#') + { + k = max(0, --k); + } + else + { + str[k++] = str[i]; + } + } + + return str.substr(0, k); + } + + bool backspaceCompare(string s, string t) { + + int n = s.size(), m = t.size(); + + return (solve(s, n) == solve(t, m)); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/README.md new file mode 100644 index 00000000..f563b42e --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divibm-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbookingcom-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvisa-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbloomberg-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtiktok-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div844-backspace-string-compare/README.md @@ -0,0 +1,37 @@ +

IBM
6
Google
3
Booking.com
3
Apple
3
Visa
3
Bloomberg
2
tiktok
2
844. Backspace String Compare

Easy


Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

+ +

Note that after backspacing an empty text, the text will continue empty.

+ +

 

+

Example 1:

+ +
Input: s = "ab#c", t = "ad#c"
+Output: true
+Explanation: Both s and t become "ac".
+
+ +

Example 2:

+ +
Input: s = "ab##", t = "c#d#"
+Output: true
+Explanation: Both s and t become "".
+
+ +

Example 3:

+ +
Input: s = "a#c", t = "b"
+Output: false
+Explanation: s becomes "c" while t becomes "b".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 200
  • +
  • s and t only contain lowercase letters and '#' characters.
  • +
+ +

 

+

Follow up: Can you solve it in O(n) time and O(1) space?

+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits.cpp new file mode 100644 index 00000000..efe6dfbd --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector sortByBits(vector& arr) { + + sort(arr.begin(), arr.end(), [&](int& a, int & b) + { + int cntA = __builtin_popcount(a); + int cntB = __builtin_popcount(b); + + return (cntA == cntB ? a < b : cntA < cntB); + }); + + return arr; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/README.md new file mode 100644 index 00000000..b5d4b137 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divinfosys-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1356-sort-integers-by-the-number-of-1-bits/README.md @@ -0,0 +1,31 @@ +

Infosys
2
1356. Sort Integers by The Number of 1 Bits

Easy


You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

+ +

Return the array after sorting it.

+ +

 

+

Example 1:

+ +
Input: arr = [0,1,2,3,4,5,6,7,8]
+Output: [0,1,2,4,8,3,5,6,7]
+Explantion: [0] is the only integer with 0 bits.
+[1,2,4,8] all have 1 bit.
+[3,5,6] have 2 bits.
+[7] has 3 bits.
+The sorted array by bits is [0,1,2,4,8,3,5,6,7]
+
+ +

Example 2:

+ +
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
+Output: [1,2,4,8,16,32,64,128,256,512,1024]
+Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 500
  • +
  • 0 <= arr[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters.cpp new file mode 100644 index 00000000..1b331ed1 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int countCharacters(vector& words, string chars) { + + int counter = 0; + + unordered_map mp; + + for(auto& ch : chars) + ++mp[ch]; + + for(auto& word : words) + { + bool canFormed = true; + + unordered_map freq; + + for(auto& ch : word) + { + ++freq[ch]; + } + + for(auto& ch : word) + { + if(freq[ch] > mp[ch]) + { + canFormed = false; + break; + } + } + + if(canFormed) + counter += word.size(); + } + + return counter; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/README.md new file mode 100644 index 00000000..de231256 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divkarat-divdiv-classcompanytagscontainer-tagoccurence12-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divindeed-divdiv-classcompanytagscontainer-tagoccurence6-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoogle-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1160-find-words-that-can-be-formed-by-characters/README.md @@ -0,0 +1,30 @@ +

Karat
12
Indeed
6
Amazon
2
Google
2
1160. Find Words That Can Be Formed by Characters

Easy


You are given an array of strings words and a string chars.

+ +

A string is good if it can be formed by characters from chars (each character can only be used once).

+ +

Return the sum of lengths of all good strings in words.

+ +

 

+

Example 1:

+ +
Input: words = ["cat","bt","hat","tree"], chars = "atach"
+Output: 6
+Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
+
+ +

Example 2:

+ +
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
+Output: 10
+Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length, chars.length <= 100
  • +
  • words[i] and chars consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii.cpp new file mode 100644 index 00000000..942b1785 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector getRow(int rowIndex) { + + vector res(rowIndex+1, 1); + + for(int i = 0; i < rowIndex; ++i) + { + for(int j = i; j > 0; --j) + res[j] += res[j-1]; + } + return res; + } +}; + diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/README.md new file mode 100644 index 00000000..e5747c89 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divgoldman-sachs-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div119-pascals-triangle-ii/README.md @@ -0,0 +1,25 @@ +

Microsoft
2
Goldman Sachs
2
119. Pascal's Triangle II

Easy


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

+ +

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

+ +

 

+

Example 1:

+
Input: rowIndex = 3
+Output: [1,3,3,1]
+

Example 2:

+
Input: rowIndex = 0
+Output: [1]
+

Example 3:

+
Input: rowIndex = 1
+Output: [1,1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= rowIndex <= 33
  • +
+ +

 

+

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

+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs.cpp new file mode 100644 index 00000000..1b672930 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numIdenticalPairs(vector& nums) { + + int n = nums.size(); + + unordered_map mp; + + for(auto& itr : nums) + ++mp[itr]; + + int count = 0; + + for(auto& [key, value] : mp) + { + count += (value * (value-1))/2; + } + + return count; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/README.md new file mode 100644 index 00000000..c5e5ff2c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1512-number-of-good-pairs/README.md @@ -0,0 +1,33 @@ +

Microsoft
3
Amazon
3
Adobe
2
1512. Number of Good Pairs

Easy


Given an array of integers nums, return the number of good pairs.

+ +

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1,1,3]
+Output: 4
+Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
+
+ +

Example 2:

+ +
Input: nums = [1,1,1,1]
+Output: 6
+Explanation: Each pair in the array are good.
+
+ +

Example 3:

+ +
Input: nums = [1,2,3]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii.cpp new file mode 100644 index 00000000..610932ec --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + string reverseWords(string s) { + + stringstream ss(s); + + string word; + + string ans; + + while(ss >> word) + { + reverse(word.begin(), word.end()); + ans += word + ' '; + } + + ans.pop_back(); + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/README.md new file mode 100644 index 00000000..b13bbc68 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divmicrosoft-divdiv-classcompanytagscontainer-tagoccurence5-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divbolt-divdiv-classcompanytagscontainer-tagoccurence3-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divyandex-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divfacebook-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divapple-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpaytm-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div557-reverse-words-in-a-string-iii/README.md @@ -0,0 +1,21 @@ +

Microsoft
5
Amazon
3
Bolt
3
Yandex
2
Facebook
2
Apple
2
PayTM
2
557. Reverse Words in a String III

Easy


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

+ +

 

+

Example 1:

+
Input: s = "Let's take LeetCode contest"
+Output: "s'teL ekat edoCteeL tsetnoc"
+

Example 2:

+
Input: s = "God Ding"
+Output: "doG gniD"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s contains printable ASCII characters.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • There is at least one word in s.
  • +
  • All the words in s are separated by a single space.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii.cpp new file mode 100644 index 00000000..92d4e476 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minimumTime(int n, vector>& E, vector& T) { + vector> G(n); + vector indegree(n), dist(n); + for (auto &e : E) { + G[e[0] - 1].push_back(e[1] - 1); + indegree[e[1] - 1]++; + } + queue q; + for (int i = 0; i < n; ++i) { + if (indegree[i] == 0) { + q.push(i); + dist[i] = T[i]; + } + } + while (q.size()) { + int u = q.front(); + q.pop(); + for (int v : G[u]) { + dist[v] = max(dist[u] + T[v], dist[v]); + if (--indegree[v] == 0) q.push(v); + } + } + return *max_element(begin(dist), end(dist)); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/README.md new file mode 100644 index 00000000..b26d9a0c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divpinterest-divdiv-classcompanytagscontainer-tagoccurence4-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2050-parallel-courses-iii/README.md @@ -0,0 +1,53 @@ +

Pinterest
4
2050. Parallel Courses III

Hard


You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.

+ +

You must find the minimum number of months needed to complete all the courses following these rules:

+ +
    +
  • You may start taking a course at any time if the prerequisites are met.
  • +
  • Any number of courses can be taken at the same time.
  • +
+ +

Return the minimum number of months needed to complete all the courses.

+ +

Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).

+ +

 

+

Example 1:

+ + +
Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
+Output: 8
+Explanation: The figure above represents the given graph and the time required to complete each course. 
+We start course 1 and course 2 simultaneously at month 0.
+Course 1 takes 3 months and course 2 takes 2 months to complete respectively.
+Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.
+
+ +

Example 2:

+ + +
Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]
+Output: 12
+Explanation: The figure above represents the given graph and the time required to complete each course.
+You can start courses 1, 2, and 3 at month 0.
+You can complete them after 1, 2, and 3 months respectively.
+Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.
+Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.
+Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 5 * 104
  • +
  • 0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)
  • +
  • relations[j].length == 2
  • +
  • 1 <= prevCoursej, nextCoursej <= n
  • +
  • prevCoursej != nextCoursej
  • +
  • All the pairs [prevCoursej, nextCoursej] are unique.
  • +
  • time.length == n
  • +
  • 1 <= time[i] <= 104
  • +
  • The given graph is a directed acyclic graph.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four.cpp new file mode 100644 index 00000000..eb1b35f2 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + + bool helper(int n) + { + if(n <= 0) + return false; + + if(n == 1) + return true; + + if(n % 4 == 0) + return helper(n/4); + + return false; + } + + bool isPowerOfFour(int n) { + return helper(n); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/README.md new file mode 100644 index 00000000..f84ffe4d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divtwo-sigma-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div342-power-of-four/README.md @@ -0,0 +1,24 @@ +

Two Sigma
1
342. Power of Four

Easy


Given an integer n, return true if it is a power of four. Otherwise, return false.

+ +

An integer n is a power of four, if there exists an integer x such that n == 4x.

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower.cpp new file mode 100644 index 00000000..f2a40390 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower.cpp @@ -0,0 +1,23 @@ +class Solution { +public: +double champagneTower(int poured, int query_row, int query_glass) { + + double result[101][101] = {0.0}; + + result[0][0] = poured; + + for (int i = 0; i < 100; i++) + { + for (int j = 0; j <= i; j++) + { + if (result[i][j] >= 1) + { + result[i + 1][j] += (result[i][j] - 1) / 2.0; + result[i + 1][j + 1] += (result[i][j] - 1) / 2.0; + result[i][j] = 1; + } + } + } + return result[query_row][query_glass]; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/README.md new file mode 100644 index 00000000..11954b9d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divuber-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divamazon-divdiv-classcompanytagscontainer-tagoccurence2-div-divdiv-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divadobe-divdiv-classcompanytagscontainer-tagoccurence2-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div799-champagne-tower/README.md @@ -0,0 +1,38 @@ +

Uber
2
Amazon
2
Adobe
2
799. Champagne Tower

Medium


We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne.

+ +

Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)

+ +

For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

+ +

+ +

Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)

+ +

 

+

Example 1:

+ +
Input: poured = 1, query_row = 1, query_glass = 1
+Output: 0.00000
+Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
+
+ +

Example 2:

+ +
Input: poured = 2, query_row = 1, query_glass = 1
+Output: 0.50000
+Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
+
+ +

Example 3:

+ +
Input: poured = 100000009, query_row = 33, query_glass = 17
+Output: 1.00000
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= poured <= 109
  • +
  • 0 <= query_glass <= query_row < 100
  • +
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings.cpp new file mode 100644 index 00000000..02b8bc5c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int countHomogenous(string s) { + + int n = s.size(), cnt = 0, prev = 0, res = 0; + + const int mod = 1e9 + 7; + + for(auto& itr : s) + { + cnt = (itr == prev ? cnt+1 : 1); + + prev = itr; + + res = (res + cnt) % mod; + } + + return res; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/README.md new file mode 100644 index 00000000..f0e7b65d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divvirtu-financial-divdiv-classcompanytagscontainer-tagoccurence1-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1759-count-number-of-homogenous-substrings/README.md @@ -0,0 +1,40 @@ +

Virtu Financial
1
1759. Count Number of Homogenous Substrings

Medium


Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.

+ +

A string is homogenous if all the characters of the string are the same.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "abbcccaa"
+Output: 13
+Explanation: The homogenous substrings are listed as below:
+"a"   appears 3 times.
+"aa"  appears 1 time.
+"b"   appears 2 times.
+"bb"  appears 1 time.
+"c"   appears 3 times.
+"cc"  appears 2 times.
+"ccc" appears 1 time.
+3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
+ +

Example 2:

+ +
Input: s = "xy"
+Output: 2
+Explanation: The homogenous substrings are "x" and "y".
+ +

Example 3:

+ +
Input: s = "zzzzz"
+Output: 15
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase letters.
  • +
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp new file mode 100644 index 00000000..adbdb99b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool winnerOfGame(string colors) { + + int n = colors.size(); + + int aliceMoves = 0, bobMoves = 0; + + for(int i = 1; i < n-1; ++i) + { + char prev = colors[i-1]; + char curr = colors[i]; + char next = colors[i+1]; + + if(prev == curr and curr == next) + { + if(curr == 'A') + ++aliceMoves; + else + ++bobMoves; + } + } + + return (aliceMoves >= bobMoves + 1 ? 1 : 0); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md new file mode 100644 index 00000000..6499f289 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tag-stylebackground-color-rgba0-10-32-005-divwalmart-global-tech-divdiv-classcompanytagscontainer-tagoccurence9-div-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md @@ -0,0 +1,63 @@ +

Walmart Global Tech
9
2038. Remove Colored Pieces if Both Neighbors are the Same Color

Medium


There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.

+ +

Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.

+ +
    +
  • Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
  • +
  • Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
  • +
  • Alice and Bob cannot remove pieces from the edge of the line.
  • +
  • If a player cannot make a move on their turn, that player loses and the other player wins.
  • +
+ +

Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.

+ +

 

+

Example 1:

+ +
Input: colors = "AAABABB"
+Output: true
+Explanation:
+AAABABB -> AABABB
+Alice moves first.
+She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.
+
+Now it's Bob's turn.
+Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
+Thus, Alice wins, so return true.
+
+ +

Example 2:

+ +
Input: colors = "AA"
+Output: false
+Explanation:
+Alice has her turn first.
+There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
+Thus, Bob wins, so return false.
+
+ +

Example 3:

+ +
Input: colors = "ABBBBBBBAAA"
+Output: false
+Explanation:
+ABBBBBBBAAA -> ABBBBBBBAA
+Alice moves first.
+Her only option is to remove the second to last 'A' from the right.
+
+ABBBBBBBAA -> ABBBBBBAA
+Next is Bob's turn.
+He has many options for which 'B' piece to remove. He can pick any.
+
+On Alice's second turn, she has no more pieces that she can remove.
+Thus, Bob wins, so return false.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= colors.length <= 105
  • +
  • colors consists of only the letters 'A' and 'B'
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain.java b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain.java new file mode 100644 index 00000000..cab2a85c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain.java @@ -0,0 +1,56 @@ +class Solution { + + int[][]dp = new int[1001][1001]; + + boolean isPredecessor(String s, String t) + { + int n = s.length(); + int m = t.length(); + + if(n >= m || m - n != 1) + return false; + + int k = 0; + + for(int i = 0; i < m && k < n; ++i) + { + if(t.charAt(i) == s.charAt(k)) + ++k; + } + + return k == n; + } + + int helper(int idx, int prevIdx, int n, String[] words) + { + if(idx == n) + return 0; + + if(dp[idx][prevIdx+1] != -1) + return dp[idx][prevIdx+1]; + + int notTake = helper(idx+1, prevIdx, n, words); + + int take = 0; + + if(prevIdx == -1 || isPredecessor(words[prevIdx], words[idx])) + { + take = 1 + helper(idx+1, idx, n, words); + } + + return dp[idx][prevIdx + 1] = Math.max(take, notTake); + } + + public int longestStrChain(String[] words) { + + int n = words.length; + + Arrays.sort(words, (String a, String b) -> a.length() - b.length()); + + for(int[] row : dp) + Arrays.fill(row,-1); + + return helper(0, -1, n, words); + + } +} \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/README.md new file mode 100644 index 00000000..318adb0c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1048-longest-string-chain/README.md @@ -0,0 +1,44 @@ +

No companies found for this problem
1048. Longest String Chain

Medium


You are given an array of words where each word consists of lowercase English letters.

+ +

wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.

+ +
    +
  • For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
  • +
+ +

A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

+ +

Return the length of the longest possible word chain with words chosen from the given list of words.

+ +

 

+

Example 1:

+ +
Input: words = ["a","b","ba","bca","bda","bdca"]
+Output: 4
+Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
+
+ +

Example 2:

+ +
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
+Output: 5
+Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
+
+ +

Example 3:

+ +
Input: words = ["abcd","dbqca"]
+Output: 1
+Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
+["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length <= 16
  • +
  • words[i] only consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters.cpp new file mode 100644 index 00000000..b9602471 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + string smallestSubsequence(string s) { + + int n = s.size(); + + vector lastOccurence(26, -1); + + vector visited(26, false); + + for(int i = 0; i < n; ++i) + lastOccurence[s[i] - 'a'] = i; + + string ans; + + for(int i = 0; i < n; ++i) + { + while(!ans.empty() and !visited[s[i] - 'a'] and s[i] < ans.back() and lastOccurence[ans.back() - 'a'] > i) + { + visited[ans.back() - 'a'] = false; + + ans.pop_back(); + } + + if(!visited[s[i] - 'a']) + { + ans += s[i]; + visited[s[i] - 'a'] = true; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/README.md new file mode 100644 index 00000000..1e0f5f90 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1081-smallest-subsequence-of-distinct-characters/README.md @@ -0,0 +1,25 @@ +

No companies found for this problem
1081. Smallest Subsequence of Distinct Characters

Medium


Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

+ +

 

+

Example 1:

+ +
Input: s = "bcabc"
+Output: "abc"
+
+ +

Example 2:

+ +
Input: s = "cbacdcbc"
+Output: "acdb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of lowercase English letters.
  • +
+ +

 

+Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array.cpp new file mode 100644 index 00000000..f0261a5c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array.cpp @@ -0,0 +1,51 @@ +/** + * // This is the MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * class MountainArray { + * public: + * int get(int index); + * int length(); + * }; + */ + +class Solution { +public: + int findInMountainArray(int target, MountainArray A) { + int n = A.length(), l, r, m, peak = 0; + + l = 0; + r = n - 1; + while (l < r) { + m = (l + r) / 2; + if (A.get(m) < A.get(m + 1)) + l = peak = m + 1; + else + r = m; + } + + l = 0; + r = peak; + while (l <= r) { + m = (l + r) / 2; + if (A.get(m) < target) + l = m + 1; + else if (A.get(m) > target) + r = m - 1; + else + return m; + } + + l = peak; + r = n - 1; + while (l <= r) { + m = (l + r) / 2; + if (A.get(m) > target) + l = m + 1; + else if (A.get(m) < target) + r = m - 1; + else + return m; + } + return -1; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/README.md new file mode 100644 index 00000000..2e3225cb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1095-find-in-mountain-array/README.md @@ -0,0 +1,48 @@ +

No companies found for this problem
1095. Find in Mountain Array

Hard


(This problem is an interactive problem.)

+ +

You may recall that an array arr is a mountain array if and only if:

+ +
    +
  • arr.length >= 3
  • +
  • There exists some i with 0 < i < arr.length - 1 such that: +
      +
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • +
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • +
    +
  • +
+ +

Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.

+ +

You cannot access the mountain array directly. You may only access the array using a MountainArray interface:

+ +
    +
  • MountainArray.get(k) returns the element of the array at index k (0-indexed).
  • +
  • MountainArray.length() returns the length of the array.
  • +
+ +

Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

+ +

 

+

Example 1:

+ +
Input: array = [1,2,3,4,5,3,1], target = 3
+Output: 2
+Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
+ +

Example 2:

+ +
Input: array = [0,1,2,4,2,1], target = 3
+Output: -1
+Explanation: 3 does not exist in the array, so we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= mountain_arr.length() <= 104
  • +
  • 0 <= target <= 109
  • +
  • 0 <= mountain_arr.get(index) <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation.cpp new file mode 100644 index 00000000..56bada35 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation.cpp @@ -0,0 +1,55 @@ +class Solution { + unordered_map> mp; + int mod = 1e9+7; + +public: + + int helper(int n ,int i ,char prev, vector>& t) + { + if(i > n) + return 0; + + if(i == n) + { + switch(prev) + { + case 'a': + return 1; + case 'e': + return 2; + case 'i': + return 4; + case 'o': + return 2; + case 'u': + return 1; + default: + return 5; + } + } + + int idx = prev - 'a'; + if(t[i][idx] != -1) + return t[i][idx]; + + long long ans = 0; + for(auto next : mp[prev]) + ans += (helper(n,i+1,next,t) % mod); + + return t[i][idx] = ans % mod; + } + + int countVowelPermutation(int n) { + + mp['c'] = {'a','e','i','o','u'}; + mp['a'] = {'e'}; + mp['e'] = {'a','i'}; + mp['i'] = {'a','e','o','u'}; + mp['o'] = {'i','u'}; + mp['u'] = {'a'}; + + vector> t(n+2,vector(27,-1)); + return helper(n,1,'c',t); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1220-count-vowels-permutation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.cpp new file mode 100644 index 00000000..5c0ea1e2 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + + const int mod = 1e9+7; + + int helper(int idx, int steps, int arrLen, vector>& dp) + { + if(steps == 0 and idx == 0) + { + return 1; + } + + if(idx < 0 or idx >= arrLen or (idx != 0 and steps == 0)) + return 0; + + if(dp[idx][steps] != -1) + return dp[idx][steps]; + + int stay = helper(idx, steps-1, arrLen, dp); + + int left = helper(idx-1, steps-1, arrLen, dp); + + int right = helper(idx+1, steps-1, arrLen, dp); + + return dp[idx][steps] = ((((stay)%mod + left)%mod + right)%mod)%mod; + } + + int numWays(int steps, int arrLen) { + + vector> dp(steps+1, vector(steps+1, -1)); + + return helper(0, steps, arrLen, dp); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/README.md new file mode 100644 index 00000000..ad55ddcb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1269-number-of-ways-to-stay-in-the-same-place-after-some-steps/README.md @@ -0,0 +1,39 @@ +

No companies found for this problem
1269. Number of Ways to Stay in the Same Place After Some Steps

Hard


You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).

+ +

Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: steps = 3, arrLen = 2
+Output: 4
+Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
+Right, Left, Stay
+Stay, Right, Left
+Right, Stay, Left
+Stay, Stay, Stay
+
+ +

Example 2:

+ +
Input: steps = 2, arrLen = 4
+Output: 2
+Explanation: There are 2 differents ways to stay at index 0 after 2 steps
+Right, Left
+Stay, Stay
+
+ +

Example 3:

+ +
Input: steps = 4, arrLen = 2
+Output: 8
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= steps <= 500
  • +
  • 1 <= arrLen <= 106
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.cpp new file mode 100644 index 00000000..70edfa32 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numOfArrays(int n, int m, int h) { + int64_t dp[n][h+1][m+1]; + memset(dp, 0, (n)*(h+1)*(m+1)*sizeof(int64_t)); + for(int i = 0; i < n; ++i) { + for(int j = 1; j <= h; ++j) { + for(int k = j; k <= m; ++k) { + dp[i][j][k] = dp[i][j][k-1]; + if(i == 0) { + dp[i][j][k] += j == 1 ? 1 : 0; + continue; + } + dp[i][j][k] = (dp[i][j][k] + dp[i-1][j-1][k-1] + (dp[i-1][j][k] + MOD - dp[i-1][j][k-1]) * k) % MOD; + } + } + } + return dp[n-1][h][m]; + } + static const int MOD = 1e9+7; +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/README.md new file mode 100644 index 00000000..b71eddf5 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons/README.md @@ -0,0 +1,43 @@ +

No companies found for this problem
1420. Build Array Where You Can Find The Maximum Exactly K Comparisons

Hard


You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:

+ +

You should build the array arr which has the following properties:

+ +
    +
  • arr has exactly n integers.
  • +
  • 1 <= arr[i] <= m where (0 <= i < n).
  • +
  • After applying the mentioned algorithm to arr, the value search_cost is equal to k.
  • +
+ +

Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 2, m = 3, k = 1
+Output: 6
+Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
+
+ +

Example 2:

+ +
Input: n = 5, m = 2, k = 3
+Output: 0
+Explanation: There are no possible arrays that satisify the mentioned conditions.
+
+ +

Example 3:

+ +
Input: n = 9, m = 1, k = 1
+Output: 1
+Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 50
  • +
  • 1 <= m <= 100
  • +
  • 0 <= k <= n
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum.cpp new file mode 100644 index 00000000..2a6a2dc4 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + + int n = nums.size(); + + vector dp(nums); + + deque dq; + + int ans = dp[0]; + + for(int i = 0; i < n; ++i) + { + while(!dq.empty() and i - dq.front() > k) + dq.pop_front(); + + if(!dq.empty()) + dp[i] = max(dp[i], nums[i] + dp[dq.front()]); + + while(!dq.empty() and dp[i] >= dp[dq.back()]) + dq.pop_back(); + + dq.push_back(i); + + ans = max(ans, dp[i]); + } + + return ans; + } +}; diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/README.md new file mode 100644 index 00000000..83b7de49 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1425-constrained-subsequence-sum/README.md @@ -0,0 +1,34 @@ +

No companies found for this problem
1425. Constrained Subsequence Sum

Hard


Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

+ +

A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

+ +

 

+

Example 1:

+ +
Input: nums = [10,2,-10,5,20], k = 2
+Output: 37
+Explanation: The subsequence is [10, 2, 5, 20].
+
+ +

Example 2:

+ +
Input: nums = [-1,-2,-3], k = 1
+Output: -1
+Explanation: The subsequence must be non-empty, so we choose the largest number.
+
+ +

Example 3:

+ +
Input: nums = [10,-2,-10,-5,20], k = 2
+Output: 23
+Explanation: The subsequence is [10, -2, -5, 20].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences.cpp new file mode 100644 index 00000000..145c11a2 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + + int helper(int i, int j, int n, int m, vector& nums1, vector& nums2, vector>& dp) + { + if(i == n or j == m) + return -1e9; + + if(dp[i][j] != -1) + return dp[i][j]; + + int res = INT_MIN; + + int take = max(nums1[i] * nums2[j], nums1[i] * nums2[j] + helper(i+1, j+1, n, m, nums1, nums2, dp)); + + int notTake = max(helper(i+1, j, n, m, nums1, nums2, dp), helper(i, j+1, n, m, nums1, nums2, dp)); + + return dp[i][j] = max(take, notTake); + + } + + int maxDotProduct(vector& nums1, vector& nums2) { + + int n = nums1.size(); + int m = nums2.size(); + + vector> dp(n+1, vector(m+1, -1)); + + return helper(0, 0, n, m, nums1, nums2, dp); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/README.md new file mode 100644 index 00000000..c15422c7 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1458-max-dot-product-of-two-subsequences/README.md @@ -0,0 +1,36 @@ +

No companies found for this problem
1458. Max Dot Product of Two Subsequences

Hard


Given two arrays nums1 and nums2.

+ +

Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.

+ +

A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).

+ +

 

+

Example 1:

+ +
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
+Output: 18
+Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
+Their dot product is (2*3 + (-2)*(-6)) = 18.
+ +

Example 2:

+ +
Input: nums1 = [3,-2], nums2 = [2,-6,7]
+Output: 21
+Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
+Their dot product is (3*7) = 21.
+ +

Example 3:

+ +
Input: nums1 = [-1,-1], nums2 = [1,1]
+Output: -1
+Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
+Their dot product is -1.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 500
  • +
  • -1000 <= nums1[i], nums2[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero.cpp new file mode 100644 index 00000000..eaad07b4 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int minimumOneBitOperations(int n) { + if (n <= 1) + return n; + int bit = 0; + while ((1 << bit) <= n) + bit++; + return ((1 << bit) - 1) - minimumOneBitOperations(n - (1 << (bit-1))); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/README.md new file mode 100644 index 00000000..683b1133 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1611-minimum-one-bit-operations-to-make-integers-zero/README.md @@ -0,0 +1,37 @@ +

No companies found for this problem
1611. Minimum One Bit Operations to Make Integers Zero

Hard


Given an integer n, you must transform it into 0 using the following operations any number of times:

+ +
    +
  • Change the rightmost (0th) bit in the binary representation of n.
  • +
  • Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
  • +
+ +

Return the minimum number of operations to transform n into 0.

+ +

 

+

Example 1:

+ +
Input: n = 3
+Output: 2
+Explanation: The binary representation of 3 is "11".
+"11" -> "01" with the 2nd operation since the 0th bit is 1.
+"01" -> "00" with the 1st operation.
+
+ +

Example 2:

+ +
Input: n = 6
+Output: 4
+Explanation: The binary representation of 6 is "110".
+"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
+"010" -> "011" with the 1st operation.
+"011" -> "001" with the 2nd operation since the 0th bit is 1.
+"001" -> "000" with the 1st operation.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort.cpp new file mode 100644 index 00000000..68298589 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int minimumEffortPath(vector>& heights) { + + int n = heights.size(); + int m = heights[0].size(); + priority_queue, vector>, greater> > pq; + + vector> dist(n, vector(m, INT_MAX)); + + dist[0][0] = 0; + + pq.push({0, 0, 0}); + + vector dx = {0, +1, 0, -1}; + vector dy = {+1, 0, -1, 0}; + + while(!pq.empty()) + { + auto currRoute = pq.top(); + pq.pop(); + + int currDiff = get<0> (currRoute); + int x = get<1> (currRoute); + int y = get<2> (currRoute); + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m) + { + int diff = max(currDiff, abs(heights[x][y] - heights[newx][newy])); + + if(diff < dist[newx][newy]) + { + pq.push({diff, newx, newy}); + dist[newx][newy] = diff; + } + } + } + } + + return dist[n-1][m-1]; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/README.md new file mode 100644 index 00000000..04c9049d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1631-path-with-minimum-effort/README.md @@ -0,0 +1,42 @@ +

No companies found for this problem
1631. Path With Minimum Effort

Medium


You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

+ +

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

+ +

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

+ +

 

+

Example 1:

+ +

+ +
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
+Output: 2
+Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
+This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
+
+ +

Example 2:

+ +

+ +
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
+Output: 1
+Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
+
+ +

Example 3:

+ +
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
+Output: 0
+Explanation: This route does not require any effort.
+
+ +

 

+

Constraints:

+ +
    +
  • rows == heights.length
  • +
  • columns == heights[i].length
  • +
  • 1 <= rows, columns <= 100
  • +
  • 1 <= heights[i][j] <= 106
  • +
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array.cpp new file mode 100644 index 00000000..e25a2d5b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector getSumAbsoluteDifferences(vector& nums) { + + int n = nums.size(); + + vector pref(n+1,0); + + for(int i = 1; i <= n; ++i) + pref[i] = pref[i-1] + nums[i-1]; + + vector ans; + + for(int i = 1; i <= n; ++i) + { + long long leftSum = nums[i-1] * 1LL * i; + long long left = leftSum - pref[i]; + + long long rightSum = nums[i-1] * 1LL * (n-i); + long long right = pref[n] - pref[i] - rightSum; + + ans.push_back(left + right); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray.cpp new file mode 100644 index 00000000..1e22038a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maximumScore(vector& nums, int k) { + + int n = nums.size(); + + int i = k, j = k; + + int ans = nums[k], currMin = nums[k]; + + while(i > 0 or j < n-1) + { + int left = (i > 0 ? nums[i-1] : 0); + int right = (j < n-1 ? nums[j+1] : 0); + + if(left > right) + { + --i; + currMin = min(currMin, nums[i]); + } + else + { + ++j; + currMin = min(currMin,nums[j]); + } + + ans = max(ans, currMin * (j-i+1)); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/README.md new file mode 100644 index 00000000..8e27f09c --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1793-maximum-score-of-a-good-subarray/README.md @@ -0,0 +1,30 @@ +

No companies found for this problem
1793. Maximum Score of a Good Subarray

Hard


You are given an array of integers nums (0-indexed) and an integer k.

+ +

The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.

+ +

Return the maximum possible score of a good subarray.

+ +

 

+

Example 1:

+ +
Input: nums = [1,4,3,7,4,5], k = 3
+Output: 15
+Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. 
+
+ +

Example 2:

+ +
Input: nums = [5,5,4,5,4,1,1,1], k = 0
+Output: 20
+Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 2 * 104
  • +
  • 0 <= k < nums.length
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp new file mode 100644 index 00000000..39056bf9 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maxFrequency(vector& nums, int k) { + + long long currSum = 0; + + int i = 0, j = 0, n = nums.size(); + + int ans = 0; + + sort(nums.begin(), nums.end()); + + while(j < n) + { + currSum += nums[j]; + + int cnt = j - i + 1; + + long long windowSum = cnt * 1LL * nums[j]; + + if(windowSum - currSum > k) + { + windowSum -= nums[j]; + currSum -= nums[i++]; + } + + ans = max(ans, (j-i+1)); + + ++j; + } + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/README.md new file mode 100644 index 00000000..bdb094f6 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1838-frequency-of-the-most-frequent-element/README.md @@ -0,0 +1,39 @@ +

No companies found for this problem
1838. Frequency of the Most Frequent Element

Medium


The frequency of an element is the number of times it occurs in an array.

+ +

You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.

+ +

Return the maximum possible frequency of an element after performing at most k operations.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,4], k = 5
+Output: 3
+Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
+4 has a frequency of 3.
+ +

Example 2:

+ +
Input: nums = [1,4,8,13], k = 5
+Output: 2
+Explanation: There are multiple optimal solutions:
+- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
+- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
+- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
+
+ +

Example 3:

+ +
Input: nums = [3,9,6], k = 2
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
  • 1 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging.cpp new file mode 100644 index 00000000..62f90fac --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maximumElementAfterDecrementingAndRearranging(vector& arr) { + + int n = arr.size(); + + sort(arr.begin(), arr.end()); + + int operation = 0; + + if(arr[0] != 1) + { + arr[0] = 1; + } + + int ans = arr[0]; + + for(int i = 1; i < n; ++i) + { + if(abs(arr[i] - arr[i-1]) > 1) + { + arr[i] = arr[i-1] + 1; + ++operation; + } + ans = max(ans, arr[i]); + } + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1846-maximum-element-after-decreasing-and-rearranging/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal.cpp new file mode 100644 index 00000000..894f7ffb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int reductionOperations(vector& nums) { + + int n = nums.size(), ans = 0; + + sort(nums.begin(), nums.end()); + + for(int i = n-1; i > 0; --i) + { + if(nums[i] != nums[i-1]) + { + ans += (n - i); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/README.md new file mode 100644 index 00000000..2cd89aae --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1887-reduction-operations-to-make-the-array-elements-equal/README.md @@ -0,0 +1,47 @@ +

No companies found for this problem
1887. Reduction Operations to Make the Array Elements Equal

Medium


Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:

+ +
    +
  1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
  2. +
  3. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
  4. +
  5. Reduce nums[i] to nextLargest.
  6. +
+ +

Return the number of operations to make all elements in nums equal.

+ +

 

+

Example 1:

+ +
Input: nums = [5,1,3]
+Output: 3
+Explanation: It takes 3 operations to make all elements in nums equal:
+1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
+2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
+3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
+
+ +

Example 2:

+ +
Input: nums = [1,1,1]
+Output: 0
+Explanation: All elements in nums are already equal.
+
+ +

Example 3:

+ +
Input: nums = [1,1,2,2,3]
+Output: 4
+Explanation: It takes 4 operations to make all elements in nums equal:
+1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
+2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
+3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
+4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 1 <= nums[i] <= 5 * 104
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters.cpp new file mode 100644 index 00000000..e7a702a0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int eliminateMaximum(vector& dist, vector& speed) { + + int n = dist.size(); + + vector vec; + + for(int i = 0; i < n; ++i) + { + vec.push_back((float)dist[i]/speed[i]); + } + + sort(vec.begin(), vec.end()); + + int counter = 1, ans = 1; + + for(int i = 1; i < n; ++i) + { + if(counter < vec[i]) + ++ans; + else + break; + ++counter; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/README.md new file mode 100644 index 00000000..684cc6cc --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div1921-eliminate-maximum-number-of-monsters/README.md @@ -0,0 +1,50 @@ +

No companies found for this problem
1921. Eliminate Maximum Number of Monsters

Medium


You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.

+ +

The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.

+ +

You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.

+ +

You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.

+ +

Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.

+ +

 

+

Example 1:

+ +
Input: dist = [1,3,4], speed = [1,1,1]
+Output: 3
+Explanation:
+In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.
+After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.
+All 3 monsters can be eliminated.
+ +

Example 2:

+ +
Input: dist = [1,1,2,3], speed = [1,1,1,1]
+Output: 1
+Explanation:
+In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,0,1,2], so you lose.
+You can only eliminate 1 monster.
+
+ +

Example 3:

+ +
Input: dist = [3,2,4], speed = [5,3,2]
+Output: 1
+Explanation:
+In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,0,2], so you lose.
+You can only eliminate 1 monster.
+
+ +

 

+

Constraints:

+ +
    +
  • n == dist.length == speed.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= dist[i], speed[i] <= 105
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous.cpp new file mode 100644 index 00000000..0214797b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minOperations(vector& arr) { + int n = arr.size(); + if(n == 1) return 0; + sort(arr.begin(), arr.end()); + + vector a; + for(int i = 0; i < n-1; i++) { + while(arr[i] == arr[i+1]) i++; + a.push_back(arr[i]); + } + if(arr.back() != a.back()) a.push_back(arr.back()); + + int mx = 0; + for(int i = 0, j = 0; i < a.size(); i++) { + while(j <= i && (a[i]-a[j]+1) > n) j++; + mx = max(mx, i-j+1); + } + return n - mx; +} +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/README.md new file mode 100644 index 00000000..0ec8717b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2009-minimum-number-of-operations-to-make-array-continuous/README.md @@ -0,0 +1,48 @@ +

No companies found for this problem
2009. Minimum Number of Operations to Make Array Continuous

Hard


You are given an integer array nums. In one operation, you can replace any element in nums with any integer.

+ +

nums is considered continuous if both of the following conditions are fulfilled:

+ +
    +
  • All elements in nums are unique.
  • +
  • The difference between the maximum element and the minimum element in nums equals nums.length - 1.
  • +
+ +

For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.

+ +

Return the minimum number of operations to make nums continuous.

+ +

 

+

Example 1:

+ +
Input: nums = [4,2,5,3]
+Output: 0
+Explanation: nums is already continuous.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,5,6]
+Output: 1
+Explanation: One possible solution is to change the last element to 4.
+The resulting array is [1,2,3,5,4], which is continuous.
+
+ +

Example 3:

+ +
Input: nums = [1,10,100,1000]
+Output: 3
+Explanation: One possible solution is to:
+- Change the second element to 2.
+- Change the third element to 3.
+- Change the fourth element to 4.
+The resulting array is [1,2,3,4], which is continuous.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor.cpp new file mode 100644 index 00000000..89923009 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + + const int mod = 1e9+7; + + int numberOfWays(string corridor) { + + int n = corridor.size(); + + int cnt = count(corridor.begin(), corridor.end(), 'S'); + + if(!cnt or cnt & 1) return 0; + + int inc = 0; + + vector v; + + int currCnt = 0; + + for(int i = 0; i < n; ++i) + { + if(!cnt) break; + + if(corridor[i] == 'S') + ++currCnt, --cnt; + if(currCnt == 3) + { + v.push_back(inc); + inc = 0; + currCnt = 1; + } + if(currCnt == 2) + (inc = !inc ? 1 : inc+1); + } + + if(currCnt) + { + v.push_back(inc); + } + + long long ans = v[0]; + + for(int i = 1; i < v.size(); ++i) + ans = (ans *1LL* v[i]) % mod; + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/README.md new file mode 100644 index 00000000..da38196d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2147-number-of-ways-to-divide-a-long-corridor/README.md @@ -0,0 +1,42 @@ +

No companies found for this problem
2147. Number of Ways to Divide a Long Corridor

Hard


Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant.

+ +

One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.

+ +

Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.

+ +

Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.

+ +

 

+

Example 1:

+ +
Input: corridor = "SSPPSPS"
+Output: 3
+Explanation: There are 3 different ways to divide the corridor.
+The black bars in the above image indicate the two room dividers already installed.
+Note that in each of the ways, each section has exactly two seats.
+
+ +

Example 2:

+ +
Input: corridor = "PPSPSP"
+Output: 1
+Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers.
+Installing any would create some section that does not have exactly two seats.
+
+ +

Example 3:

+ +
Input: corridor = "S"
+Output: 0
+Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.
+
+ +

 

+

Constraints:

+ +
    +
  • n == corridor.length
  • +
  • 1 <= n <= 105
  • +
  • corridor[i] is either 'S' or 'P'.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom.cpp new file mode 100644 index 00000000..b4d8e152 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& persons) { + vector start, end; + for (auto& t : flowers) + start.push_back(t[0]), end.push_back(t[1]); + sort(start.begin(), start.end()); + sort(end.begin(), end.end()); + vector res; + for (int t : persons) { + int started = upper_bound(start.begin(), start.end(), t) - start.begin(); + int ended = lower_bound(end.begin(), end.end(), t) - end.begin(); + res.push_back(started - ended); + } + return res; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/README.md new file mode 100644 index 00000000..fc333323 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2251-number-of-flowers-in-full-bloom/README.md @@ -0,0 +1,32 @@ +

No companies found for this problem
2251. Number of Flowers in Full Bloom

Hard


You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers.

+ +

Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.

+ +

 

+

Example 1:

+ +
Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11]
+Output: [1,2,2,2]
+Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
+For each person, we return the number of flowers in full bloom during their arrival.
+
+ +

Example 2:

+ +
Input: flowers = [[1,10],[3,3]], poeple = [3,3,2]
+Output: [2,2,1]
+Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
+For each person, we return the number of flowers in full bloom during their arrival.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= flowers.length <= 5 * 104
  • +
  • flowers[i].length == 2
  • +
  • 1 <= starti <= endi <= 109
  • +
  • 1 <= people.length <= 5 * 104
  • +
  • 1 <= people[i] <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string.cpp new file mode 100644 index 00000000..2dc69092 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + string largestGoodInteger(string num) { + + int n = num.size(); + + string ans; + + int i = 0, j = 0, k = 3; + + string curr; + + while(j < n) + { + curr += num[j]; + + if(curr.size() == 3) + { + if(j>=2 and num[j] == num[j-1] and num[j-1] == num[j-2]) + { + ans = max(ans, curr); + } + curr.erase(curr.begin()); + } + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/README.md new file mode 100644 index 00000000..aeb415ac --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2264-largest-3-same-digit-number-in-string/README.md @@ -0,0 +1,47 @@ +

No companies found for this problem
2264. Largest 3-Same-Digit Number in String

Easy


You are given a string num representing a large integer. An integer is good if it meets the following conditions:

+ +
    +
  • It is a substring of num with length 3.
  • +
  • It consists of only one unique digit.
  • +
+ +

Return the maximum good integer as a string or an empty string "" if no such integer exists.

+ +

Note:

+ +
    +
  • A substring is a contiguous sequence of characters within a string.
  • +
  • There may be leading zeroes in num or a good integer.
  • +
+ +

 

+

Example 1:

+ +
Input: num = "6777133339"
+Output: "777"
+Explanation: There are two distinct good integers: "777" and "333".
+"777" is the largest, so we return "777".
+
+ +

Example 2:

+ +
Input: num = "2300019"
+Output: "000"
+Explanation: "000" is the only good integer.
+
+ +

Example 3:

+ +
Input: num = "42352338"
+Output: ""
+Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= num.length <= 1000
  • +
  • num only consists of digits.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree.cpp new file mode 100644 index 00000000..19d7070b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int ans = 0; + + pair helper(TreeNode* root) + { + if(!root) + { + return {0, 0}; + } + + auto left = helper(root->left); + auto right = helper(root->right); + + int sum = left.first + right.first + root->val; + int cnt = left.second + right.second + 1; + + // cout<val<<" " <val) + { + ++ans; + } + + return {sum, cnt}; + } + + int averageOfSubtree(TreeNode* root) { + + helper(root); + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/README.md new file mode 100644 index 00000000..42ee90a0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2265-count-nodes-equal-to-average-of-subtree/README.md @@ -0,0 +1,37 @@ +

No companies found for this problem
2265. Count Nodes Equal to Average of Subtree

Medium


Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.

+ +

Note:

+ +
    +
  • The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
  • +
  • A subtree of root is a tree consisting of root and all of its descendants.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [4,8,5,0,1,null,6]
+Output: 5
+Explanation: 
+For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
+For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
+For the node with value 0: The average of its subtree is 0 / 1 = 0.
+For the node with value 1: The average of its subtree is 1 / 1 = 1.
+For the node with value 6: The average of its subtree is 6 / 1 = 6.
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: 1
+Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage.cpp new file mode 100644 index 00000000..80607765 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + + int n = garbage.size(); + + int totalTime = 0; + + unordered_map mp; + + for(int i = 0; i < n; ++i) + { + for(auto& gar : garbage[i]) + ++mp[gar]; + } + + for(int i = 0; i < n; ++i) + { + int p = 0, g = 0, m = 0; + + for(auto& gar : garbage[i]) + { + if(gar == 'P') + ++p; + else if(gar == 'G') + ++g; + else + ++m; + } + + totalTime += (p+g+m); + + if(i-1 >= 0) + { + if(mp['P']) totalTime += travel[i-1]; + if(mp['G']) totalTime += travel[i-1]; + if(mp['M']) totalTime += travel[i-1]; + } + + mp['P'] -= p; + mp['M'] -= m; + mp['G'] -= g; + + if(mp['P'] == 0) + mp.erase('P'); + if(mp['G'] == 0) + mp.erase('G'); + if(mp['M'] == 0) + mp.erase('M'); + + } + + return totalTime; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/README.md new file mode 100644 index 00000000..b4706728 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2391-minimum-amount-of-time-to-collect-garbage/README.md @@ -0,0 +1,56 @@ +

No companies found for this problem
2391. Minimum Amount of Time to Collect Garbage

Medium


You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.

+ +

You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.

+ +

There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.

+ +

Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.

+ +

Return the minimum number of minutes needed to pick up all the garbage.

+ +

 

+

Example 1:

+ +
Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
+Output: 21
+Explanation:
+The paper garbage truck:
+1. Travels from house 0 to house 1
+2. Collects the paper garbage at house 1
+3. Travels from house 1 to house 2
+4. Collects the paper garbage at house 2
+Altogether, it takes 8 minutes to pick up all the paper garbage.
+The glass garbage truck:
+1. Collects the glass garbage at house 0
+2. Travels from house 0 to house 1
+3. Travels from house 1 to house 2
+4. Collects the glass garbage at house 2
+5. Travels from house 2 to house 3
+6. Collects the glass garbage at house 3
+Altogether, it takes 13 minutes to pick up all the glass garbage.
+Since there is no metal garbage, we do not need to consider the metal garbage truck.
+Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.
+
+ +

Example 2:

+ +
Input: garbage = ["MMM","PGM","GP"], travel = [3,10]
+Output: 37
+Explanation:
+The metal garbage truck takes 7 minutes to pick up all the metal garbage.
+The paper garbage truck takes 15 minutes to pick up all the paper garbage.
+The glass garbage truck takes 15 minutes to pick up all the glass garbage.
+It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= garbage.length <= 105
  • +
  • garbage[i] consists of only the letters 'M', 'P', and 'G'.
  • +
  • 1 <= garbage[i].length <= 10
  • +
  • travel.length == garbage.length - 1
  • +
  • 1 <= travel[i] <= 100
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor.cpp new file mode 100644 index 00000000..1151b9bd --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector findArray(vector& pref) { + + int n = pref.size(); + + vector ans(n); + + ans[0] = pref[0]; + + for(int i = 1; i < n; ++i) + ans[i] = pref[i] ^ pref[i-1]; + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/README.md new file mode 100644 index 00000000..a6752d89 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2433-find-the-original-array-of-prefix-xor/README.md @@ -0,0 +1,38 @@ +

No companies found for this problem
2433. Find The Original Array of Prefix Xor

Medium


You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:

+ +
    +
  • pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
  • +
+ +

Note that ^ denotes the bitwise-xor operation.

+ +

It can be proven that the answer is unique.

+ +

 

+

Example 1:

+ +
Input: pref = [5,2,0,3,1]
+Output: [5,7,2,3,2]
+Explanation: From the array [5,7,2,3,2] we have the following:
+- pref[0] = 5.
+- pref[1] = 5 ^ 7 = 2.
+- pref[2] = 5 ^ 7 ^ 2 = 0.
+- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
+- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
+
+ +

Example 2:

+ +
Input: pref = [13]
+Output: [13]
+Explanation: We have pref[0] = arr[0] = 13.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pref.length <= 105
  • +
  • 0 <= pref[i] <= 106
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator.cpp new file mode 100644 index 00000000..b46998f3 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator.cpp @@ -0,0 +1,76 @@ +class Graph { +public: + + vector > adj[105]; + + int dijistras(int src, int dest) + { + vector dist(105, INT_MAX); + + priority_queue, vector>, greater> > pq; + + dist[src] = 0; + + pq.push({dist[src], src}); + + while(!pq.empty()) + { + pair curr = pq.top(); + pq.pop(); + + int distance = curr.first; + int node = curr.second; + + if(node == dest) + { + return distance; + } + + for(auto& child : adj[node]) + { + if(distance + child.second < dist[child.first]) + { + dist[child.first] = distance + child.second; + + pq.push({dist[child.first], child.first}); + } + } + } + return -1; + } + + Graph(int n, vector>& edges) { + + for(auto& edge : edges) + { + int u = edge[0]; + int v = edge[1]; + int wt = edge[2]; + + adj[u].push_back({v, wt}); + } + } + + void addEdge(vector edge) { + + int u = edge[0]; + int v = edge[1]; + int wt = edge[2]; + + adj[u].push_back({v, wt}); + + } + + int shortestPath(int node1, int node2) { + + return dijistras(node1, node2); + + } +}; + +/** + * Your Graph object will be instantiated and called as such: + * Graph* obj = new Graph(n, edges); + * obj->addEdge(edge); + * int param_2 = obj->shortestPath(node1,node2); + */ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/README.md new file mode 100644 index 00000000..09d240cb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2642-design-graph-with-shortest-path-calculator/README.md @@ -0,0 +1,41 @@ +

No companies found for this problem
2642. Design Graph With Shortest Path Calculator

Hard


There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.

+ +

Implement the Graph class:

+ +
    +
  • Graph(int n, int[][] edges) initializes the object with n nodes and the given edges.
  • +
  • addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one.
  • +
  • int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"]
+[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]]
+Output
+[null, 6, -1, null, 6]
+
+Explanation
+Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);
+g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6.
+g.shortestPath(0, 3); // return -1. There is no path from 0 to 3.
+g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above.
+g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 0 <= edges.length <= n * (n - 1)
  • +
  • edges[i].length == edge.length == 3
  • +
  • 0 <= fromi, toi, from, to, node1, node2 <= n - 1
  • +
  • 1 <= edgeCosti, edgeCost <= 106
  • +
  • There are no repeated edges and no self-loops in the graph at any point.
  • +
  • At most 100 calls will be made for addEdge.
  • +
  • At most 100 calls will be made for shortestPath.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/README.md new file mode 100644 index 00000000..b6396262 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2742-painting-the-walls/README.md @@ -0,0 +1,34 @@ +

No companies found for this problem
2742. Painting the Walls

Hard


You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:

+ +
    +
  • A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of money.
  • +
  • A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied.
  • +
+ +

Return the minimum amount of money required to paint the n walls.

+ +

 

+

Example 1:

+ +
Input: cost = [1,2,3,2], time = [1,2,3,2]
+Output: 3
+Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
+
+ +

Example 2:

+ +
Input: cost = [2,3,4,2], time = [1,1,1,1]
+Output: 4
+Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= cost.length <= 500
  • +
  • cost.length == time.length
  • +
  • 1 <= cost[i] <= 106
  • +
  • 1 <= time[i] <= 500
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string.cpp new file mode 100644 index 00000000..f6265c5a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string sortVowels(string s) { + + string vowels; + + auto isVowel = [&](char ch) + { + return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u' or ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U'); + }; + + for(auto& ch : s) + { + if(isVowel(ch)) + vowels += ch; + } + + sort(vowels.begin(), vowels.end()); + + int i = 0; + + for(auto& ch : s) + { + if(isVowel(ch)) + ch = vowels[i++]; + } + + return s; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/README.md new file mode 100644 index 00000000..c4634ae8 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2785-sort-vowels-in-a-string/README.md @@ -0,0 +1,34 @@ +

No companies found for this problem
2785. Sort Vowels in a String

Medium


Given a 0-indexed string s, permute s to get a new string t such that:

+ +
    +
  • All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].
  • +
  • The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].
  • +
+ +

Return the resulting string.

+ +

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

+ +

 

+

Example 1:

+ +
Input: s = "lEetcOde"
+Output: "lEOtcede"
+Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
+
+ +

Example 2:

+ +
Input: s = "lYmpH"
+Output: "lYmpH"
+Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists only of letters of the English alphabet in uppercase and lowercase.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp new file mode 100644 index 00000000..e87e582f --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + + int xDiff = abs(sx - fx); + int yDiff = abs(sy - fy); + + int diagonalDist = min(xDiff, yDiff); + + if(sx == fx and sy == fy and t == 1) + return false; + + int minDist = diagonalDist + abs(xDiff - yDiff); + + return minDist <= t; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md new file mode 100644 index 00000000..13a5881b --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md @@ -0,0 +1,31 @@ +

No companies found for this problem
2849. Determine if a Cell Is Reachable at a Given Time

Medium


You are given four integers sx, sy, fx, fy, and a non-negative integer t.

+ +

In an infinite 2D grid, you start at the cell (sx, sy). Each second, you must move to any of its adjacent cells.

+ +

Return true if you can reach cell (fx, fy) after exactly t seconds, or false otherwise.

+ +

A cell's adjacent cells are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.

+ +

 

+

Example 1:

+ +
Input: sx = 2, sy = 4, fx = 7, fy = 7, t = 6
+Output: true
+Explanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. 
+
+ +

Example 2:

+ +
Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3
+Output: false
+Explanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= sx, sy, fx, fy <= 109
  • +
  • 0 <= t <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph.cpp new file mode 100644 index 00000000..878be0de --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph.cpp @@ -0,0 +1,84 @@ +class Solution { +public: + vector countVisitedNodes(vector& edges) { + + int n = edges.size(); + + vector indegree(n, 0); + + for(int i = 0; i < n; ++i) + { + ++indegree[edges[i]]; + } + + vector visited(n, false); + + queue q; + stack st; + + for(int i = 0; i < n; ++i) + { + if(indegree[i] == 0) + { + q.push(i); + } + } + + while(!q.empty()) + { + int curr = q.front(); + visited[curr] = true; + st.push(curr); + q.pop(); + + if(--indegree[edges[curr]] == 0) + { + q.push(edges[curr]); + } + } + + vector res(n, 0); + + function dfs = [&](int sv) + { + int length = 0; + + for(int i = sv; !visited[i]; i = edges[i]) + { + visited[i] = true; + ++length; + } + + res[sv] = length; + + for(int i = edges[sv]; i != sv; i = edges[i]) + { + res[i] = length; + } + }; + + for(int i = 0; i < n; ++i) + { + if(!visited[i]) + { + dfs(i); + } + } + + for(int i = 0; i < n; ++i) + { + if(!visited[i]) + dfs(i); + } + + while(!st.empty()) + { + int curr = st.top(); + res[curr] = res[edges[curr]] + 1; + st.pop(); + } + + return res; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/README.md new file mode 100644 index 00000000..a4dcde69 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2876-count-visited-nodes-in-a-directed-graph/README.md @@ -0,0 +1,41 @@ +

No companies found for this problem
2876. Count Visited Nodes in a Directed Graph

Hard


There is a directed graph consisting of n nodes numbered from 0 to n - 1 and n directed edges.

+ +

You are given a 0-indexed array edges where edges[i] indicates that there is an edge from node i to node edges[i].

+ +

Consider the following process on the graph:

+ +
    +
  • You start from a node x and keep visiting other nodes through edges until you reach a node that you have already visited before on this same process.
  • +
+ +

Return an array answer where answer[i] is the number of different nodes that you will visit if you perform the process starting from node i.

+ +

 

+

Example 1:

+ +
Input: edges = [1,2,0,0]
+Output: [3,3,3,4]
+Explanation: We perform the process starting from each node in the following way:
+- Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3.
+- Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3.
+- Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3.
+- Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4.
+
+ +

Example 2:

+ +
Input: edges = [1,2,3,4,0]
+Output: [5,5,5,5,5]
+Explanation: Starting from any node we can visit every node in the graph in the process.
+
+ +

 

+

Constraints:

+ +
    +
  • n == edges.length
  • +
  • 2 <= n <= 105
  • +
  • 0 <= edges[i] <= n - 1
  • +
  • edges[i] != i
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful.cpp new file mode 100644 index 00000000..3bde932d --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + long long helper(int idx, int n, vector& nums, int k, vector& dp) + { + if(idx >= n) + return 0; + + long long ans = LONG_MAX; + + if(dp[idx] != -1) + return dp[idx]; + + for(int i = 0; i < 3 and idx + i < n; ++i) + { + long long take = (nums[idx] < k ? k - nums[idx] : 0) + helper(idx+i+1, n, nums, k , dp); + + ans = min(ans, take); + } + + return dp[idx] = ans; + } + + long long minIncrementOperations(vector& nums, int k) { + + int n = nums.size(); + + vector dp(n+1, -1); + + long long op1 = helper(0, n, nums, k, dp); + long long op2 = helper(1, n, nums, k, dp); + long long op3 = helper(2, n, nums, k, dp); + + return min({op1, op2, op3}); + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/README.md new file mode 100644 index 00000000..c5ad89b8 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2919-minimum-increment-operations-to-make-array-beautiful/README.md @@ -0,0 +1,60 @@ +

No companies found for this problem
2919. Minimum Increment Operations to Make Array Beautiful

Medium


You are given a 0-indexed integer array nums having length n, and an integer k.

+ +

You can perform the following increment operation any number of times (including zero):

+ +
    +
  • Choose an index i in the range [0, n - 1], and increase nums[i] by 1.
  • +
+ +

An array is considered beautiful if, for any subarray with a size of 3 or more, its maximum element is greater than or equal to k.

+ +

Return an integer denoting the minimum number of increment operations needed to make nums beautiful.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,0,0,2], k = 4
+Output: 3
+Explanation: We can perform the following increment operations to make nums beautiful:
+Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
+Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
+Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
+The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
+In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
+It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
+Hence, the answer is 3.
+
+ +

Example 2:

+ +
Input: nums = [0,1,3,3], k = 5
+Output: 2
+Explanation: We can perform the following increment operations to make nums beautiful:
+Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
+Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
+The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
+In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
+It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
+Hence, the answer is 2.
+
+ +

Example 3:

+ +
Input: nums = [1,1,2], k = 1
+Output: 0
+Explanation: The only subarray with a size of 3 or more in this example is [1,1,2].
+The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
+Hence, the answer is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n == nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
  • 0 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii.cpp new file mode 100644 index 00000000..53c005cb --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii.cpp @@ -0,0 +1,42 @@ +#define ll long long + +class Solution { +public: + long long beautifulSubstrings(string s, int k) { + + int n = s.size(); + + function isVowel = [&](char ch) + { + return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'); + }; + + unordered_map > mp; + + ll ans = 0; + + ++mp[0][0]; + + ll pref = 0, vow = 0; + + for(int i = 0; i < n; ++i) + { + if(isVowel(s[i])) + ++pref, ++vow; + else + --pref; + + for(auto& [f, cnt] : mp[pref]) + { + ll curr = (vow%k) - f; + if((curr * curr) % k == 0) + ans += cnt; + } + + ++mp[pref][vow%k]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/README.md new file mode 100644 index 00000000..f8de40bc --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div2949-count-beautiful-substrings-ii/README.md @@ -0,0 +1,59 @@ +

No companies found for this problem
2949. Count Beautiful Substrings II

Hard


You are given a string s and a positive integer k.

+ +

Let vowels and consonants be the number of vowels and consonants in a string.

+ +

A string is beautiful if:

+ +
    +
  • vowels == consonants.
  • +
  • (vowels * consonants) % k == 0, in other terms the multiplication of vowels and consonants is divisible by k.
  • +
+ +

Return the number of non-empty beautiful substrings in the given string s.

+ +

A substring is a contiguous sequence of characters in a string.

+ +

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

+ +

Consonant letters in English are every letter except vowels.

+ +

 

+

Example 1:

+ +
Input: s = "baeyh", k = 2
+Output: 2
+Explanation: There are 2 beautiful substrings in the given string.
+- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]).
+You can see that string "aeyh" is beautiful as vowels == consonants and vowels * consonants % k == 0.
+- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]).
+You can see that string "baey" is beautiful as vowels == consonants and vowels * consonants % k == 0.
+It can be shown that there are only 2 beautiful substrings in the given string.
+
+ +

Example 2:

+ +
Input: s = "abba", k = 1
+Output: 3
+Explanation: There are 3 beautiful substrings in the given string.
+- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).
+- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).
+- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]).
+It can be shown that there are only 3 beautiful substrings in the given string.
+
+ +

Example 3:

+ +
Input: s = "bcdf", k = 1
+Output: 0
+Explanation: There are no beautiful substrings in the given string.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • 1 <= k <= 1000
  • +
  • s consists of only English lowercase letters.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array.cpp new file mode 100644 index 00000000..16bba9d0 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array.cpp @@ -0,0 +1,72 @@ +class Solution { +public: + + int binarySearchFirst(vector& nums, int target) + { + int start = 0, end = nums.size()-1; + + int first = - 1; + + while(start <= end) + { + int mid = start + (end - start)/ 2; + + if(nums[mid] == target) + { + first = mid; + end = mid-1; + } + else if(nums[mid] < target) + { + start = mid+1; + } + else + { + end = mid - 1; + } + } + + return first; + } + + int binarySearchEnd(vector& nums, int target) + { + int start = 0, end = nums.size()-1; + + int last = -1; + + while(start <= end) + { + int mid = start + (end - start)/ 2; + + if(nums[mid] == target) + { + last = mid; + start = mid+1; + } + else if(nums[mid] > target) + { + end = mid-1; + } + else + { + start = mid+1; + } + } + + return last; + } + + vector searchRange(vector& nums, int target) { + + int n = nums.size(); + + int first = -1, last = -1; + + first = binarySearchFirst(nums, target); + last = binarySearchEnd(nums, target); + + return {first, last}; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/README.md new file mode 100644 index 00000000..30176ded --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div34-find-first-and-last-position-of-element-in-sorted-array/README.md @@ -0,0 +1,27 @@ +

No companies found for this problem
34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

+ +

If target is not found in the array, return [-1, -1].

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [5,7,7,8,8,10], target = 8
+Output: [3,4]
+

Example 2:

+
Input: nums = [5,7,7,8,8,10], target = 6
+Output: [-1,-1]
+

Example 3:

+
Input: nums = [], target = 0
+Output: [-1,-1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • nums is a non-decreasing array.
  • +
  • -109 <= target <= 109
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs.cpp new file mode 100644 index 00000000..c9a68d06 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + + // trial^pigs = buckets + + return ceil(log2(buckets) / log2(minutesToTest / minutesToDie + 1)); + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/README.md new file mode 100644 index 00000000..5b73b537 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div458-poor-pigs/README.md @@ -0,0 +1,48 @@ +

No companies found for this problem
458. Poor Pigs

Hard


There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

+ +

You can feed the pigs according to these steps:

+ +
    +
  1. Choose some live pigs to feed.
  2. +
  3. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
  4. +
  5. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  6. +
  7. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  8. +
  9. Repeat this process until you run out of time.
  10. +
+ +

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

+ +

 

+

Example 1:

+ +
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
+Output: 2
+Explanation: We can determine the poisonous bucket as follows:
+At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
+At time 15, there are 4 possible outcomes:
+- If only the first pig dies, then bucket 1 must be poisonous.
+- If only the second pig dies, then bucket 3 must be poisonous.
+- If both pigs die, then bucket 2 must be poisonous.
+- If neither pig dies, then bucket 4 must be poisonous.
+
+ +

Example 2:

+ +
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
+Output: 2
+Explanation: We can determine the poisonous bucket as follows:
+At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
+At time 15, there are 2 possible outcomes:
+- If either pig dies, then the poisonous bucket is the one it was fed.
+- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
+At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= buckets <= 1000
  • +
  • 1 <= minutesToDie <= minutesToTest <= 100
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree.cpp new file mode 100644 index 00000000..e9971d98 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree.cpp @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, unordered_map& mp, int& maxi) + { + if(root) + { + helper(root->left, mp, maxi); + ++mp[root->val]; + maxi = max(maxi, mp[root->val]); + helper(root->right, mp, maxi); + } + } + + vector findMode(TreeNode* root) { + + unordered_map mp; + + int maxi = 0; + + helper(root, mp, maxi); + + vector ans; + + for(auto& itr : mp) + { + if(itr.second == maxi) + ans.push_back(itr.first); + } + + return ans; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/README.md new file mode 100644 index 00000000..184716c6 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div501-find-mode-in-binary-search-tree/README.md @@ -0,0 +1,35 @@ +

No companies found for this problem
501. Find Mode in Binary Search Tree

Easy


Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

+ +

If the tree has more than one mode, return them in any order.

+ +

Assume a BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,2]
+Output: [2]
+
+ +

Example 2:

+ +
Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ +

 

+Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes.cpp new file mode 100644 index 00000000..fd1cd0af --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + int numBusesToDestination(vector>& routes, int source, int target) { + + if(source == target) + return 0; + + unordered_map> adj; + + for(int route = 0; route < routes.size(); ++route) + { + for(auto& stop : routes[route]) + { + adj[stop].push_back(route); + } + } + + queue q; + + unordered_set visited; + + for(auto& route : adj[source]) + { + q.push(route); + visited.insert(route); + } + + int bus = 1; + + while(!q.empty()) + { + int size = q.size(); + + while(size--) + { + int route = q.front(); + q.pop(); + + for(auto& stop : routes[route]) + { + if(stop == target) + return bus; + + for(auto& nextRoute : adj[stop]) + { + if(visited.count(nextRoute)) + continue; + q.push(nextRoute); + visited.insert(nextRoute); + } + } + } + ++bus; + } + + return -1; + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/README.md new file mode 100644 index 00000000..6d9ea192 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div815-bus-routes/README.md @@ -0,0 +1,36 @@ +

No companies found for this problem
815. Bus Routes

Hard


You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.

+ +
    +
  • For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
  • +
+ +

You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.

+ +

Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

+ +

 

+

Example 1:

+ +
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
+Output: 2
+Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
+
+ +

Example 2:

+ +
Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= routes.length <= 500.
  • +
  • 1 <= routes[i].length <= 105
  • +
  • All the values of routes[i] are unique.
  • +
  • sum(routes[i].length) <= 105
  • +
  • 0 <= routes[i][j] < 106
  • +
  • 0 <= source, target < 106
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes.cpp new file mode 100644 index 00000000..a9571d67 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + int shortestPathLength(vector>& graph) { + + int n = graph.size(); + + if(n == 1) + return 0; + + queue > q; + + set > visited; + + int allVisited = (1 << n) - 1; + + for(int i = 0; i < n; ++i) + { + int mask = 1 << i; + + q.push({i, mask}); + + visited.insert({i, mask}); + } + + int path = 0; + + while(!q.empty()) + { + int size = q.size(); + + ++path; + + while(size--) + { + auto curr = q.front(); + q.pop(); + + int node = curr.first; + int mask = curr.second; + + for(auto& adjNode : graph[node]) + { + int newMask = mask | (1 << adjNode); + + if(newMask == allVisited) + return path; + + if(!visited.count({adjNode, newMask})) + { + q.push({adjNode, newMask}); + visited.insert({adjNode, newMask}); + } + } + } + } + + return -1; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/README.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/README.md new file mode 100644 index 00000000..6635b22a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div847-shortest-path-visiting-all-nodes/README.md @@ -0,0 +1,31 @@ +

No companies found for this problem
847. Shortest Path Visiting All Nodes

Hard


You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.

+ +

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

+ +

 

+

Example 1:

+ +
Input: graph = [[1,2,3],[0],[0],[0]]
+Output: 4
+Explanation: One possible path is [1,0,2,0,3]
+
+ +

Example 2:

+ +
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
+Output: 4
+Explanation: One possible path is [0,1,4,2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • 1 <= n <= 12
  • +
  • 0 <= graph[i].length < n
  • +
  • graph[i] does not contain i.
  • +
  • If graph[a] contains b, then graph[b] contains a.
  • +
  • The input graph is always connected.
  • +
+
\ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity.cpp b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity.cpp new file mode 100644 index 00000000..6455ee55 --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector sortArrayByParity(vector& nums) { + + int n = nums.size(); + + int start = 0, end = n-1; + + while(start < end) + { + if(nums[start] & 1) + { + swap(nums[start], nums[end--]); + } + else + ++start; + } + + return nums; + + } +}; \ No newline at end of file diff --git a/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/NOTES.md b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/0div-idbig-omega-company-tagsdiv-idbig-omega-topbardiv-classcompanytagscontainer-styleoverflow-x-scroll-flex-wrap-nowrap-div-classcompanytagscontainer-tagno-companies-found-for-this-problem-div-divdiv-classcompanytagscontainer-chevrondivsvg-version11-idicon-xmlnshttp-wwww3org-2000-svg-xmlns-xlinkhttp-wwww3org-1999-xlink-x0px-y0px-viewbox0-0-32-32-fill4087f1-xml-spacepreserve-stylewidth-20px-polygon-points16-22-6-12-74-106-16-192-246-106-26-12-polygonrect-id-x3c-transparent-rectangle-x3e-classst0-fillnone-width32-height32-rect-svg-div-div-div-div905-sort-array-by-parity/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1002-find-common-characters/1002-find-common-characters.cpp b/1002-find-common-characters/1002-find-common-characters.cpp new file mode 100644 index 00000000..f2254e0a --- /dev/null +++ b/1002-find-common-characters/1002-find-common-characters.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector commonChars(vector& words) { + + int n = words.size(); + + vector freq(26, 0); + + for(int i = 0; i < n; ++i) + { + vector curr(26, 0); + + for(int j = 0; j < words[i].size(); ++j) + ++curr[words[i][j] - 'a']; + + if(i != 0) + { + for(int j = 0; j < 26; ++j) + curr[j] = min(curr[j], freq[j]); + } + + freq = curr; + } + + vector ans; + + for(int i = 0; i < 26; ++i) + { + for(int j = 0; j < freq[i]; ++j) + { + ans.push_back(string(1, 'a' + i)); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1002-find-common-characters/NOTES.md b/1002-find-common-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1002-find-common-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1002-find-common-characters/README.md b/1002-find-common-characters/README.md new file mode 100644 index 00000000..54c8be40 --- /dev/null +++ b/1002-find-common-characters/README.md @@ -0,0 +1,19 @@ +

1002. Find Common Characters

Easy


Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

+ +

 

+

Example 1:

+
Input: words = ["bella","label","roller"]
+Output: ["e","l","l"]
+

Example 2:

+
Input: words = ["cool","lock","cook"]
+Output: ["c","o"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp b/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp new file mode 100644 index 00000000..b2d6bfa9 --- /dev/null +++ b/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + + int n = nums.size(); + + int i = 0, j = 0, zeroCnt = 0, ans = 0; + + while(j < n) + { + zeroCnt += (nums[j] == 0 ? 1 : 0); + + while(zeroCnt > k) + { + zeroCnt -= (nums[i] == 0 ? 1 : 0); + ++i; + } + + ans = max(ans, j - i + 1); + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1004-max-consecutive-ones-iii/NOTES.md b/1004-max-consecutive-ones-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1004-max-consecutive-ones-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp b/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp new file mode 100644 index 00000000..296a59ae --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/1010-pairs-of-songs-with-total-durations-divisible-by-60.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + + vector songFreq(60, 0); + + int counter = 0; + + for(auto& songTime : time) + { + counter += songFreq[(60 - (songTime % 60)) % 60]; + + ++songFreq[songTime%60]; + } + + return counter; + } +}; \ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md b/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md b/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md new file mode 100644 index 00000000..7dc115db --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60/README.md @@ -0,0 +1,30 @@ +

1010. Pairs of Songs With Total Durations Divisible by 60

Medium


You are given a list of songs where the ith song has a duration of time[i] seconds.

+ +

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

+ +

 

+

Example 1:

+ +
Input: time = [30,20,150,100,40]
+Output: 3
+Explanation: Three pairs have a total duration divisible by 60:
+(time[0] = 30, time[2] = 150): total duration 180
+(time[1] = 20, time[3] = 100): total duration 120
+(time[1] = 20, time[4] = 40): total duration 60
+
+ +

Example 2:

+ +
Input: time = [60,60,60]
+Output: 3
+Explanation: All three pairs have a total duration of 120, which is divisible by 60.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= time.length <= 6 * 104
  • +
  • 1 <= time[i] <= 500
  • +
+
\ No newline at end of file diff --git a/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp b/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp new file mode 100644 index 00000000..56072fbf --- /dev/null +++ b/1011-capacity-to-ship-packages-within-d-days/1011-capacity-to-ship-packages-within-d-days.cpp @@ -0,0 +1,51 @@ +#define ll long long int +class Solution { +public: + + int helper(vector& weights, int mid, int days) + { + ll sum = 0; + int cnt = 1; + int n = weights.size(); + + for(int i = 0; i mid) + return false; + else if(sum + weights[i] > mid) + { + sum = weights[i]; + ++cnt; + } + else + sum += weights[i]; + } + + return (cnt <= days); + } + + int shipWithinDays(vector& weights, int days) { + + ll sum = accumulate(weights.begin(),weights.end(),0); + int mini = *min_element(weights.begin(),weights.end()); + + ll low = mini , high = sum; + ll ans; + + while(low <= high) + { + ll mid = low + (high - low)/2; + + if(helper(weights,mid,days)) + { + ans = mid; + high = mid - 1; + } + else + low = mid + 1; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1011-capacity-to-ship-packages-within-d-days/NOTES.md b/1011-capacity-to-ship-packages-within-d-days/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1011-capacity-to-ship-packages-within-d-days/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1011-capacity-to-ship-packages-within-d-days/README.md b/1011-capacity-to-ship-packages-within-d-days/README.md new file mode 100644 index 00000000..fc96f7e9 --- /dev/null +++ b/1011-capacity-to-ship-packages-within-d-days/README.md @@ -0,0 +1,49 @@ +

1011. Capacity To Ship Packages Within D Days

Medium


A conveyor belt has packages that must be shipped from one port to another within days days.

+ +

The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

+ +

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

+ +

 

+

Example 1:

+ +
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
+Output: 15
+Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
+1st day: 1, 2, 3, 4, 5
+2nd day: 6, 7
+3rd day: 8
+4th day: 9
+5th day: 10
+
+Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
+
+ +

Example 2:

+ +
Input: weights = [3,2,2,4,1,4], days = 3
+Output: 6
+Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
+1st day: 3, 2
+2nd day: 2, 4
+3rd day: 1, 4
+
+ +

Example 3:

+ +
Input: weights = [1,2,3,1,1], days = 4
+Output: 3
+Explanation:
+1st day: 1
+2nd day: 2
+3rd day: 3
+4th day: 1, 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= days <= weights.length <= 5 * 104
  • +
  • 1 <= weights[i] <= 500
  • +
\ No newline at end of file diff --git a/1020-number-of-enclaves/1020-number-of-enclaves.cpp b/1020-number-of-enclaves/1020-number-of-enclaves.cpp new file mode 100644 index 00000000..c94761f5 --- /dev/null +++ b/1020-number-of-enclaves/1020-number-of-enclaves.cpp @@ -0,0 +1,76 @@ +class Solution { +public: + int numEnclaves(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector> visited(n, vector(m, false)); + + queue> q; + + for(int i = 0; i < n; ++i) + { + if(!visited[i][0] and grid[i][0] == 1) + { + q.push({i,0}); + visited[i][0] = true; + } + if(!visited[i][m-1] and grid[i][m-1] == 1) + { + q.push({i,m-1}); + visited[i][m-1] = true; + } + } + + for(int j = 0; j < m; ++j) + { + if(!visited[0][j] and grid[0][j] == 1) + { + q.push({0,j}); + visited[0][j] = true; + } + if(!visited[n-1][j] and grid[n-1][j] == 1) + { + q.push({n-1,j}); + visited[n-1][j] = true; + } + } + + vector dx = {-1, 0, 0, 1}; + vector dy = {0, -1, +1, 0}; + + while(!q.empty()) + { + int x = q.front().first; + int y = q.front().second; + + q.pop(); + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and !visited[newx][newy] and grid[newx][newy] == 1) + { + visited[newx][newy] = true; + q.push({newx, newy}); + } + } + } + + int cnt = 0; + + for(int i =0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(!visited[i][j] and grid[i][j] == 1) + ++cnt; + } + } + + return cnt; + + } +}; \ No newline at end of file diff --git a/1020-number-of-enclaves/NOTES.md b/1020-number-of-enclaves/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1020-number-of-enclaves/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1020-number-of-enclaves/README.md b/1020-number-of-enclaves/README.md new file mode 100644 index 00000000..b2758cbf --- /dev/null +++ b/1020-number-of-enclaves/README.md @@ -0,0 +1,31 @@ +

1020. Number of Enclaves

Medium


You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

+ +

A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

+ +

Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
+Output: 3
+Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
+
+ +

Example 2:

+ +
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
+Output: 0
+Explanation: All 1s are either on the boundary or can reach the boundary.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • grid[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1026-maximum-difference-between-node-and-ancestor/1026-maximum-difference-between-node-and-ancestor.cpp b/1026-maximum-difference-between-node-and-ancestor/1026-maximum-difference-between-node-and-ancestor.cpp new file mode 100644 index 00000000..170912a6 --- /dev/null +++ b/1026-maximum-difference-between-node-and-ancestor/1026-maximum-difference-between-node-and-ancestor.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int helper(TreeNode* root, int currMax, int currMin) + { + if(!root) + return currMax - currMin; + currMax = max(currMax,root->val); + currMin = min(currMin,root->val); + + int left = helper(root->left,currMax,currMin); + int right = helper(root->right,currMax,currMin); + + return max(left,right); + } + + + int maxAncestorDiff(TreeNode* root) { + + if(!root) + return 0; + + return helper(root,root->val,root->val); + + + } +}; \ No newline at end of file diff --git a/1026-maximum-difference-between-node-and-ancestor/README.md b/1026-maximum-difference-between-node-and-ancestor/README.md new file mode 100644 index 00000000..67c353c5 --- /dev/null +++ b/1026-maximum-difference-between-node-and-ancestor/README.md @@ -0,0 +1,30 @@ +

1026. Maximum Difference Between Node and Ancestor

Medium


Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.

+ +

A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.

+ +

 

+

Example 1:

+ +
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
+Output: 7
+Explanation: We have various ancestor-node differences, some of which are given below :
+|8 - 3| = 5
+|3 - 7| = 4
+|8 - 1| = 7
+|10 - 13| = 3
+Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
+ +

Example 2:

+ +
Input: root = [1,null,2,null,0,3]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 5000].
  • +
  • 0 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/1027-longest-arithmetic-subsequence/1027-longest-arithmetic-subsequence.cpp b/1027-longest-arithmetic-subsequence/1027-longest-arithmetic-subsequence.cpp new file mode 100644 index 00000000..e6fd8d76 --- /dev/null +++ b/1027-longest-arithmetic-subsequence/1027-longest-arithmetic-subsequence.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + + int longestArithSeqLength(vector& nums) { + + int n = nums.size(); + int ans = 0; + + if(n <= 2) + return n; + + unordered_map dp[n+1]; + + for(int i=1;i1027. Longest Arithmetic Subsequence

Medium


Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

+ +

Note that:

+ +
    +
  • A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
  • +
  • A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [3,6,9,12]
+Output: 4
+Explanation:  The whole array is an arithmetic sequence with steps of length = 3.
+
+ +

Example 2:

+ +
Input: nums = [9,4,7,2,10]
+Output: 3
+Explanation:  The longest arithmetic subsequence is [4,7,10].
+
+ +

Example 3:

+ +
Input: nums = [20,1,15,3,10,5,8]
+Output: 4
+Explanation:  The longest arithmetic subsequence is [20,15,10,5].
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 500
  • +
+
\ No newline at end of file diff --git a/1038-binary-search-tree-to-greater-sum-tree/1038-binary-search-tree-to-greater-sum-tree.cpp b/1038-binary-search-tree-to-greater-sum-tree/1038-binary-search-tree-to-greater-sum-tree.cpp new file mode 100644 index 00000000..fd6e8ffc --- /dev/null +++ b/1038-binary-search-tree-to-greater-sum-tree/1038-binary-search-tree-to-greater-sum-tree.cpp @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, int& sum) + { + if(!root) + return; + + helper(root->right, sum); + + root->val += sum; + + sum = root->val; + + helper(root-> left, sum); + } + + TreeNode* bstToGst(TreeNode* root) { + + int sum = 0; + + helper(root, sum); + + return root; + + } +}; \ No newline at end of file diff --git a/1038-binary-search-tree-to-greater-sum-tree/README.md b/1038-binary-search-tree-to-greater-sum-tree/README.md new file mode 100644 index 00000000..c503c670 --- /dev/null +++ b/1038-binary-search-tree-to-greater-sum-tree/README.md @@ -0,0 +1,35 @@ +

1038. Binary Search Tree to Greater Sum Tree

Medium


Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

+ +

As a reminder, a binary search tree is a tree that satisfies these constraints:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
+Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
+
+ +

Example 2:

+ +
Input: root = [0,null,1]
+Output: [1,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 100].
  • +
  • 0 <= Node.val <= 100
  • +
  • All the values in the tree are unique.
  • +
+ +

 

+

Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/

+
\ No newline at end of file diff --git a/1039-minimum-score-triangulation-of-polygon/1039-minimum-score-triangulation-of-polygon.cpp b/1039-minimum-score-triangulation-of-polygon/1039-minimum-score-triangulation-of-polygon.cpp new file mode 100644 index 00000000..25f1e439 --- /dev/null +++ b/1039-minimum-score-triangulation-of-polygon/1039-minimum-score-triangulation-of-polygon.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + + int helper(int i, int j, vector& values, vector>& dp) + { + if(i == j) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + int ans = INT_MAX; + for(int k = i; k < j; ++k) + { + int steps = values[i-1] * values[k] * values[j] + helper(i,k, values, dp) + helper(k+1,j,values, dp); + + ans = min(ans, steps); + } + + return dp[i][j] = ans; + } + + int minScoreTriangulation(vector& values) { + + int n = values.size(); + vector> dp(n+1,vector(n+1,INT_MAX)); + + for(int i = 0; i=1; --i) + { + for(int j = i+1; j1039. Minimum Score Triangulation of Polygon

Medium


You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).

+ +

You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.

+ +

Return the smallest possible total score that you can achieve with some triangulation of the polygon.

+ +

 

+

Example 1:

+ +
Input: values = [1,2,3]
+Output: 6
+Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
+
+ +

Example 2:

+ +
Input: values = [3,7,4,5]
+Output: 144
+Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
+The minimum score is 144.
+
+ +

Example 3:

+ +
Input: values = [1,3,1,4,1,5]
+Output: 13
+Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
+
+ +

 

+

Constraints:

+ +
    +
  • n == values.length
  • +
  • 3 <= n <= 50
  • +
  • 1 <= values[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1043-partition-array-for-maximum-sum/1043-partition-array-for-maximum-sum.cpp b/1043-partition-array-for-maximum-sum/1043-partition-array-for-maximum-sum.cpp new file mode 100644 index 00000000..acd86493 --- /dev/null +++ b/1043-partition-array-for-maximum-sum/1043-partition-array-for-maximum-sum.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + + int helper(int idx, int n, vector& arr, int k, vector& dp) + { + if(idx == n) + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int maxSum = INT_MIN, maxi = INT_MIN, len = 0; + for(int i = idx; i < min(idx + k, n); ++i) + { + ++len; + maxi = max(maxi, arr[i]); + + int sum = len * maxi + helper(i+1, n, arr, k, dp); + + maxSum = max(maxSum, sum); + } + return dp[idx] = maxSum; + } + + int maxSumAfterPartitioning(vector& arr, int k) { + + int n = arr.size(); + // vector dp(n+1,-1); + // return helper(0,n,arr,k,dp); + + vector dp(n+1,0); + dp[n] = 0; + + for(int idx = n-1; idx >= 0; --idx) + { + int maxSum = INT_MIN, maxi = INT_MIN, len = 0; + for(int i = idx; i < min(idx + k, n); ++i) + { + ++len; + maxi = max(maxi, arr[i]); + + int sum = len * maxi + dp[i+1]; + + maxSum = max(maxSum, sum); + } + dp[idx] = maxSum; + } + + return dp[0]; + } +}; \ No newline at end of file diff --git a/1043-partition-array-for-maximum-sum/NOTES.md b/1043-partition-array-for-maximum-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1043-partition-array-for-maximum-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1043-partition-array-for-maximum-sum/README.md b/1043-partition-array-for-maximum-sum/README.md new file mode 100644 index 00000000..c0114e41 --- /dev/null +++ b/1043-partition-array-for-maximum-sum/README.md @@ -0,0 +1,33 @@ +

1043. Partition Array for Maximum Sum

Medium


Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.

+ +

Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.

+ +

 

+

Example 1:

+ +
Input: arr = [1,15,7,9,2,5,10], k = 3
+Output: 84
+Explanation: arr becomes [15,15,15,9,10,10,10]
+
+ +

Example 2:

+ +
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
+Output: 83
+
+ +

Example 3:

+ +
Input: arr = [1], k = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 500
  • +
  • 0 <= arr[i] <= 109
  • +
  • 1 <= k <= arr.length
  • +
+
\ No newline at end of file diff --git a/1046-last-stone-weight/1046-last-stone-weight.cpp b/1046-last-stone-weight/1046-last-stone-weight.cpp new file mode 100644 index 00000000..c5b2e06e --- /dev/null +++ b/1046-last-stone-weight/1046-last-stone-weight.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int lastStoneWeight(vector& stones) { + + priority_queue pq(stones.begin(),stones.end()); + + while(!pq.empty()) + { + int a, b; + + a = pq.top(); + pq.pop(); + + if(pq.empty()) + return a; + else + { + b = pq.top(); + pq.pop(); + } + + if(a == b) + continue; + else + pq.push(a - b); + } + + return 0; + } +}; \ No newline at end of file diff --git a/1046-last-stone-weight/NOTES.md b/1046-last-stone-weight/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1046-last-stone-weight/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1046-last-stone-weight/README.md b/1046-last-stone-weight/README.md new file mode 100644 index 00000000..34945b64 --- /dev/null +++ b/1046-last-stone-weight/README.md @@ -0,0 +1,39 @@ +

1046. Last Stone Weight

Easy


You are given an array of integers stones where stones[i] is the weight of the ith stone.

+ +

We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

+ +
    +
  • If x == y, both stones are destroyed, and
  • +
  • If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
  • +
+ +

At the end of the game, there is at most one stone left.

+ +

Return the weight of the last remaining stone. If there are no stones left, return 0.

+ +

 

+

Example 1:

+ +
Input: stones = [2,7,4,1,8,1]
+Output: 1
+Explanation: 
+We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
+we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
+we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
+we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
+
+ +

Example 2:

+ +
Input: stones = [1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= stones.length <= 30
  • +
  • 1 <= stones[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1051-height-checker/1051-height-checker.cpp b/1051-height-checker/1051-height-checker.cpp new file mode 100644 index 00000000..d54f8363 --- /dev/null +++ b/1051-height-checker/1051-height-checker.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int heightChecker(vector& heights) { + + int n = heights.size(); + + vector copy = heights; + + sort(copy.begin(), copy.end()); + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + cnt += (heights[i] != copy[i]); + } + + return cnt; + + } +}; \ No newline at end of file diff --git a/1051-height-checker/README.md b/1051-height-checker/README.md new file mode 100644 index 00000000..59363b7e --- /dev/null +++ b/1051-height-checker/README.md @@ -0,0 +1,45 @@ +

1051. Height Checker

Easy


A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.

+ +

You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).

+ +

Return the number of indices where heights[i] != expected[i].

+ +

 

+

Example 1:

+ +
Input: heights = [1,1,4,2,1,3]
+Output: 3
+Explanation: 
+heights:  [1,1,4,2,1,3]
+expected: [1,1,1,2,3,4]
+Indices 2, 4, and 5 do not match.
+
+ +

Example 2:

+ +
Input: heights = [5,1,2,3,4]
+Output: 5
+Explanation:
+heights:  [5,1,2,3,4]
+expected: [1,2,3,4,5]
+All indices do not match.
+
+ +

Example 3:

+ +
Input: heights = [1,2,3,4,5]
+Output: 0
+Explanation:
+heights:  [1,2,3,4,5]
+expected: [1,2,3,4,5]
+All indices match.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 100
  • +
  • 1 <= heights[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1052-grumpy-bookstore-owner/1052-grumpy-bookstore-owner.cpp b/1052-grumpy-bookstore-owner/1052-grumpy-bookstore-owner.cpp new file mode 100644 index 00000000..d4f877be --- /dev/null +++ b/1052-grumpy-bookstore-owner/1052-grumpy-bookstore-owner.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + + int helper(int idx, bool flag, int n, int minutes, vector& grumpy, vector& customers, vector& pref, vector>& dp) + { + if(idx >= n) + return 0; + + if(dp[idx][flag] != -1) + return dp[idx][flag]; + + int ans = (grumpy[idx] == 0 ? customers[idx] : 0) + helper(idx+1, flag, n, minutes, grumpy, customers, pref, dp); + + int secretMove = 0; + + if(!flag) + { + secretMove = (idx + minutes - 1 < n ? (pref[idx+minutes-1] - (idx-1 >= 0 ? pref[idx-1] : 0)) : pref[n-1] - (idx-1 >= 0 ? pref[idx-1] : 0)) + helper(idx + minutes, 1, n, minutes, grumpy, customers, pref, dp); + + ans = max(ans, secretMove); + } + + return dp[idx][flag] = ans; + } + + int maxSatisfied(vector& customers, vector& grumpy, int minutes) { + + int n = customers.size(); + + vector> dp(n, vector(2, -1)); + + vector pref(n, 0); + + pref[0] = customers[0]; + + for(int i = 1; i < n; ++i) + { + pref[i] = pref[i-1] + customers[i]; + } + + return helper(0, 0, n, minutes, grumpy, customers, pref, dp); + + } +}; \ No newline at end of file diff --git a/1052-grumpy-bookstore-owner/NOTES.md b/1052-grumpy-bookstore-owner/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1052-grumpy-bookstore-owner/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1052-grumpy-bookstore-owner/README.md b/1052-grumpy-bookstore-owner/README.md new file mode 100644 index 00000000..dce57e16 --- /dev/null +++ b/1052-grumpy-bookstore-owner/README.md @@ -0,0 +1,35 @@ +

1052. Grumpy Bookstore Owner

Medium


There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.

+ +

On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.

+ +

When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.

+ +

The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.

+ +

Return the maximum number of customers that can be satisfied throughout the day.

+ +

 

+

Example 1:

+ +
Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3
+Output: 16
+Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. 
+The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
+
+ +

Example 2:

+ +
Input: customers = [1], grumpy = [0], minutes = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == customers.length == grumpy.length
  • +
  • 1 <= minutes <= n <= 2 * 104
  • +
  • 0 <= customers[i] <= 1000
  • +
  • grumpy[i] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.cpp b/1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.cpp new file mode 100644 index 00000000..30071c25 --- /dev/null +++ b/1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int par[26]; + + int find(int x){ + if(par[x]==-1) return x; + return par[x]=find(par[x]); + } + + void Union(int x, int y) { + x = find(x); + y = find(y); + + if (x != y) + par[max(x, y)] = min(x, y); + } + + string smallestEquivalentString(string s1, string s2, string baseStr) { + + memset(par, -1, sizeof(par)); + + for (auto i = 0; i < s1.size(); ++i) + Union(s1[i] - 'a', s2[i] - 'a'); + + for(auto i=0;i1061. Lexicographically Smallest Equivalent String

Medium


You are given two strings of the same length s1 and s2 and a string baseStr.

+ +

We say s1[i] and s2[i] are equivalent characters.

+ +
    +
  • For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.
  • +
+ +

Equivalent characters follow the usual rules of any equivalence relation:

+ +
    +
  • Reflexivity: 'a' == 'a'.
  • +
  • Symmetry: 'a' == 'b' implies 'b' == 'a'.
  • +
  • Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.
  • +
+ +

For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.

+ +

Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.

+ +

 

+

Example 1:

+ +
Input: s1 = "parker", s2 = "morris", baseStr = "parser"
+Output: "makkek"
+Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].
+The characters in each group are equivalent and sorted in lexicographical order.
+So the answer is "makkek".
+
+ +

Example 2:

+ +
Input: s1 = "hello", s2 = "world", baseStr = "hold"
+Output: "hdld"
+Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].
+So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".
+
+ +

Example 3:

+ +
Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
+Output: "aauaaaaada"
+Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s1.length, s2.length, baseStr <= 1000
  • +
  • s1.length == s2.length
  • +
  • s1, s2, and baseStr consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1068-product-sales-analysis-i/1068-product-sales-analysis-i.sql b/1068-product-sales-analysis-i/1068-product-sales-analysis-i.sql new file mode 100644 index 00000000..e4ba918b --- /dev/null +++ b/1068-product-sales-analysis-i/1068-product-sales-analysis-i.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below + + +select Product.product_name, Sales.year, Sales.price from Sales +inner join Product on +Sales.product_id = Product.product_id; \ No newline at end of file diff --git a/1068-product-sales-analysis-i/NOTES.md b/1068-product-sales-analysis-i/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1068-product-sales-analysis-i/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1068-product-sales-analysis-i/README.md b/1068-product-sales-analysis-i/README.md new file mode 100644 index 00000000..cfcc2de3 --- /dev/null +++ b/1068-product-sales-analysis-i/README.md @@ -0,0 +1,73 @@ +

1068. Product Sales Analysis I

Easy


Table: Sales

+ +
+-------------+-------+
+| Column Name | Type  |
++-------------+-------+
+| sale_id     | int   |
+| product_id  | int   |
+| year        | int   |
+| quantity    | int   |
+| price       | int   |
++-------------+-------+
+(sale_id, year) is the primary key (combination of columns with unique values) of this table.
+product_id is a foreign key (reference column) to Product table.
+Each row of this table shows a sale on the product product_id in a certain year.
+Note that the price is per unit.
+
+ +

 

+ +

Table: Product

+ +
+--------------+---------+
+| Column Name  | Type    |
++--------------+---------+
+| product_id   | int     |
+| product_name | varchar |
++--------------+---------+
+product_id is the primary key (column with unique values) of this table.
+Each row of this table indicates the product name of each product.
+
+ +

 

+ +

Write a solution to report the product_name, year, and price for each sale_id in the Sales table.

+ +

Return the resulting table in any order.

+ +

The result format is in the following example.

+ +

 

+

Example 1:

+ +
Input: 
+Sales table:
++---------+------------+------+----------+-------+
+| sale_id | product_id | year | quantity | price |
++---------+------------+------+----------+-------+ 
+| 1       | 100        | 2008 | 10       | 5000  |
+| 2       | 100        | 2009 | 12       | 5000  |
+| 7       | 200        | 2011 | 15       | 9000  |
++---------+------------+------+----------+-------+
+Product table:
++------------+--------------+
+| product_id | product_name |
++------------+--------------+
+| 100        | Nokia        |
+| 200        | Apple        |
+| 300        | Samsung      |
++------------+--------------+
+Output: 
++--------------+-------+-------+
+| product_name | year  | price |
++--------------+-------+-------+
+| Nokia        | 2008  | 5000  |
+| Nokia        | 2009  | 5000  |
+| Apple        | 2011  | 9000  |
++--------------+-------+-------+
+Explanation: 
+From sale_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008.
+From sale_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009.
+From sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011.
+
+
\ No newline at end of file diff --git a/1071-greatest-common-divisor-of-strings/1071-greatest-common-divisor-of-strings.cpp b/1071-greatest-common-divisor-of-strings/1071-greatest-common-divisor-of-strings.cpp new file mode 100644 index 00000000..e8bee77c --- /dev/null +++ b/1071-greatest-common-divisor-of-strings/1071-greatest-common-divisor-of-strings.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + string gcdOfStrings(string str1, string str2) { + + if(str1 + str2 != str2 + str1) + return ""; + + return str1.substr(0, __gcd(size(str1), size(str2))); + + } +}; \ No newline at end of file diff --git a/1071-greatest-common-divisor-of-strings/NOTES.md b/1071-greatest-common-divisor-of-strings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1071-greatest-common-divisor-of-strings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1071-greatest-common-divisor-of-strings/README.md b/1071-greatest-common-divisor-of-strings/README.md new file mode 100644 index 00000000..67a8a3af --- /dev/null +++ b/1071-greatest-common-divisor-of-strings/README.md @@ -0,0 +1,31 @@ +

1071. Greatest Common Divisor of Strings

Easy


For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).

+ +

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

+ +

 

+

Example 1:

+ +
Input: str1 = "ABCABC", str2 = "ABC"
+Output: "ABC"
+
+ +

Example 2:

+ +
Input: str1 = "ABABAB", str2 = "ABAB"
+Output: "AB"
+
+ +

Example 3:

+ +
Input: str1 = "LEET", str2 = "CODE"
+Output: ""
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= str1.length, str2.length <= 1000
  • +
  • str1 and str2 consist of English uppercase letters.
  • +
+
\ No newline at end of file diff --git a/1074-number-of-submatrices-that-sum-to-target/1074-number-of-submatrices-that-sum-to-target.cpp b/1074-number-of-submatrices-that-sum-to-target/1074-number-of-submatrices-that-sum-to-target.cpp new file mode 100644 index 00000000..1fe999aa --- /dev/null +++ b/1074-number-of-submatrices-that-sum-to-target/1074-number-of-submatrices-that-sum-to-target.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int numSubmatrixSumTarget(vector>& matrix, int target) { + + int m = matrix.size(); + int n = matrix[0].size(); + + // prefix sum + + for(int row = 0; row < m; ++row) + { + for(int col = 1; col < n; ++col) + { + matrix[row][col] += matrix[row][col-1]; + } + } + + int count = 0; + + // fix 2 colums + + for(int c1 = 0; c1 < n; ++c1) + { + for(int c2 = c1; c2 < n; ++c2) + { + unordered_map mp; + int sum = 0; + mp.insert({0,1}); + + for(int row = 0; row < m; ++row) + { + sum += matrix[row][c2] - (c1 > 0 ? matrix[row][c1-1] : 0); + count += mp[sum-target]; + + if(mp.find(sum) != mp.end()) + ++mp[sum]; + else + mp[sum] = 1; + } + } + } + + return count; + } +}; \ No newline at end of file diff --git a/1074-number-of-submatrices-that-sum-to-target/NOTES.md b/1074-number-of-submatrices-that-sum-to-target/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1074-number-of-submatrices-that-sum-to-target/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1081-smallest-subsequence-of-distinct-characters/1081-smallest-subsequence-of-distinct-characters.cpp b/1081-smallest-subsequence-of-distinct-characters/1081-smallest-subsequence-of-distinct-characters.cpp new file mode 100644 index 00000000..b9602471 --- /dev/null +++ b/1081-smallest-subsequence-of-distinct-characters/1081-smallest-subsequence-of-distinct-characters.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + string smallestSubsequence(string s) { + + int n = s.size(); + + vector lastOccurence(26, -1); + + vector visited(26, false); + + for(int i = 0; i < n; ++i) + lastOccurence[s[i] - 'a'] = i; + + string ans; + + for(int i = 0; i < n; ++i) + { + while(!ans.empty() and !visited[s[i] - 'a'] and s[i] < ans.back() and lastOccurence[ans.back() - 'a'] > i) + { + visited[ans.back() - 'a'] = false; + + ans.pop_back(); + } + + if(!visited[s[i] - 'a']) + { + ans += s[i]; + visited[s[i] - 'a'] = true; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1081-smallest-subsequence-of-distinct-characters/NOTES.md b/1081-smallest-subsequence-of-distinct-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1081-smallest-subsequence-of-distinct-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1081-smallest-subsequence-of-distinct-characters/README.md b/1081-smallest-subsequence-of-distinct-characters/README.md new file mode 100644 index 00000000..27cd917c --- /dev/null +++ b/1081-smallest-subsequence-of-distinct-characters/README.md @@ -0,0 +1,25 @@ +

1081. Smallest Subsequence of Distinct Characters

Medium


Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

+ +

 

+

Example 1:

+ +
Input: s = "bcabc"
+Output: "abc"
+
+ +

Example 2:

+ +
Input: s = "cbacdcbc"
+Output: "acdb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of lowercase English letters.
  • +
+ +

 

+Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
\ No newline at end of file diff --git a/1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.cpp b/1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.cpp new file mode 100644 index 00000000..3125c601 --- /dev/null +++ b/1091-shortest-path-in-binary-matrix/1091-shortest-path-in-binary-matrix.cpp @@ -0,0 +1,57 @@ +class Solution { + +private: + bool isValid(int x, int y, int n, int m) + { + return (x >= 0 and y >= 0 and x < n and y < m); + } + +public: + int shortestPathBinaryMatrix(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + priority_queue>, vector>> ,greater>> > pq; + + if(grid[0][0] == 0) + { + pq.push({1,{0, 0}}); + } + else + return -1; + + vector dx = {-1, -1, -1, 0, 1, 1, 1, 0}; + vector dy = {-1, 0, +1, +1, +1, 0, -1, -1}; + + while(!pq.empty()) + { + int dist = pq.top().first; + + int x = pq.top().second.first; + int y = pq.top().second.second; + + pq.pop(); + + if(x == n-1 and y == m-1) + { + return dist; + } + + for(int i = 0; i < 8; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(isValid(newx, newy, n, m) and grid[newx][newy] == 0) + { + grid[newx][newy] = 1; + + pq.push({dist + 1, {newx, newy}}); + } + } + } + + return -1; + } +}; \ No newline at end of file diff --git a/1091-shortest-path-in-binary-matrix/README.md b/1091-shortest-path-in-binary-matrix/README.md new file mode 100644 index 00000000..b59fa875 --- /dev/null +++ b/1091-shortest-path-in-binary-matrix/README.md @@ -0,0 +1,40 @@ +

1091. Shortest Path in Binary Matrix

Medium


Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

+ +

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

+ +
    +
  • All the visited cells of the path are 0.
  • +
  • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
  • +
+ +

The length of a clear path is the number of visited cells of this path.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1],[1,0]]
+Output: 2
+
+ +

Example 2:

+ +
Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
+Output: 4
+
+ +

Example 3:

+ +
Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= n <= 100
  • +
  • grid[i][j] is 0 or 1
  • +
+
\ No newline at end of file diff --git a/1092-shortest-common-supersequence/1092-shortest-common-supersequence.cpp b/1092-shortest-common-supersequence/1092-shortest-common-supersequence.cpp new file mode 100644 index 00000000..47e9291d --- /dev/null +++ b/1092-shortest-common-supersequence/1092-shortest-common-supersequence.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + string shortestCommonSupersequence(string str1, string str2) { + + int n = str1.size(), m = str2.size(); + + vector> dp(n+1, vector(m+1, 0)); + + for(int i = 1; i <= n; ++i) + { + for(int j = 1; j <= m; ++j) + { + if(str1[i-1] == str2[j-1]) + dp[i][j] = 1 + dp[i-1][j-1]; + else + dp[i][j] = max(dp[i-1][j], dp[i][j-1]); + } + } + + int i = n, j = m; + string ans; + + while(i > 0 and j > 0) + { + if(str1[i-1] == str2[j-1]) + { + ans += str1[i-1]; + --i, --j; + } + else if(dp[i-1][j] > dp[i][j-1]) + { + ans += str1[i-1]; + --i; + } + else + { + ans += str2[j-1]; + --j; + } + } + + while(i > 0) + { + ans += str1[i-1]; + --i; + } + + while(j > 0) + { + ans += str2[j-1]; + --j; + } + + reverse(ans.begin(), ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/1092-shortest-common-supersequence/NOTES.md b/1092-shortest-common-supersequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1092-shortest-common-supersequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1092-shortest-common-supersequence/README.md b/1092-shortest-common-supersequence/README.md new file mode 100644 index 00000000..f93f6296 --- /dev/null +++ b/1092-shortest-common-supersequence/README.md @@ -0,0 +1,29 @@ +

1092. Shortest Common Supersequence

Hard


Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.

+ +

A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.

+ +

 

+

Example 1:

+ +
Input: str1 = "abac", str2 = "cab"
+Output: "cabac"
+Explanation: 
+str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
+str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
+The answer provided is the shortest such string that satisfies these properties.
+
+ +

Example 2:

+ +
Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
+Output: "aaaaaaaa"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= str1.length, str2.length <= 1000
  • +
  • str1 and str2 consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1105-filling-bookcase-shelves/1105-filling-bookcase-shelves.cpp b/1105-filling-bookcase-shelves/1105-filling-bookcase-shelves.cpp new file mode 100644 index 00000000..1c7ef1c7 --- /dev/null +++ b/1105-filling-bookcase-shelves/1105-filling-bookcase-shelves.cpp @@ -0,0 +1,33 @@ +class Solution { +private: + int solve(vector> &books, int i, int remShelfWidth, int maxShelfHeight, + int shelfWidth, vector> &dp) { + + if(i == books.size()) { + return maxShelfHeight; + } + + if(dp[i][remShelfWidth] != -1) + return dp[i][remShelfWidth]; + + int currShelf = INT_MAX, nextShelf = INT_MAX; + + int bookWidth = books[i][0]; + int bookHeight = books[i][1]; + + if(bookWidth <= remShelfWidth) { + currShelf = solve(books, i + 1, remShelfWidth - bookWidth, + max(maxShelfHeight, bookHeight), shelfWidth, dp); + } + + nextShelf = maxShelfHeight + solve(books, i + 1, shelfWidth - bookWidth, + bookHeight, shelfWidth, dp); + + return dp[i][remShelfWidth] = min(currShelf, nextShelf); + } +public: + int minHeightShelves(vector>& books, int shelfWidth) { + vector> dp(1001, vector (shelfWidth + 1, -1)); + return solve(books, 0, shelfWidth, 0, shelfWidth, dp); + } +}; \ No newline at end of file diff --git a/1105-filling-bookcase-shelves/NOTES.md b/1105-filling-bookcase-shelves/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1105-filling-bookcase-shelves/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1110-delete-nodes-and-return-forest/1110-delete-nodes-and-return-forest.cpp b/1110-delete-nodes-and-return-forest/1110-delete-nodes-and-return-forest.cpp new file mode 100644 index 00000000..b0d40593 --- /dev/null +++ b/1110-delete-nodes-and-return-forest/1110-delete-nodes-and-return-forest.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool set[1001] = {}; + void dfs(TreeNode* &root, bool flag, vector& res){ + if (root == nullptr) return; + dfs(root->left, set[root->val], res); + dfs(root->right, set[root->val], res); + if (!set[root->val] && flag) res.push_back(root); + if (set[root->val]) root = nullptr; + } +public: + vector delNodes(TreeNode* root, vector& to_delete) { + vector res; + for (int num : to_delete) + set[num] = true; + dfs(root, true, res); + return res; + } + +}; \ No newline at end of file diff --git a/1110-delete-nodes-and-return-forest/NOTES.md b/1110-delete-nodes-and-return-forest/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1110-delete-nodes-and-return-forest/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1110-delete-nodes-and-return-forest/README.md b/1110-delete-nodes-and-return-forest/README.md new file mode 100644 index 00000000..d613487a --- /dev/null +++ b/1110-delete-nodes-and-return-forest/README.md @@ -0,0 +1,29 @@ +

1110. Delete Nodes And Return Forest

Medium


Given the root of a binary tree, each node in the tree has a distinct value.

+ +

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

+ +

Return the roots of the trees in the remaining forest. You may return the result in any order.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
+Output: [[1,2,null,4],[6],[7]]
+
+ +

Example 2:

+ +
Input: root = [1,2,4,null,3], to_delete = [3]
+Output: [[1,2,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the given tree is at most 1000.
  • +
  • Each node has a distinct value between 1 and 1000.
  • +
  • to_delete.length <= 1000
  • +
  • to_delete contains distinct values between 1 and 1000.
  • +
+
\ No newline at end of file diff --git a/1122-relative-sort-array/1122-relative-sort-array.cpp b/1122-relative-sort-array/1122-relative-sort-array.cpp new file mode 100644 index 00000000..e9aae6f3 --- /dev/null +++ b/1122-relative-sort-array/1122-relative-sort-array.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector relativeSortArray(vector& arr1, vector& arr2) { + + map mp; + + for(auto& ele : arr1) + ++mp[ele]; + + int j = 0; + + for(int i = 0; i < arr2.size(); ++i) + { + for(int k = 0; k < mp[arr2[i]]; ++k) + { + arr1[j++] = arr2[i]; + } + mp.erase(arr2[i]); + } + + for(auto&[f, e] : mp) + { + for(int k = 0; k < e; ++k) + arr1[j++] = f; + } + + return arr1; + } +}; \ No newline at end of file diff --git a/1122-relative-sort-array/NOTES.md b/1122-relative-sort-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1122-relative-sort-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1122-relative-sort-array/README.md b/1122-relative-sort-array/README.md new file mode 100644 index 00000000..fabd6b8c --- /dev/null +++ b/1122-relative-sort-array/README.md @@ -0,0 +1,27 @@ +

1122. Relative Sort Array

Easy


Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

+ +

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.

+ +

 

+

Example 1:

+ +
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
+Output: [2,2,2,1,4,3,3,9,6,7,19]
+
+ +

Example 2:

+ +
Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
+Output: [22,28,8,6,17,44]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr1.length, arr2.length <= 1000
  • +
  • 0 <= arr1[i], arr2[i] <= 1000
  • +
  • All the elements of arr2 are distinct.
  • +
  • Each arr2[i] is in arr1.
  • +
+
\ No newline at end of file diff --git a/1125-smallest-sufficient-team/1125-smallest-sufficient-team.cpp b/1125-smallest-sufficient-team/1125-smallest-sufficient-team.cpp new file mode 100644 index 00000000..799d66d1 --- /dev/null +++ b/1125-smallest-sufficient-team/1125-smallest-sufficient-team.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + +vectorres; + +void helper(int i,vector&people_skill,int m,int mask,vector&ans,vector>&dp) +{ + if(i == people_skill.size()) + { + if(mask == ((1< 0) dp[i][mask] = ans.size(); +} + + + vector smallestSufficientTeam(vector& req_skills, vector>& people) { + + int n = people.size(); + int m = req_skills.size(); + + unordered_mapmpp; + + for(int i = 0;ipeople_skill; + + for(auto it : people) + { + int mask = 0; + for(int j = 0; j < it.size(); ++j) + { + if(mpp.count(it[j])) mask |= mpp[it[j]]; + } + people_skill.push_back(mask); + } + + vector> dp(n, vector((1<ans; + + helper(0,people_skill,m,0,ans,dp); + return res; + } +}; \ No newline at end of file diff --git a/1125-smallest-sufficient-team/NOTES.md b/1125-smallest-sufficient-team/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1125-smallest-sufficient-team/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1125-smallest-sufficient-team/README.md b/1125-smallest-sufficient-team/README.md new file mode 100644 index 00000000..ea414a9c --- /dev/null +++ b/1125-smallest-sufficient-team/README.md @@ -0,0 +1,37 @@ +

1125. Smallest Sufficient Team

Hard


In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.

+ +

Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.

+ +
    +
  • For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].
  • +
+ +

Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.

+ +

It is guaranteed an answer exists.

+ +

 

+

Example 1:

+
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
+Output: [0,2]
+

Example 2:

+
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
+Output: [1,2]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= req_skills.length <= 16
  • +
  • 1 <= req_skills[i].length <= 16
  • +
  • req_skills[i] consists of lowercase English letters.
  • +
  • All the strings of req_skills are unique.
  • +
  • 1 <= people.length <= 60
  • +
  • 0 <= people[i].length <= 16
  • +
  • 1 <= people[i][j].length <= 16
  • +
  • people[i][j] consists of lowercase English letters.
  • +
  • All the strings of people[i] are unique.
  • +
  • Every skill in people[i] is a skill in req_skills.
  • +
  • It is guaranteed a sufficient team exists.
  • +
+
\ No newline at end of file diff --git a/1129-shortest-path-with-alternating-colors/1129-shortest-path-with-alternating-colors.cpp b/1129-shortest-path-with-alternating-colors/1129-shortest-path-with-alternating-colors.cpp new file mode 100644 index 00000000..b7086e8f --- /dev/null +++ b/1129-shortest-path-with-alternating-colors/1129-shortest-path-with-alternating-colors.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { + + vector>> graph(n); + for(auto edge: redEdges) + graph[edge[0]].emplace_back(edge[1],0); + for(auto edge: blueEdges) + graph[edge[0]].emplace_back(edge[1],1); + vector dist(n,-1); + + queue> q; + q.emplace(vector{0,0,-1}); + + while(!q.empty()) { + auto front = q.front(); + q.pop(); + dist[front[0]] = dist[front[0]] != -1 ? dist[front[0]] : front[1]; + + for(auto &adj : graph[front[0]]) { + + if(front[2] != adj.second && adj.first!= -1) { + q.emplace(vector{adj.first, front[1] + 1, adj.second}); + + adj.first = -1; + } + } + } + return dist; + } +}; \ No newline at end of file diff --git a/1129-shortest-path-with-alternating-colors/NOTES.md b/1129-shortest-path-with-alternating-colors/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1129-shortest-path-with-alternating-colors/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1129-shortest-path-with-alternating-colors/README.md b/1129-shortest-path-with-alternating-colors/README.md new file mode 100644 index 00000000..1409cff8 --- /dev/null +++ b/1129-shortest-path-with-alternating-colors/README.md @@ -0,0 +1,34 @@ +

1129. Shortest Path with Alternating Colors

Medium


You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.

+ +

You are given two arrays redEdges and blueEdges where:

+ +
    +
  • redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and
  • +
  • blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.
  • +
+ +

Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.

+ +

 

+

Example 1:

+ +
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
+Output: [0,1,-1]
+
+ +

Example 2:

+ +
Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
+Output: [0,1,-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 0 <= redEdges.length, blueEdges.length <= 400
  • +
  • redEdges[i].length == blueEdges[j].length == 2
  • +
  • 0 <= ai, bi, uj, vj < n
  • +
+
\ No newline at end of file diff --git a/1137-n-th-tribonacci-number/1137-n-th-tribonacci-number.cpp b/1137-n-th-tribonacci-number/1137-n-th-tribonacci-number.cpp new file mode 100644 index 00000000..55514f8d --- /dev/null +++ b/1137-n-th-tribonacci-number/1137-n-th-tribonacci-number.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int tribonacci(int n) { + + if(n == 0) + return 0; + if(n <= 2) + return 1; + + int prev3 = 0, prev2 = 1, prev1 = 1, next; + + for(int i = 3; i <= n; ++i) + { + next = prev1 + prev2 + prev3; + prev3 = prev2; + prev2 = prev1; + prev1 = next; + } + return next; + } +}; \ No newline at end of file diff --git a/1137-n-th-tribonacci-number/NOTES.md b/1137-n-th-tribonacci-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1137-n-th-tribonacci-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1137-n-th-tribonacci-number/README.md b/1137-n-th-tribonacci-number/README.md new file mode 100644 index 00000000..198667d5 --- /dev/null +++ b/1137-n-th-tribonacci-number/README.md @@ -0,0 +1,29 @@ +

1137. N-th Tribonacci Number

Easy


The Tribonacci sequence Tn is defined as follows: 

+ +

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

+ +

Given n, return the value of Tn.

+ +

 

+

Example 1:

+ +
Input: n = 4
+Output: 4
+Explanation:
+T_3 = 0 + 1 + 1 = 2
+T_4 = 1 + 1 + 2 = 4
+
+ +

Example 2:

+ +
Input: n = 25
+Output: 1389537
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 37
  • +
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
  • +
\ No newline at end of file diff --git a/1140-stone-game-ii/1140-stone-game-ii.cpp b/1140-stone-game-ii/1140-stone-game-ii.cpp new file mode 100644 index 00000000..c2506848 --- /dev/null +++ b/1140-stone-game-ii/1140-stone-game-ii.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + + int dp[101][201]; + + int helper(int i,int m,vector& piles){ + + if(i >= piles.size()) + return 0; + + if(dp[i][m] != -1) + return dp[i][m]; + + int total = 0; + int ans = INT_MIN; + + for(int j=0;j<2*m;j++){ + + if(i+j < piles.size()) + total += piles[i+j]; + + ans = max(ans,total - helper(i+j+1,max(m,j+1),piles)); + } + + return dp[i][m] = ans; + } + int stoneGameII(vector& piles) { + + + memset(dp,-1,sizeof dp); + + int sum = 0; + for(auto x:piles) + sum += x; + + + int diff = helper(0,1,piles); + + return (sum+diff)/2; + } +}; \ No newline at end of file diff --git a/1140-stone-game-ii/NOTES.md b/1140-stone-game-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1140-stone-game-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1140-stone-game-ii/README.md b/1140-stone-game-ii/README.md new file mode 100644 index 00000000..7add6be1 --- /dev/null +++ b/1140-stone-game-ii/README.md @@ -0,0 +1,32 @@ +

1140. Stone Game II

Medium


Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. 

+ +

Alice and Bob take turns, with Alice starting first.  Initially, M = 1.

+ +

On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).

+ +

The game continues until all the stones have been taken.

+ +

Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.

+ +

 

+

Example 1:

+ +
Input: piles = [2,7,9,4,4]
+Output: 10
+Explanation:  If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. 
+
+ +

Example 2:

+ +
Input: piles = [1,2,3,4,5,100]
+Output: 104
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= piles.length <= 100
  • +
  • 1 <= piles[i] <= 104
  • +
+
\ No newline at end of file diff --git a/1143-longest-common-subsequence/1143-longest-common-subsequence.cpp b/1143-longest-common-subsequence/1143-longest-common-subsequence.cpp new file mode 100644 index 00000000..c4f5a4ae --- /dev/null +++ b/1143-longest-common-subsequence/1143-longest-common-subsequence.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + + int helper(int i, int j, string& text1, string& text2, int n, int m, vector>& dp) + { + if(i == n or j == m) + return 0; + if(dp[i][j] != -1) + return dp[i][j]; + if(text1[i] == text2[j]) + return dp[i][j] = 1 + helper(i+1, j+1, text1, text2, n ,m, dp); + return dp[i][j] = max(helper(i,j+1, text1, text2, n, m, dp), helper(i+1, j, text1, text2, n, m, dp)); + } + + + int longestCommonSubsequence(string text1, string text2) { + + int n = text1.size(), m = text2.size(); + vector> dp(n+1, vector(m+1,-1)); + return helper(0,0,text1, text2, text1.size(), text2.size(),dp); + + } +}; \ No newline at end of file diff --git a/1143-longest-common-subsequence/NOTES.md b/1143-longest-common-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1143-longest-common-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1143-longest-common-subsequence/README.md b/1143-longest-common-subsequence/README.md new file mode 100644 index 00000000..41371569 --- /dev/null +++ b/1143-longest-common-subsequence/README.md @@ -0,0 +1,40 @@ +

1143. Longest Common Subsequence

Medium


Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

+ +

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

+ +
    +
  • For example, "ace" is a subsequence of "abcde".
  • +
+ +

A common subsequence of two strings is a subsequence that is common to both strings.

+ +

 

+

Example 1:

+ +
Input: text1 = "abcde", text2 = "ace" 
+Output: 3  
+Explanation: The longest common subsequence is "ace" and its length is 3.
+
+ +

Example 2:

+ +
Input: text1 = "abc", text2 = "abc"
+Output: 3
+Explanation: The longest common subsequence is "abc" and its length is 3.
+
+ +

Example 3:

+ +
Input: text1 = "abc", text2 = "def"
+Output: 0
+Explanation: There is no such common subsequence, so the result is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= text1.length, text2.length <= 1000
  • +
  • text1 and text2 consist of only lowercase English characters.
  • +
+
\ No newline at end of file diff --git a/1146-snapshot-array/1146-snapshot-array.cpp b/1146-snapshot-array/1146-snapshot-array.cpp new file mode 100644 index 00000000..b8c78c47 --- /dev/null +++ b/1146-snapshot-array/1146-snapshot-array.cpp @@ -0,0 +1,40 @@ +class SnapshotArray { +public: + + map> mp; + int cnt = 0; + + SnapshotArray(int length) { + for(int i = 0; i < length; ++i) + { + map mp2; + mp2[0] = 0; + mp[i] = mp2; + } + } + + void set(int index, int val) { + mp[index][cnt] = val; + } + + int snap() { + ++cnt; + + return cnt-1; + } + + int get(int index, int snap_id) { + + auto here = mp[index].upper_bound(snap_id); + --here; + return here->second; + } +}; + +/** + * Your SnapshotArray object will be instantiated and called as such: + * SnapshotArray* obj = new SnapshotArray(length); + * obj->set(index,val); + * int param_2 = obj->snap(); + * int param_3 = obj->get(index,snap_id); + */ \ No newline at end of file diff --git a/1146-snapshot-array/README.md b/1146-snapshot-array/README.md new file mode 100644 index 00000000..b3ccb749 --- /dev/null +++ b/1146-snapshot-array/README.md @@ -0,0 +1,33 @@ +

1146. Snapshot Array

Medium


Implement a SnapshotArray that supports the following interface:

+ +
    +
  • SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.
  • +
  • void set(index, val) sets the element at the given index to be equal to val.
  • +
  • int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
  • +
  • int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id
  • +
+ +

 

+

Example 1:

+ +
Input: ["SnapshotArray","set","snap","set","get"]
+[[3],[0,5],[],[0,6],[0,0]]
+Output: [null,null,0,null,5]
+Explanation: 
+SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
+snapshotArr.set(0,5);  // Set array[0] = 5
+snapshotArr.snap();  // Take a snapshot, return snap_id = 0
+snapshotArr.set(0,6);
+snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5
+ +

 

+

Constraints:

+ +
    +
  • 1 <= length <= 5 * 104
  • +
  • 0 <= index < length
  • +
  • 0 <= val <= 109
  • +
  • 0 <= snap_id < (the total number of times we call snap())
  • +
  • At most 5 * 104 calls will be made to set, snap, and get.
  • +
+
\ No newline at end of file diff --git a/1148-article-views-i/1148-article-views-i.sql b/1148-article-views-i/1148-article-views-i.sql new file mode 100644 index 00000000..f6d15e95 --- /dev/null +++ b/1148-article-views-i/1148-article-views-i.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below + +select distinct(author_id) as id from Views where author_id = viewer_id order by author_id asc; \ No newline at end of file diff --git a/1148-article-views-i/NOTES.md b/1148-article-views-i/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1148-article-views-i/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1148-article-views-i/README.md b/1148-article-views-i/README.md new file mode 100644 index 00000000..fa2d7609 --- /dev/null +++ b/1148-article-views-i/README.md @@ -0,0 +1,48 @@ +

1148. Article Views I

Easy


Table: Views

+ +
+---------------+---------+
+| Column Name   | Type    |
++---------------+---------+
+| article_id    | int     |
+| author_id     | int     |
+| viewer_id     | int     |
+| view_date     | date    |
++---------------+---------+
+There is no primary key (column with unique values) for this table, the table may have duplicate rows.
+Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 
+Note that equal author_id and viewer_id indicate the same person.
+
+ +

 

+ +

Write a solution to find all the authors that viewed at least one of their own articles.

+ +

Return the result table sorted by id in ascending order.

+ +

The result format is in the following example.

+ +

 

+

Example 1:

+ +
Input: 
+Views table:
++------------+-----------+-----------+------------+
+| article_id | author_id | viewer_id | view_date  |
++------------+-----------+-----------+------------+
+| 1          | 3         | 5         | 2019-08-01 |
+| 1          | 3         | 6         | 2019-08-02 |
+| 2          | 7         | 7         | 2019-08-01 |
+| 2          | 7         | 6         | 2019-08-02 |
+| 4          | 7         | 1         | 2019-07-22 |
+| 3          | 4         | 4         | 2019-07-21 |
+| 3          | 4         | 4         | 2019-07-21 |
++------------+-----------+-----------+------------+
+Output: 
++------+
+| id   |
++------+
+| 4    |
+| 7    |
++------+
+
+
\ No newline at end of file diff --git a/1155-number-of-dice-rolls-with-target-sum/1155-number-of-dice-rolls-with-target-sum.cpp b/1155-number-of-dice-rolls-with-target-sum/1155-number-of-dice-rolls-with-target-sum.cpp new file mode 100644 index 00000000..af9c24b2 --- /dev/null +++ b/1155-number-of-dice-rolls-with-target-sum/1155-number-of-dice-rolls-with-target-sum.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + + const int mod = 1e9+7; + + vector> dp(n+1, vector(target+1, 0)); + + dp[0][0] = 1; + + for(int i = 1; i <= n; ++i) + { + for(int j = 1; j <= target; ++j) + { + for(int f = 1; f <= k; ++f) + { + if(j - f >= 0) + dp[i][j] = (dp[i][j] + dp[i-1][j-f]) % mod; + } + } + } + + return dp[n][target]; + + } +}; \ No newline at end of file diff --git a/1155-number-of-dice-rolls-with-target-sum/NOTES.md b/1155-number-of-dice-rolls-with-target-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1155-number-of-dice-rolls-with-target-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1155-number-of-dice-rolls-with-target-sum/README.md b/1155-number-of-dice-rolls-with-target-sum/README.md new file mode 100644 index 00000000..19dd039a --- /dev/null +++ b/1155-number-of-dice-rolls-with-target-sum/README.md @@ -0,0 +1,36 @@ +

1155. Number of Dice Rolls With Target Sum

Medium


You have n dice, and each die has k faces numbered from 1 to k.

+ +

Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 1, k = 6, target = 3
+Output: 1
+Explanation: You throw one die with 6 faces.
+There is only one way to get a sum of 3.
+
+ +

Example 2:

+ +
Input: n = 2, k = 6, target = 7
+Output: 6
+Explanation: You throw two dice, each with 6 faces.
+There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
+
+ +

Example 3:

+ +
Input: n = 30, k = 30, target = 500
+Output: 222616187
+Explanation: The answer must be returned modulo 109 + 7.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n, k <= 30
  • +
  • 1 <= target <= 1000
  • +
+
\ No newline at end of file diff --git a/1160-find-words-that-can-be-formed-by-characters/1160-find-words-that-can-be-formed-by-characters.cpp b/1160-find-words-that-can-be-formed-by-characters/1160-find-words-that-can-be-formed-by-characters.cpp new file mode 100644 index 00000000..1b331ed1 --- /dev/null +++ b/1160-find-words-that-can-be-formed-by-characters/1160-find-words-that-can-be-formed-by-characters.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int countCharacters(vector& words, string chars) { + + int counter = 0; + + unordered_map mp; + + for(auto& ch : chars) + ++mp[ch]; + + for(auto& word : words) + { + bool canFormed = true; + + unordered_map freq; + + for(auto& ch : word) + { + ++freq[ch]; + } + + for(auto& ch : word) + { + if(freq[ch] > mp[ch]) + { + canFormed = false; + break; + } + } + + if(canFormed) + counter += word.size(); + } + + return counter; + + } +}; \ No newline at end of file diff --git a/1160-find-words-that-can-be-formed-by-characters/NOTES.md b/1160-find-words-that-can-be-formed-by-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1160-find-words-that-can-be-formed-by-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1160-find-words-that-can-be-formed-by-characters/README.md b/1160-find-words-that-can-be-formed-by-characters/README.md new file mode 100644 index 00000000..62067b24 --- /dev/null +++ b/1160-find-words-that-can-be-formed-by-characters/README.md @@ -0,0 +1,30 @@ +

1160. Find Words That Can Be Formed by Characters

Easy


You are given an array of strings words and a string chars.

+ +

A string is good if it can be formed by characters from chars (each character can only be used once).

+ +

Return the sum of lengths of all good strings in words.

+ +

 

+

Example 1:

+ +
Input: words = ["cat","bt","hat","tree"], chars = "atach"
+Output: 6
+Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
+
+ +

Example 2:

+ +
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
+Output: 10
+Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length, chars.length <= 100
  • +
  • words[i] and chars consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp b/1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp new file mode 100644 index 00000000..d85f70ba --- /dev/null +++ b/1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp @@ -0,0 +1,54 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxLevelSum(TreeNode* root) { + + queue q; + + int lvl = 0, ans = 0, maxLvlSum = -1e9; + + q.push(root); + + while(!q.empty()) + { + lvl += 1; + + int size = q.size(); + + int sum = 0; + + for(int i = 0; i < size; ++i) + { + TreeNode* curr = q.front(); + + q.pop(); + + if(curr->left) + q.push(curr->left); + + if(curr->right) + q.push(curr->right); + + sum += curr->val; + } + + if(sum > maxLvlSum) + { + ans = lvl; + maxLvlSum = sum; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1161-maximum-level-sum-of-a-binary-tree/README.md b/1161-maximum-level-sum-of-a-binary-tree/README.md new file mode 100644 index 00000000..a172e9a4 --- /dev/null +++ b/1161-maximum-level-sum-of-a-binary-tree/README.md @@ -0,0 +1,30 @@ +

1161. Maximum Level Sum of a Binary Tree

Medium


Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

+ +

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

+ +

 

+

Example 1:

+ +
Input: root = [1,7,0,7,-8,null,null]
+Output: 2
+Explanation: 
+Level 1 sum = 1.
+Level 2 sum = 7 + 0 = 7.
+Level 3 sum = 7 + -8 = -1.
+So we return the level with the maximum sum which is level 2.
+
+ +

Example 2:

+ +
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/1162-as-far-from-land-as-possible/1162-as-far-from-land-as-possible.cpp b/1162-as-far-from-land-as-possible/1162-as-far-from-land-as-possible.cpp new file mode 100644 index 00000000..8fa408c0 --- /dev/null +++ b/1162-as-far-from-land-as-possible/1162-as-far-from-land-as-possible.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + int maxDistance(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + vector> visited(n,vector(m,false)); + vector> dir ={{0,1},{-1,0},{1,0}, {0,-1}}; + queue> q; + int ans = -1; + + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1) + { + visited[i][j] = true; + q.push({i,j}); + } + } + } + + while(!q.empty()) + { + int size = q.size(); + + for(int i = 0 ; i here = q.front(); + q.pop(); + + int currx = here.first; + int curry = here.second; + + for(auto itr : dir) + { + int newx = currx + itr[0]; + int newy = curry + itr[1]; + + + if(newx < 0 or newx >= n or newy < 0 or newy >= m or visited[newx][newy]) + continue; + + + visited[newx][newy] = true; + + grid[newx][newy] = grid[currx][curry] + 1; + + ans = max(ans,grid[newx][newy]); + + q.push({newx,newy}); + } + } + } + + return (ans == -1 ? -1 : ans - 1); + } +}; \ No newline at end of file diff --git a/1162-as-far-from-land-as-possible/README.md b/1162-as-far-from-land-as-possible/README.md new file mode 100644 index 00000000..54ce9084 --- /dev/null +++ b/1162-as-far-from-land-as-possible/README.md @@ -0,0 +1,29 @@ +

1162. As Far from Land as Possible

Medium


Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.

+ +

The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
+Output: 2
+Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
+
+ +

Example 2:

+ +
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
+Output: 4
+Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= n <= 100
  • +
  • grid[i][j] is 0 or 1
  • +
+
\ No newline at end of file diff --git a/1171-remove-zero-sum-consecutive-nodes-from-linked-list/1171-remove-zero-sum-consecutive-nodes-from-linked-list.cpp b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/1171-remove-zero-sum-consecutive-nodes-from-linked-list.cpp new file mode 100644 index 00000000..40d9fa70 --- /dev/null +++ b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/1171-remove-zero-sum-consecutive-nodes-from-linked-list.cpp @@ -0,0 +1,41 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeZeroSumSublists(ListNode* head) { + ListNode *dummynode=new ListNode(0),*curr=dummynode; + dummynode->next=head; + map mp; + int sum=0; + while(curr) + { + sum+=curr->val; + if(mp.count(sum)) + { + curr=mp[sum]->next; + int p=sum+curr->val; + while(p!=sum) + { + mp.erase(p); + curr=curr->next; + p+=curr->val; + } + mp[sum]->next=curr->next; + } + else + { + mp[sum]=curr; + } + curr=curr->next; + } + return dummynode->next; + } +}; \ No newline at end of file diff --git a/1171-remove-zero-sum-consecutive-nodes-from-linked-list/NOTES.md b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1171-remove-zero-sum-consecutive-nodes-from-linked-list/README.md b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/README.md new file mode 100644 index 00000000..a851823f --- /dev/null +++ b/1171-remove-zero-sum-consecutive-nodes-from-linked-list/README.md @@ -0,0 +1,34 @@ +

1171. Remove Zero Sum Consecutive Nodes from Linked List

Medium


Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

+ +

After doing so, return the head of the final linked list.  You may return any such answer.

+ +

 

+

(Note that in the examples below, all sequences are serializations of ListNode objects.)

+ +

Example 1:

+ +
Input: head = [1,2,-3,3,1]
+Output: [3,1]
+Note: The answer [1,2,1] would also be accepted.
+
+ +

Example 2:

+ +
Input: head = [1,2,3,-3,4]
+Output: [1,2,4]
+
+ +

Example 3:

+ +
Input: head = [1,2,3,-3,-2]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The given linked list will contain between 1 and 1000 nodes.
  • +
  • Each node in the linked list has -1000 <= node.val <= 1000.
  • +
+
\ No newline at end of file diff --git a/1187-make-array-strictly-increasing/1187-make-array-strictly-increasing.cpp b/1187-make-array-strictly-increasing/1187-make-array-strictly-increasing.cpp new file mode 100644 index 00000000..c6944efa --- /dev/null +++ b/1187-make-array-strictly-increasing/1187-make-array-strictly-increasing.cpp @@ -0,0 +1,46 @@ +#define ll long long int + +class Solution { + +private: + ll helper(int idx, int prev, int n, vector& arr1, vector& arr2, map,int>& dp) + { + if(idx == n) + return 0; + + if(dp.find({idx, prev}) != dp.end()) + return dp[{idx, prev}]; + + ll ans = INT_MAX; + + ll ind = upper_bound(arr2.begin(), arr2.end(), prev) - arr2.begin(); + + if(arr1[idx] > prev) + { + ans = min(ans, helper(idx+1, arr1[idx], n, arr1, arr2, dp)); + } + + if(ind < arr2.size()) + { + ans = min(ans, 1 + helper(idx+1, arr2[ind], n, arr1, arr2, dp)); + } + + + return dp[{idx, prev}] = ans; + } + +public: + int makeArrayIncreasing(vector& arr1, vector& arr2) { + + sort(arr2.begin(), arr2.end()); + + map, int> dp; + + int n = arr1.size(); + + int ans = helper(0, INT_MIN,n, arr1, arr2, dp); + + return (ans == INT_MAX ? -1 : ans); + + } +}; \ No newline at end of file diff --git a/1187-make-array-strictly-increasing/README.md b/1187-make-array-strictly-increasing/README.md new file mode 100644 index 00000000..de398023 --- /dev/null +++ b/1187-make-array-strictly-increasing/README.md @@ -0,0 +1,36 @@ +

1187. Make Array Strictly Increasing

Hard


Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.

+ +

In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].

+ +

If there is no way to make arr1 strictly increasing, return -1.

+ +

 

+

Example 1:

+ +
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
+Output: 1
+Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].
+
+ +

Example 2:

+ +
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
+Output: 2
+Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].
+
+ +

Example 3:

+ +
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
+Output: -1
+Explanation: You can't make arr1 strictly increasing.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr1.length, arr2.length <= 2000
  • +
  • 0 <= arr1[i], arr2[i] <= 10^9
  • +
+ +

 

\ No newline at end of file diff --git a/1192-critical-connections-in-a-network/1192-critical-connections-in-a-network.cpp b/1192-critical-connections-in-a-network/1192-critical-connections-in-a-network.cpp new file mode 100644 index 00000000..dcbe31ca --- /dev/null +++ b/1192-critical-connections-in-a-network/1192-critical-connections-in-a-network.cpp @@ -0,0 +1,60 @@ +class Solution { +private: + int timer = 0; + + void dfs(int sv, int par, vector adj[], vector& visited, vector& disc, vector& low, vector>& bridges) + { + visited[sv] = true; + + disc[sv] = low[sv] = ++timer; + + for(auto itr : adj[sv]) + { + if(itr == par) + continue; + + if(!visited[itr]) + { + dfs(itr, sv, adj, visited, disc, low, bridges); + + low[sv] = min(low[sv], low[itr]); + + if(low[itr] > disc[sv]) + { + bridges.push_back({sv, itr}); + } + } + else + { + low[sv] = min(low[sv], low[itr]); + } + } + } + +public: + vector> criticalConnections(int n, vector>& connections) { + + vector adj[n]; + + for(auto itr : connections) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + } + + vector visited(n, false); + + vector disc(n, 0) , low(n, 0); + + vector> bridges; + + for(int i = 0; i < n; ++i) + { + if(!visited[i]) + dfs(i, -1, adj, visited, disc, low, bridges); + } + + return bridges; + + } +}; \ No newline at end of file diff --git a/1192-critical-connections-in-a-network/NOTES.md b/1192-critical-connections-in-a-network/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1192-critical-connections-in-a-network/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1192-critical-connections-in-a-network/README.md b/1192-critical-connections-in-a-network/README.md new file mode 100644 index 00000000..1851e0a3 --- /dev/null +++ b/1192-critical-connections-in-a-network/README.md @@ -0,0 +1,31 @@ +

1192. Critical Connections in a Network

Hard


There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.

+ +

A critical connection is a connection that, if removed, will make some servers unable to reach some other server.

+ +

Return all critical connections in the network in any order.

+ +

 

+

Example 1:

+ +
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
+Output: [[1,3]]
+Explanation: [[3,1]] is also accepted.
+
+ +

Example 2:

+ +
Input: n = 2, connections = [[0,1]]
+Output: [[0,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 105
  • +
  • n - 1 <= connections.length <= 105
  • +
  • 0 <= ai, bi <= n - 1
  • +
  • ai != bi
  • +
  • There are no repeated connections.
  • +
+
\ No newline at end of file diff --git a/1203-sort-items-by-groups-respecting-dependencies/1203-sort-items-by-groups-respecting-dependencies.cpp b/1203-sort-items-by-groups-respecting-dependencies/1203-sort-items-by-groups-respecting-dependencies.cpp new file mode 100644 index 00000000..3bf145c4 --- /dev/null +++ b/1203-sort-items-by-groups-respecting-dependencies/1203-sort-items-by-groups-respecting-dependencies.cpp @@ -0,0 +1,97 @@ +class Solution { + +private: + vector topologicalSort(vector adj[] , int n) + { + vector indegree(n+1, 0); + + for(int i =0 ; i < n; ++i) + { + for(auto& itr : adj[i]) + ++indegree[itr]; + } + + queue q; + + vector topo; + + for(int i = 0 ; i < n; ++i) + { + if(indegree[i] == 0) + q.push(i); + } + + while(!q.empty()) + { + int currNode = q.front(); + q.pop(); + + topo.push_back(currNode); + + for(auto& itr : adj[currNode]) + { + --indegree[itr]; + + if(indegree[itr] == 0) + q.push(itr); + } + } + + if(topo.size() == n) + return topo; + return {}; + } + +public: + vector sortItems(int n, int m, vector& group, vector>& beforeItems) { + + // JAI SHREE RAM + + for(int i = 0; i < n; ++i) + { + if(group[i] == -1) + group[i] = m++; + } + + vector itemsGraph[n+1], groupGraph[m+1]; + + for(int i = 0; i < n; ++i) + { + for(auto& prev : beforeItems[i]) + { + itemsGraph[prev].push_back(i); + + if(group[i] != group[prev]) + { + int prevItemGroup = group[prev]; + int currItemGroup = group[i]; + + groupGraph[prevItemGroup].push_back(currItemGroup); + } + } + } + + vector itemsTopologicalOrdering = topologicalSort(itemsGraph, n); + + vector groupsTopologicalOrdering = topologicalSort(groupGraph, m); + + unordered_map> groupToItemOrder; + + for(auto& item : itemsTopologicalOrdering) + { + int itemGroup = group[item]; + + groupToItemOrder[itemGroup].push_back(item); + + } + + vector ans; + + for(auto& group : groupsTopologicalOrdering) + { + ans.insert(ans.end(), groupToItemOrder[group].begin(), groupToItemOrder[group].end()); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1203-sort-items-by-groups-respecting-dependencies/NOTES.md b/1203-sort-items-by-groups-respecting-dependencies/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1203-sort-items-by-groups-respecting-dependencies/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1203-sort-items-by-groups-respecting-dependencies/README.md b/1203-sort-items-by-groups-respecting-dependencies/README.md new file mode 100644 index 00000000..3bf64a00 --- /dev/null +++ b/1203-sort-items-by-groups-respecting-dependencies/README.md @@ -0,0 +1,40 @@ +

1203. Sort Items by Groups Respecting Dependencies

Hard


There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.

+ +

Return a sorted list of the items such that:

+ +
    +
  • The items that belong to the same group are next to each other in the sorted list.
  • +
  • There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
  • +
+ +

Return any solution if there is more than one solution and return an empty list if there is no solution.

+ +

 

+

Example 1:

+ +

+ +
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
+Output: [6,3,4,1,5,2,0,7]
+
+ +

Example 2:

+ +
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
+Output: []
+Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m <= n <= 3 * 104
  • +
  • group.length == beforeItems.length == n
  • +
  • -1 <= group[i] <= m - 1
  • +
  • 0 <= beforeItems[i].length <= n - 1
  • +
  • 0 <= beforeItems[i][j] <= n - 1
  • +
  • i != beforeItems[i][j]
  • +
  • beforeItems[i] does not contain duplicates elements.
  • +
+
\ No newline at end of file diff --git a/1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.cpp b/1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.cpp new file mode 100644 index 00000000..68291a5b --- /dev/null +++ b/1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool uniqueOccurrences(vector& arr) { + + unordered_map mp; + unordered_set s; + for(auto itr : arr) + ++mp[itr]; + + for(auto itr : mp) + s.insert(itr.second); + + return (mp.size() == s.size()); + } +}; \ No newline at end of file diff --git a/1207-unique-number-of-occurrences/NOTES.md b/1207-unique-number-of-occurrences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1207-unique-number-of-occurrences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1207-unique-number-of-occurrences/README.md b/1207-unique-number-of-occurrences/README.md new file mode 100644 index 00000000..17a227c4 --- /dev/null +++ b/1207-unique-number-of-occurrences/README.md @@ -0,0 +1,29 @@ +

1207. Unique Number of Occurrences

Easy


Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: arr = [1,2,2,1,1,3]
+Output: true
+Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
+ +

Example 2:

+ +
Input: arr = [1,2]
+Output: false
+
+ +

Example 3:

+ +
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • -1000 <= arr[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1208-get-equal-substrings-within-budget/1208-get-equal-substrings-within-budget.cpp b/1208-get-equal-substrings-within-budget/1208-get-equal-substrings-within-budget.cpp new file mode 100644 index 00000000..430101aa --- /dev/null +++ b/1208-get-equal-substrings-within-budget/1208-get-equal-substrings-within-budget.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + + int n = s.size(); + + int i = 0, j = 0, ans = 0; + + while(j < n) + { + maxCost -= abs(s[j] - t[j]); + + if(maxCost < 0) + { + maxCost += abs(s[i] - t[i]); + ++i; + } + + ans = max(ans, j - i + 1); + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1208-get-equal-substrings-within-budget/NOTES.md b/1208-get-equal-substrings-within-budget/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1208-get-equal-substrings-within-budget/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1208-get-equal-substrings-within-budget/README.md b/1208-get-equal-substrings-within-budget/README.md new file mode 100644 index 00000000..45da0232 --- /dev/null +++ b/1208-get-equal-substrings-within-budget/README.md @@ -0,0 +1,39 @@ +

1208. Get Equal Substrings Within Budget

Medium


You are given two strings s and t of the same length and an integer maxCost.

+ +

You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).

+ +

Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.

+ +

 

+

Example 1:

+ +
Input: s = "abcd", t = "bcdf", maxCost = 3
+Output: 3
+Explanation: "abc" of s can change to "bcd".
+That costs 3, so the maximum length is 3.
+
+ +

Example 2:

+ +
Input: s = "abcd", t = "cdef", maxCost = 3
+Output: 1
+Explanation: Each character in s costs 2 to change to character in t,  so the maximum length is 1.
+
+ +

Example 3:

+ +
Input: s = "abcd", t = "acde", maxCost = 0
+Output: 1
+Explanation: You cannot make any change, so the maximum length is 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • t.length == s.length
  • +
  • 0 <= maxCost <= 106
  • +
  • s and t consist of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1218-longest-arithmetic-subsequence-of-given-difference/1218-longest-arithmetic-subsequence-of-given-difference.cpp b/1218-longest-arithmetic-subsequence-of-given-difference/1218-longest-arithmetic-subsequence-of-given-difference.cpp new file mode 100644 index 00000000..e21c8d06 --- /dev/null +++ b/1218-longest-arithmetic-subsequence-of-given-difference/1218-longest-arithmetic-subsequence-of-given-difference.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int longestSubsequence(vector& arr, int difference) { + + unordered_map dp; + + int n = arr.size(); + + int ans = 1; + + for(int i = 0; i < n; ++i) + { + int num = arr[i]; + + if(dp.find(num-difference) != dp.end()) + dp[num] = dp[num-difference] + 1; + + else + dp[num] = 1; + + ans = max(ans, dp[num]); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1218-longest-arithmetic-subsequence-of-given-difference/README.md b/1218-longest-arithmetic-subsequence-of-given-difference/README.md new file mode 100644 index 00000000..6fbe49c9 --- /dev/null +++ b/1218-longest-arithmetic-subsequence-of-given-difference/README.md @@ -0,0 +1,33 @@ +

1218. Longest Arithmetic Subsequence of Given Difference

Medium


Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

+ +

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

+ +

 

+

Example 1:

+ +
Input: arr = [1,2,3,4], difference = 1
+Output: 4
+Explanation: The longest arithmetic subsequence is [1,2,3,4].
+ +

Example 2:

+ +
Input: arr = [1,3,5,7], difference = 1
+Output: 1
+Explanation: The longest arithmetic subsequence is any single element.
+
+ +

Example 3:

+ +
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
+Output: 4
+Explanation: The longest arithmetic subsequence is [7,5,3,1].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 105
  • +
  • -104 <= arr[i], difference <= 104
  • +
+
\ No newline at end of file diff --git a/1219-path-with-maximum-gold/1219-path-with-maximum-gold.cpp b/1219-path-with-maximum-gold/1219-path-with-maximum-gold.cpp new file mode 100644 index 00000000..d38be720 --- /dev/null +++ b/1219-path-with-maximum-gold/1219-path-with-maximum-gold.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + + vector dx = {-1, +1, 0, 0}; + vector dy = {0, 0, +1, -1}; + + bool isValid(int x, int y, int n, int m) + { + return (x >= 0 and y >= 0 and x < n and y < m); + } + + int dfs(int i, int j, int n, int m, vector>& grid, vector>& visited){ + + int maxAns = 0; + + visited[i][j] = true; + + for(int k = 0; k < 4; ++k) + { + int newx = dx[k] + i; + int newy = dy[k] + j; + + if(isValid(newx, newy, n, m) and grid[newx][newy] != 0 and !visited[newx][newy]) + { + int ans = grid[newx][newy] + dfs(newx, newy, n, m, grid, visited); + maxAns = max(maxAns, ans); + } + } + + visited[i][j] = false; + + return maxAns; + } + + int getMaximumGold(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + int ans = 0; + + vector> visited(n, vector(m, false)); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] != 0) + { + int currVal = grid[i][j] + dfs(i, j, n, m, grid, visited); + ans = max(ans, currVal); + } + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1219-path-with-maximum-gold/README.md b/1219-path-with-maximum-gold/README.md new file mode 100644 index 00000000..399cf0bd --- /dev/null +++ b/1219-path-with-maximum-gold/README.md @@ -0,0 +1,48 @@ +

1219. Path with Maximum Gold

Medium


In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

+ +

Return the maximum amount of gold you can collect under the conditions:

+ +
    +
  • Every time you are located in a cell you will collect all the gold in that cell.
  • +
  • From your position, you can walk one step to the left, right, up, or down.
  • +
  • You can't visit the same cell more than once.
  • +
  • Never visit a cell with 0 gold.
  • +
  • You can start and stop collecting gold from any position in the grid that has some gold.
  • +
+ +

 

+

Example 1:

+ +
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
+Output: 24
+Explanation:
+[[0,6,0],
+ [5,8,7],
+ [0,9,0]]
+Path to get the maximum gold, 9 -> 8 -> 7.
+
+ +

Example 2:

+ +
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
+Output: 28
+Explanation:
+[[1,0,7],
+ [2,0,6],
+ [3,4,5],
+ [0,3,0],
+ [9,0,20]]
+Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 15
  • +
  • 0 <= grid[i][j] <= 100
  • +
  • There are at most 25 cells containing gold.
  • +
+
\ No newline at end of file diff --git a/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp b/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp new file mode 100644 index 00000000..56bada35 --- /dev/null +++ b/1220-count-vowels-permutation/1220-count-vowels-permutation.cpp @@ -0,0 +1,55 @@ +class Solution { + unordered_map> mp; + int mod = 1e9+7; + +public: + + int helper(int n ,int i ,char prev, vector>& t) + { + if(i > n) + return 0; + + if(i == n) + { + switch(prev) + { + case 'a': + return 1; + case 'e': + return 2; + case 'i': + return 4; + case 'o': + return 2; + case 'u': + return 1; + default: + return 5; + } + } + + int idx = prev - 'a'; + if(t[i][idx] != -1) + return t[i][idx]; + + long long ans = 0; + for(auto next : mp[prev]) + ans += (helper(n,i+1,next,t) % mod); + + return t[i][idx] = ans % mod; + } + + int countVowelPermutation(int n) { + + mp['c'] = {'a','e','i','o','u'}; + mp['a'] = {'e'}; + mp['e'] = {'a','i'}; + mp['i'] = {'a','e','o','u'}; + mp['o'] = {'i','u'}; + mp['u'] = {'a'}; + + vector> t(n+2,vector(27,-1)); + return helper(n,1,'c',t); + + } +}; \ No newline at end of file diff --git a/1220-count-vowels-permutation/NOTES.md b/1220-count-vowels-permutation/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1220-count-vowels-permutation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1220-count-vowels-permutation/README.md b/1220-count-vowels-permutation/README.md new file mode 100644 index 00000000..0eaafd10 --- /dev/null +++ b/1220-count-vowels-permutation/README.md @@ -0,0 +1,40 @@ +

1220. Count Vowels Permutation

Hard


Given an integer n, your task is to count how many strings of length n can be formed under the following rules:

+ +
    +
  • Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
  • +
  • Each vowel 'a' may only be followed by an 'e'.
  • +
  • Each vowel 'e' may only be followed by an 'a' or an 'i'.
  • +
  • Each vowel 'i' may not be followed by another 'i'.
  • +
  • Each vowel 'o' may only be followed by an 'i' or a 'u'.
  • +
  • Each vowel 'u' may only be followed by an 'a'.
  • +
+ +

Since the answer may be too large, return it modulo 10^9 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 5
+Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 10
+Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
+
+ +

Example 3: 

+ +
Input: n = 5
+Output: 68
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 10^4
  • +
+
\ No newline at end of file diff --git a/1220. Count Vowels Permutation.cpp b/1220. Count Vowels Permutation.cpp new file mode 100644 index 00000000..01d3b860 --- /dev/null +++ b/1220. Count Vowels Permutation.cpp @@ -0,0 +1,57 @@ +// 1220.✅ Count Vowels Permutation + +class Solution +{ + unordered_map> mp; + int mod = 1e9 + 7; + +public: + int helper(int n, int i, char prev, vector> &t) + { + if (i > n) + return 0; + + if (i == n) + { + switch (prev) + { + case 'a': + return 1; + case 'e': + return 2; + case 'i': + return 4; + case 'o': + return 2; + case 'u': + return 1; + default: + return 5; + } + } + + int idx = prev - 'a'; + if (t[i][idx] != -1) + return t[i][idx]; + + long long ans = 0; + for (auto next : mp[prev]) + ans += (helper(n, i + 1, next, t) % mod); + + return t[i][idx] = ans % mod; + } + + int countVowelPermutation(int n) + { + + mp['c'] = {'a', 'e', 'i', 'o', 'u'}; + mp['a'] = {'e'}; + mp['e'] = {'a', 'i'}; + mp['i'] = {'a', 'e', 'o', 'u'}; + mp['o'] = {'i', 'u'}; + mp['u'] = {'a'}; + + vector> t(n + 2, vector(27, -1)); + return helper(n, 1, 'c', t); + } +}; \ No newline at end of file diff --git a/1232-check-if-it-is-a-straight-line/1232-check-if-it-is-a-straight-line.cpp b/1232-check-if-it-is-a-straight-line/1232-check-if-it-is-a-straight-line.cpp new file mode 100644 index 00000000..239943ba --- /dev/null +++ b/1232-check-if-it-is-a-straight-line/1232-check-if-it-is-a-straight-line.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool checkStraightLine(vector>& coordinates) { + + int n = coordinates.size(); + + int x1 = coordinates[0][0]; + int y1 = coordinates[0][1]; + + int x2 = coordinates[1][0]; + int y2 = coordinates[1][1]; + + for(int i = 2; i < n; ++i) + { + int x = coordinates[i][0]; + int y = coordinates[i][1]; + + // y-y1/x-x1 = y-y2/x-x2 + + if((y-y1)*(x-x2) != (x-x1)*(y-y2)) + return false; + } + + return true; + + } +}; \ No newline at end of file diff --git a/1232-check-if-it-is-a-straight-line/README.md b/1232-check-if-it-is-a-straight-line/README.md new file mode 100644 index 00000000..832bb14e --- /dev/null +++ b/1232-check-if-it-is-a-straight-line/README.md @@ -0,0 +1,30 @@ +

1232. Check If It Is a Straight Line

Easy


You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

+ +

 

+ +

 

+

Example 1:

+ +

+ +
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
+Output: true
+
+ +

Example 2:

+ +

+ +
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= coordinates.length <= 1000
  • +
  • coordinates[i].length == 2
  • +
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • +
  • coordinates contains no duplicate point.
  • +
\ No newline at end of file diff --git a/1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.cpp b/1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.cpp new file mode 100644 index 00000000..a2d455e9 --- /dev/null +++ b/1235-maximum-profit-in-job-scheduling/1235-maximum-profit-in-job-scheduling.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + + int getNextIdx(int low, int last, vector>& jobs) + { + int n = jobs.size(); + int high = n-1, result = n; + + while(low <= high) + { + int mid = low + (high - low)/2; + + if(jobs[mid][0] >= last) + { + result = mid; + high = mid-1; + } + else + low = mid+1; + } + + return result; + } + + int helper(int idx, int n, vector>& jobs, vector& dp) + { + if(idx == n) + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int next = getNextIdx(idx+1, jobs[idx][1], jobs); + + int notTake = helper(idx+1, n, jobs, dp); + + int take = jobs[idx][2] + helper(next, n, jobs, dp); + + return dp[idx] = max(take, notTake); + } + + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + + int n = startTime.size(); + + vector> jobs; + + for(int i = 0; i < n; ++i) + { + jobs.push_back({startTime[i], endTime[i], profit[i]}); + } + + sort(jobs.begin(), jobs.end()); + + vector dp(n+1, -1); + + return helper(0, n, jobs, dp); + + } +}; \ No newline at end of file diff --git a/1235-maximum-profit-in-job-scheduling/README.md b/1235-maximum-profit-in-job-scheduling/README.md new file mode 100644 index 00000000..8660019e --- /dev/null +++ b/1235-maximum-profit-in-job-scheduling/README.md @@ -0,0 +1,44 @@ +

1235. Maximum Profit in Job Scheduling

Hard


We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

+ +

You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

+ +

If you choose a job that ends at time X you will be able to start another job that starts at time X.

+ +

 

+

Example 1:

+ +

+ +
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
+Output: 120
+Explanation: The subset chosen is the first and fourth job. 
+Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
+
+ +

Example 2:

+ +

+ +
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
+Output: 150
+Explanation: The subset chosen is the first, fourth and fifth job. 
+Profit obtained 150 = 20 + 70 + 60.
+
+ +

Example 3:

+ +

+ +
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= startTime.length == endTime.length == profit.length <= 5 * 104
  • +
  • 1 <= startTime[i] < endTime[i] <= 109
  • +
  • 1 <= profit[i] <= 104
  • +
+
\ No newline at end of file diff --git a/1239-maximum-length-of-a-concatenated-string-with-unique-characters/1239-maximum-length-of-a-concatenated-string-with-unique-characters.cpp b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/1239-maximum-length-of-a-concatenated-string-with-unique-characters.cpp new file mode 100644 index 00000000..dfde3d51 --- /dev/null +++ b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/1239-maximum-length-of-a-concatenated-string-with-unique-characters.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + + void helper(int idx, int n, string str, set st, int& maxLength, vector& arr) + { + if(idx == n) + { + maxLength = max(maxLength, (int)str.size()); + return; + } + + helper(idx+1, n, str, st, maxLength, arr); + + bool canTake = true; + + set curr; + + for(auto& ch : arr[idx]) + { + if(curr.count(ch)) + return; + else + curr.insert(ch); + } + + if(canTake) + { + for(auto& ch : curr) + { + if(st.count(ch)) + return; + } + } + + + for(auto& ch : curr) + st.insert(ch); + + helper(idx+1, n, str + arr[idx], st, maxLength, arr); + + for(auto& ch : curr) + st.erase(ch); + + } + + int maxLength(vector& arr) { + + int n = arr.size(); + + set st; + string str; + int maxLength = 0; + + helper(0, n, str, st, maxLength, arr); + + return maxLength; + } +}; \ No newline at end of file diff --git a/1239-maximum-length-of-a-concatenated-string-with-unique-characters/NOTES.md b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1239-maximum-length-of-a-concatenated-string-with-unique-characters/README.md b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/README.md new file mode 100644 index 00000000..32b1a080 --- /dev/null +++ b/1239-maximum-length-of-a-concatenated-string-with-unique-characters/README.md @@ -0,0 +1,44 @@ +

1239. Maximum Length of a Concatenated String with Unique Characters

Medium


You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.

+ +

Return the maximum possible length of s.

+ +

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

+ +

 

+

Example 1:

+ +
Input: arr = ["un","iq","ue"]
+Output: 4
+Explanation: All the valid concatenations are:
+- ""
+- "un"
+- "iq"
+- "ue"
+- "uniq" ("un" + "iq")
+- "ique" ("iq" + "ue")
+Maximum length is 4.
+
+ +

Example 2:

+ +
Input: arr = ["cha","r","act","ers"]
+Output: 6
+Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
+
+ +

Example 3:

+ +
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
+Output: 26
+Explanation: The only string in arr has all 26 characters.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 16
  • +
  • 1 <= arr[i].length <= 26
  • +
  • arr[i] contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1248-count-number-of-nice-subarrays/1248-count-number-of-nice-subarrays.cpp b/1248-count-number-of-nice-subarrays/1248-count-number-of-nice-subarrays.cpp new file mode 100644 index 00000000..aac4bacf --- /dev/null +++ b/1248-count-number-of-nice-subarrays/1248-count-number-of-nice-subarrays.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int numberOfSubarrays(vector& nums, int k) { + + int n = nums.size(); + + int i = 0, j = 0, ans = 0; + + list indexes; + + while(j < n) + { + if(nums[j] & 1) + indexes.push_back(j); + + if(indexes.size() > k) + { + i = indexes.front() + 1; + indexes.pop_front(); + } + + if(indexes.size() == k) ans += (indexes.front() - i + 1); + + ++j; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1248-count-number-of-nice-subarrays/NOTES.md b/1248-count-number-of-nice-subarrays/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1248-count-number-of-nice-subarrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp b/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp new file mode 100644 index 00000000..c1a6bc24 --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + string minRemoveToMakeValid(string s) { + + int n = s.size(); + + stack st; + + for(int i = 0; i < n; ++i) + { + if(!st.empty() and s[st.top()] == '(' and s[i] == ')') + st.pop(); + else if(s[i] == '(' or s[i] == ')') + st.push(i); + } + + while(!st.empty()) + { + s[st.top()] = '#'; + st.pop(); + } + + string ans; + for(int i = 0; i < n; ++i) + { + if(s[i] != '#') + ans += s[i]; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1249-minimum-remove-to-make-valid-parentheses/README.md b/1249-minimum-remove-to-make-valid-parentheses/README.md new file mode 100644 index 00000000..d5ec3542 --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses/README.md @@ -0,0 +1,41 @@ +

1249. Minimum Remove to Make Valid Parentheses

Medium


Given a string s of '(' , ')' and lowercase English characters.

+ +

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

+ +

Formally, a parentheses string is valid if and only if:

+ +
    +
  • It is the empty string, contains only lowercase characters, or
  • +
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • +
  • It can be written as (A), where A is a valid string.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "lee(t(c)o)de)"
+Output: "lee(t(c)o)de"
+Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
+
+ +

Example 2:

+ +
Input: s = "a)b(c)d"
+Output: "ab(c)d"
+
+ +

Example 3:

+ +
Input: s = "))(("
+Output: ""
+Explanation: An empty string is also valid.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either'(' , ')', or lowercase English letter.
  • +
+
\ No newline at end of file diff --git a/1254-number-of-closed-islands/1254-number-of-closed-islands.cpp b/1254-number-of-closed-islands/1254-number-of-closed-islands.cpp new file mode 100644 index 00000000..9aea186b --- /dev/null +++ b/1254-number-of-closed-islands/1254-number-of-closed-islands.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int closedIsland(vector>& grid) { + int res = 0; + for (int i = 0; i < grid.size(); i++){ + for (int j = 0; j < grid[0].size(); j++){ + if (grid[i][j] == 0){ + res += dfs(grid, i, j) ? 1 : 0; + } + } + } + return res; + } + bool dfs(vector>& g, int i, int j){ + if (i < 0 || j < 0 || i >= g.size() || j >= g[0].size()){ + return false; + } + if (g[i][j] == 1){ + return true; + } + g[i][j] = 1; + + bool d1 = dfs(g, i+1, j); + bool d2 = dfs(g, i, j+1); + bool d3 = dfs(g, i-1, j); + bool d4 = dfs(g, i, j-1); + return d1 && d2 && d3 && d4; + } +}; \ No newline at end of file diff --git a/1254-number-of-closed-islands/README.md b/1254-number-of-closed-islands/README.md new file mode 100644 index 00000000..b3f4dc8a --- /dev/null +++ b/1254-number-of-closed-islands/README.md @@ -0,0 +1,42 @@ +

1254. Number of Closed Islands

Medium


Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

+ +

Return the number of closed islands.

+ +

 

+

Example 1:

+ +

+ +
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
+Output: 2
+Explanation: 
+Islands in gray are closed because they are completely surrounded by water (group of 1s).
+ +

Example 2:

+ +

+ +
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
+Output: 1
+
+ +

Example 3:

+ +
Input: grid = [[1,1,1,1,1,1,1],
+               [1,0,0,0,0,0,1],
+               [1,0,1,1,1,0,1],
+               [1,0,1,0,1,0,1],
+               [1,0,1,1,1,0,1],
+               [1,0,0,0,0,0,1],
+               [1,1,1,1,1,1,1]]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= grid.length, grid[0].length <= 100
  • +
  • 0 <= grid[i][j] <=1
  • +
+
\ No newline at end of file diff --git a/1277-count-square-submatrices-with-all-ones/1277-count-square-submatrices-with-all-ones.cpp b/1277-count-square-submatrices-with-all-ones/1277-count-square-submatrices-with-all-ones.cpp new file mode 100644 index 00000000..22a050dd --- /dev/null +++ b/1277-count-square-submatrices-with-all-ones/1277-count-square-submatrices-with-all-ones.cpp @@ -0,0 +1,53 @@ +class Solution { + +private: + int helper(int i, int j, int n, int m, vector>& matrix, vector>& dp) + { + if(i < 0 or j < 0) + return 0; + + if(matrix[i][j] == 0) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + int topLeft = helper(i-1, j-1, n, m, matrix, dp); + int topRight = helper(i-1, j, n, m, matrix, dp); + int bottomLeft = helper(i,j-1, n, m, matrix, dp); + + return dp[i][j] = 1 + min({topLeft, topRight, bottomLeft}); + } + +public: + int countSquares(vector>& matrix) { + + int n = matrix.size(), m = matrix[0].size(); + + vector> dp(n, vector(m, 0)); + + int squareSubmatrices = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(i == 0 or j == 0) + dp[i][j] = matrix[i][j]; + + if(i > 0 and j > 0 and matrix[i][j] != 0) + { + int leftDiag = dp[i-1][j-1]; + int left = dp[i][j-1]; + int top = dp[i-1][j]; + + dp[i][j] = min({leftDiag, left, top}) + 1; + } + + squareSubmatrices += dp[i][j]; + } + } + + return squareSubmatrices; + } +}; \ No newline at end of file diff --git a/1277-count-square-submatrices-with-all-ones/NOTES.md b/1277-count-square-submatrices-with-all-ones/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1277-count-square-submatrices-with-all-ones/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1277-count-square-submatrices-with-all-ones/README.md b/1277-count-square-submatrices-with-all-ones/README.md new file mode 100644 index 00000000..9bd542fa --- /dev/null +++ b/1277-count-square-submatrices-with-all-ones/README.md @@ -0,0 +1,43 @@ +

1277. Count Square Submatrices with All Ones

Medium


Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

+ +

 

+

Example 1:

+ +
Input: matrix =
+[
+  [0,1,1,1],
+  [1,1,1,1],
+  [0,1,1,1]
+]
+Output: 15
+Explanation: 
+There are 10 squares of side 1.
+There are 4 squares of side 2.
+There is  1 square of side 3.
+Total number of squares = 10 + 4 + 1 = 15.
+
+ +

Example 2:

+ +
Input: matrix = 
+[
+  [1,0,1],
+  [1,1,0],
+  [1,1,0]
+]
+Output: 7
+Explanation: 
+There are 6 squares of side 1.  
+There is 1 square of side 2. 
+Total number of squares = 6 + 1 = 7.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 300
  • +
  • 1 <= arr[0].length <= 300
  • +
  • 0 <= arr[i][j] <= 1
  • +
+
\ No newline at end of file diff --git a/1282-group-the-people-given-the-group-size-they-belong-to/1282-group-the-people-given-the-group-size-they-belong-to.cpp b/1282-group-the-people-given-the-group-size-they-belong-to/1282-group-the-people-given-the-group-size-they-belong-to.cpp new file mode 100644 index 00000000..4a6c40d9 --- /dev/null +++ b/1282-group-the-people-given-the-group-size-they-belong-to/1282-group-the-people-given-the-group-size-they-belong-to.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector> groupThePeople(vector& groupSizes) { + + int n = groupSizes.size(); + + unordered_map> mp; + + vector> ans; + + for(int i = 0; i < n; ++i) + { + mp[groupSizes[i]].push_back(i); + + if(mp[groupSizes[i]].size() == groupSizes[i] ) + { + ans.push_back(mp[groupSizes[i]]); + mp[groupSizes[i]].clear(); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1282-group-the-people-given-the-group-size-they-belong-to/NOTES.md b/1282-group-the-people-given-the-group-size-they-belong-to/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1282-group-the-people-given-the-group-size-they-belong-to/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1282-group-the-people-given-the-group-size-they-belong-to/README.md b/1282-group-the-people-given-the-group-size-they-belong-to/README.md new file mode 100644 index 00000000..3861a420 --- /dev/null +++ b/1282-group-the-people-given-the-group-size-they-belong-to/README.md @@ -0,0 +1,35 @@ +

1282. Group the People Given the Group Size They Belong To

Medium


There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.

+ +

You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.

+ +

Return a list of groups such that each person i is in a group of size groupSizes[i].

+ +

Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.

+ +

 

+

Example 1:

+ +
Input: groupSizes = [3,3,3,3,3,1,3]
+Output: [[5],[0,1,2],[3,4,6]]
+Explanation: 
+The first group is [5]. The size is 1, and groupSizes[5] = 1.
+The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
+The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
+Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
+
+ +

Example 2:

+ +
Input: groupSizes = [2,1,3,3,3,2]
+Output: [[1],[0,5],[2,3,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • groupSizes.length == n
  • +
  • 1 <= n <= 500
  • +
  • 1 <= groupSizes[i] <= n
  • +
+
\ No newline at end of file diff --git a/1287-element-appearing-more-than-25-in-sorted-array/1287-element-appearing-more-than-25-in-sorted-array.cpp b/1287-element-appearing-more-than-25-in-sorted-array/1287-element-appearing-more-than-25-in-sorted-array.cpp new file mode 100644 index 00000000..f5a2fa74 --- /dev/null +++ b/1287-element-appearing-more-than-25-in-sorted-array/1287-element-appearing-more-than-25-in-sorted-array.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findSpecialInteger(vector& arr) { + + int n = arr.size(), oneFourth = n/4; + + for(int i = 0; i < n - oneFourth; ++i) + { + if(arr[i] == arr[i+oneFourth]) + return arr[i]; + } + + return -1; + + } +}; \ No newline at end of file diff --git a/1287-element-appearing-more-than-25-in-sorted-array/README.md b/1287-element-appearing-more-than-25-in-sorted-array/README.md new file mode 100644 index 00000000..d7dfbbff --- /dev/null +++ b/1287-element-appearing-more-than-25-in-sorted-array/README.md @@ -0,0 +1,23 @@ +

1287. Element Appearing More Than 25% In Sorted Array

Easy


Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.

+ +

 

+

Example 1:

+ +
Input: arr = [1,2,2,6,6,6,6,7,10]
+Output: 6
+
+ +

Example 2:

+ +
Input: arr = [1,1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 104
  • +
  • 0 <= arr[i] <= 105
  • +
+
\ No newline at end of file diff --git a/1289-minimum-falling-path-sum-ii/1289-minimum-falling-path-sum-ii.cpp b/1289-minimum-falling-path-sum-ii/1289-minimum-falling-path-sum-ii.cpp new file mode 100644 index 00000000..b667b066 --- /dev/null +++ b/1289-minimum-falling-path-sum-ii/1289-minimum-falling-path-sum-ii.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + + int helper(int idx, int prev, int n, vector>& grid, vector>& dp) + { + if(idx == n) + return 0; + + if(dp[idx][prev+1] != -1) + return dp[idx][prev+1]; + + int ans = INT_MAX; + for(int j = 0; j < n; ++j) + { + if(j != prev) + { + int curr = grid[idx][j] + helper(idx+1, j, n, grid, dp); + ans = min(ans, curr); + } + } + + return dp[idx][prev+1] = ans; + } + + int minFallingPathSum(vector>& grid) { + + int n = grid.size(); + vector> dp(n+1, vector(n+1, -1)); + + return helper(0, -1, n, grid, dp); + } +}; \ No newline at end of file diff --git a/1289-minimum-falling-path-sum-ii/README.md b/1289-minimum-falling-path-sum-ii/README.md new file mode 100644 index 00000000..90e5bbb6 --- /dev/null +++ b/1289-minimum-falling-path-sum-ii/README.md @@ -0,0 +1,32 @@ +

1289. Minimum Falling Path Sum II

Hard


Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.

+ +

A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
+Output: 13
+Explanation: 
+The possible falling paths are:
+[1,5,9], [1,5,7], [1,6,7], [1,6,8],
+[2,4,8], [2,4,9], [2,6,7], [2,6,8],
+[3,4,8], [3,4,9], [3,5,7], [3,5,9]
+The falling path with the smallest sum is [1,5,7], so the answer is 13.
+
+ +

Example 2:

+ +
Input: grid = [[7]]
+Output: 7
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 1 <= n <= 200
  • +
  • -99 <= grid[i][j] <= 99
  • +
+
\ No newline at end of file diff --git a/1291-sequential-digits/1291-sequential-digits.cpp b/1291-sequential-digits/1291-sequential-digits.cpp new file mode 100644 index 00000000..180d3292 --- /dev/null +++ b/1291-sequential-digits/1291-sequential-digits.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector sequentialDigits(int low, int high) { + + vector ans; + + for(int i = 1; i <=8; ++i) + { + int currNum = i; + for(int j = i+1; j <= 9; ++j) + { + currNum = (currNum * 10) + j; + + if(currNum >= low and currNum <= high) + ans.push_back(currNum); + } + } + + sort(ans.begin(), ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/1291-sequential-digits/NOTES.md b/1291-sequential-digits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1291-sequential-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1312-minimum-insertion-steps-to-make-a-string-palindrome/README.md b/1312-minimum-insertion-steps-to-make-a-string-palindrome/README.md new file mode 100644 index 00000000..3049ba4a --- /dev/null +++ b/1312-minimum-insertion-steps-to-make-a-string-palindrome/README.md @@ -0,0 +1,36 @@ +

1312. Minimum Insertion Steps to Make a String Palindrome

Hard


Given a string s. In one step you can insert any character at any index of the string.

+ +

Return the minimum number of steps to make s palindrome.

+ +

Palindrome String is one that reads the same backward as well as forward.

+ +

 

+

Example 1:

+ +
Input: s = "zzazz"
+Output: 0
+Explanation: The string "zzazz" is already palindrome we do not need any insertions.
+
+ +

Example 2:

+ +
Input: s = "mbadm"
+Output: 2
+Explanation: String can be "mbdadbm" or "mdbabdm".
+
+ +

Example 3:

+ +
Input: s = "leetcode"
+Output: 5
+Explanation: Inserting 5 characters the string becomes "leetcodocteel".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 500
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1318-minimum-flips-to-make-a-or-b-equal-to-c/1318-minimum-flips-to-make-a-or-b-equal-to-c.cpp b/1318-minimum-flips-to-make-a-or-b-equal-to-c/1318-minimum-flips-to-make-a-or-b-equal-to-c.cpp new file mode 100644 index 00000000..7b0fa96e --- /dev/null +++ b/1318-minimum-flips-to-make-a-or-b-equal-to-c/1318-minimum-flips-to-make-a-or-b-equal-to-c.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minFlips(int a, int b, int c) { + + int ai, bi, ci, cnt = 0; + + while(a or b or c) + { + ai = a & 1; + bi = b & 1; + ci = c & 1; + + if((ai | bi) != ci) + { + if(ai & bi) + cnt += 2; + else + ++cnt; + } + + a >>= 1; + b >>= 1; + c >>= 1; + } + + return cnt; + + } +}; + + \ No newline at end of file diff --git a/1318-minimum-flips-to-make-a-or-b-equal-to-c/NOTES.md b/1318-minimum-flips-to-make-a-or-b-equal-to-c/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1318-minimum-flips-to-make-a-or-b-equal-to-c/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1318-minimum-flips-to-make-a-or-b-equal-to-c/README.md b/1318-minimum-flips-to-make-a-or-b-equal-to-c/README.md new file mode 100644 index 00000000..343f0c92 --- /dev/null +++ b/1318-minimum-flips-to-make-a-or-b-equal-to-c/README.md @@ -0,0 +1,32 @@ +

1318. Minimum Flips to Make a OR b Equal to c

Medium


Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
+Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

+ +

 

+

Example 1:

+ +

+ +
Input: a = 2, b = 6, c = 5
+Output: 3
+Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
+ +

Example 2:

+ +
Input: a = 4, b = 2, c = 7
+Output: 1
+
+ +

Example 3:

+ +
Input: a = 1, b = 2, c = 3
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= a <= 10^9
  • +
  • 1 <= b <= 10^9
  • +
  • 1 <= c <= 10^9
  • +
\ No newline at end of file diff --git a/1319-number-of-operations-to-make-network-connected/1319-number-of-operations-to-make-network-connected.cpp b/1319-number-of-operations-to-make-network-connected/1319-number-of-operations-to-make-network-connected.cpp new file mode 100644 index 00000000..cf1c3117 --- /dev/null +++ b/1319-number-of-operations-to-make-network-connected/1319-number-of-operations-to-make-network-connected.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + + void dfs(int sv, vector& visited, vector adj[]){ + visited[sv] = true; + + for(auto itr : adj[sv]) + { + if(!visited[itr]) + dfs(itr, visited, adj); + } + } + + int makeConnected(int n, vector>& connections) { + + int edges = connections.size(); + + if(n-1 > edges) + return -1; + + vector adj[n+1]; + for(auto itr : connections) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + } + + vector visited(n+1,false); + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + if(!visited[i]) + { + dfs(i, visited, adj); + ++cnt; + } + } + + return cnt - 1; + + } +}; \ No newline at end of file diff --git a/1319-number-of-operations-to-make-network-connected/NOTES.md b/1319-number-of-operations-to-make-network-connected/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1319-number-of-operations-to-make-network-connected/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1319-number-of-operations-to-make-network-connected/README.md b/1319-number-of-operations-to-make-network-connected/README.md new file mode 100644 index 00000000..380130be --- /dev/null +++ b/1319-number-of-operations-to-make-network-connected/README.md @@ -0,0 +1,40 @@ +

1319. Number of Operations to Make Network Connected

Medium


There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.

+ +

You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.

+ +

Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.

+ +

 

+

Example 1:

+ +
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
+Output: 1
+Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
+
+ +

Example 2:

+ +
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
+Output: 2
+
+ +

Example 3:

+ +
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
+Output: -1
+Explanation: There are not enough cables.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 1 <= connections.length <= min(n * (n - 1) / 2, 105)
  • +
  • connections[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • There are no repeated connections.
  • +
  • No two computers are connected by more than one cable.
  • +
+
\ No newline at end of file diff --git a/1325-delete-leaves-with-a-given-value/1325-delete-leaves-with-a-given-value.cpp b/1325-delete-leaves-with-a-given-value/1325-delete-leaves-with-a-given-value.cpp new file mode 100644 index 00000000..16914d74 --- /dev/null +++ b/1325-delete-leaves-with-a-given-value/1325-delete-leaves-with-a-given-value.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + TreeNode* helper(TreeNode* root, int target) + { + if(!root) + return nullptr; + + TreeNode* left = helper(root->left, target); + TreeNode* right = helper(root->right, target); + + if(!left) + root->left = nullptr; + + if(!right) + root->right = nullptr; + + if(!left and !right and root->val == target) + { + return nullptr; + } + return root; + } + + + TreeNode* removeLeafNodes(TreeNode* root, int target) { + + return helper(root, target); + + } +}; \ No newline at end of file diff --git a/1325-delete-leaves-with-a-given-value/README.md b/1325-delete-leaves-with-a-given-value/README.md new file mode 100644 index 00000000..23f321db --- /dev/null +++ b/1325-delete-leaves-with-a-given-value/README.md @@ -0,0 +1,40 @@ +

1325. Delete Leaves With a Given Value

Medium


Given a binary tree root and an integer target, delete all the leaf nodes with value target.

+ +

Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).

+ +

 

+

Example 1:

+ +

+ +
Input: root = [1,2,3,2,null,2,4], target = 2
+Output: [1,null,3,null,4]
+Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). 
+After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
+
+ +

Example 2:

+ +

+ +
Input: root = [1,3,3,3,2], target = 3
+Output: [1,3,null,null,2]
+
+ +

Example 3:

+ +

+ +
Input: root = [1,2,null,2,null,2], target = 2
+Output: [1]
+Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3000].
  • +
  • 1 <= Node.val, target <= 1000
  • +
+
\ No newline at end of file diff --git a/1326-minimum-number-of-taps-to-open-to-water-a-garden/1326-minimum-number-of-taps-to-open-to-water-a-garden.cpp b/1326-minimum-number-of-taps-to-open-to-water-a-garden/1326-minimum-number-of-taps-to-open-to-water-a-garden.cpp new file mode 100644 index 00000000..f3542250 --- /dev/null +++ b/1326-minimum-number-of-taps-to-open-to-water-a-garden/1326-minimum-number-of-taps-to-open-to-water-a-garden.cpp @@ -0,0 +1,44 @@ +class Solution { + +private: + int helper(int idx, int maxEnd, int n, vector >& startEnd, map,int>& dp) + { + if(idx == startEnd.size()) + return (maxEnd >= n ? 0 : 1e9); + + if(dp.find({idx, maxEnd}) != dp.end()) + return dp[{idx, maxEnd}]; + + if(maxEnd < startEnd[idx].first) + return 1e9; + + int notTake = helper(idx+1, maxEnd, n, startEnd, dp); + + int take = 1 + helper(idx+1, max(maxEnd,startEnd[idx].second), n, startEnd , dp); + + return dp[{idx, maxEnd}] = min(take, notTake); + } + +public: + int minTaps(int n, vector& ranges) { + + vector > startEnd; + + for(int i = 0; i < ranges.size(); ++i) + { + int start = max(0, i - ranges[i]); + int end = min(n, i + ranges[i]); + + startEnd.push_back({start, end}); + } + + sort(startEnd.begin(), startEnd.end()); + + map,int> dp; + + int ans = helper(0, 0, n, startEnd, dp); + + return (ans == 1e9 ? -1 : ans); + + } +}; \ No newline at end of file diff --git a/1326-minimum-number-of-taps-to-open-to-water-a-garden/NOTES.md b/1326-minimum-number-of-taps-to-open-to-water-a-garden/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1326-minimum-number-of-taps-to-open-to-water-a-garden/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1326-minimum-number-of-taps-to-open-to-water-a-garden/README.md b/1326-minimum-number-of-taps-to-open-to-water-a-garden/README.md new file mode 100644 index 00000000..ce218a32 --- /dev/null +++ b/1326-minimum-number-of-taps-to-open-to-water-a-garden/README.md @@ -0,0 +1,38 @@ +

1326. Minimum Number of Taps to Open to Water a Garden

Hard


There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).

+ +

There are n + 1 taps located at points [0, 1, ..., n] in the garden.

+ +

Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.

+ +

Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.

+ +

 

+

Example 1:

+ +
Input: n = 5, ranges = [3,4,1,1,0,0]
+Output: 1
+Explanation: The tap at point 0 can cover the interval [-3,3]
+The tap at point 1 can cover the interval [-3,5]
+The tap at point 2 can cover the interval [1,3]
+The tap at point 3 can cover the interval [2,4]
+The tap at point 4 can cover the interval [4,4]
+The tap at point 5 can cover the interval [5,5]
+Opening Only the second tap will water the whole garden [0,5]
+
+ +

Example 2:

+ +
Input: n = 3, ranges = [0,0,0,0]
+Output: -1
+Explanation: Even if you activate all the four taps you cannot water the whole garden.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
  • ranges.length == n + 1
  • +
  • 0 <= ranges[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cpp b/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cpp new file mode 100644 index 00000000..871c7262 --- /dev/null +++ b/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + + vector> mat(n, vector(n, 1e9)); + + for(auto itr : edges) + { + int i = itr[0]; + int j = itr[1]; + int wt = itr[2]; + + mat[i][j] = wt; + mat[j][i] = wt; + } + + for(int k = 0; k < n; ++k) + { + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(i == j) + mat[i][j] = 0; + + mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j]); + } + } + } + + // for(auto itr : mat) + // { + // for(auto x : itr) + // cout<> vp; + + for(int i = 0; i < n; ++i) + { + int cnt = 0; + for(int j = 0; j < n; ++j) + { + if(mat[i][j] <= distanceThreshold) + { + ++cnt; + } + } + vp.push_back({cnt, i}); + } + + sort(vp.begin(), vp.end(),[&](const auto &a, const auto &b){ + if(a.first == b.first) + return a.second > b.second; + return a.first < b.first; + }); + + // for(auto itr : vp) + // cout<1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance

Medium


There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.

+ +

Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.

+ +

Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

+ +

 

+

Example 1:

+ +
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
+Output: 3
+Explanation: The figure above describes the graph. 
+The neighboring cities at a distanceThreshold = 4 for each city are:
+City 0 -> [City 1, City 2] 
+City 1 -> [City 0, City 2, City 3] 
+City 2 -> [City 0, City 1, City 3] 
+City 3 -> [City 1, City 2] 
+Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
+
+ +

Example 2:

+ +
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
+Output: 0
+Explanation: The figure above describes the graph. 
+The neighboring cities at a distanceThreshold = 2 for each city are:
+City 0 -> [City 1] 
+City 1 -> [City 0, City 4] 
+City 2 -> [City 3, City 4] 
+City 3 -> [City 2, City 4]
+City 4 -> [City 1, City 2, City 3] 
+The city 0 has 1 neighboring city at a distanceThreshold = 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 100
  • +
  • 1 <= edges.length <= n * (n - 1) / 2
  • +
  • edges[i].length == 3
  • +
  • 0 <= fromi < toi < n
  • +
  • 1 <= weighti, distanceThreshold <= 10^4
  • +
  • All pairs (fromi, toi) are distinct.
  • +
+
\ No newline at end of file diff --git a/1335-minimum-difficulty-of-a-job-schedule/1335-minimum-difficulty-of-a-job-schedule.cpp b/1335-minimum-difficulty-of-a-job-schedule/1335-minimum-difficulty-of-a-job-schedule.cpp new file mode 100644 index 00000000..8f18eb59 --- /dev/null +++ b/1335-minimum-difficulty-of-a-job-schedule/1335-minimum-difficulty-of-a-job-schedule.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int t[301][11]; + int solve(vector& mat, int n, int idx, int d) { + if(d == 1) + return *max_element(begin(mat)+idx, end(mat)); + + if(t[idx][d] != -1) + return t[idx][d]; + + + int Max = INT_MIN; + int result = INT_MAX; + + for(int i = idx; i<=n-d; i++) { + Max = max(Max, mat[i]); + result = min(result, Max + solve(mat, n, i+1, d-1)); + } + return t[idx][d] = result; + } + + int minDifficulty(vector& jobDifficulty, int d) { + int n = jobDifficulty.size(); + if(n < d) + return -1; + memset(t, -1, sizeof(t)); + return solve(jobDifficulty, n, 0, d); + } +}; \ No newline at end of file diff --git a/1335-minimum-difficulty-of-a-job-schedule/README.md b/1335-minimum-difficulty-of-a-job-schedule/README.md new file mode 100644 index 00000000..2c1f6130 --- /dev/null +++ b/1335-minimum-difficulty-of-a-job-schedule/README.md @@ -0,0 +1,41 @@ +

1335. Minimum Difficulty of a Job Schedule

Hard


You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).

+ +

You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.

+ +

You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].

+ +

Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

+ +

 

+

Example 1:

+ +
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
+Output: 7
+Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
+Second day you can finish the last job, total difficulty = 1.
+The difficulty of the schedule = 6 + 1 = 7 
+
+ +

Example 2:

+ +
Input: jobDifficulty = [9,9,9], d = 4
+Output: -1
+Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
+
+ +

Example 3:

+ +
Input: jobDifficulty = [1,1,1], d = 3
+Output: 3
+Explanation: The schedule is one job per day. total difficulty will be 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= jobDifficulty.length <= 300
  • +
  • 0 <= jobDifficulty[i] <= 1000
  • +
  • 1 <= d <= 10
  • +
+
\ No newline at end of file diff --git a/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp b/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp new file mode 100644 index 00000000..303f9688 --- /dev/null +++ b/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + + int n = mat.size(); + int m = mat[0].size(); + + vector ans; + + priority_queue, vector>, greater> > pq; + + for(int i = 0; i < n; ++i) + { + int currRowOnesCount = 0; + for(int j = 0; j < m; ++j) + { + if(mat[i][j] == 1) + ++currRowOnesCount; + else + break; + } + + pq.push({currRowOnesCount, i}); + } + + while(k--) + { + int kthWeakestIdx = pq.top().second; + pq.pop(); + + ans.push_back(kthWeakestIdx); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1337-the-k-weakest-rows-in-a-matrix/README.md b/1337-the-k-weakest-rows-in-a-matrix/README.md new file mode 100644 index 00000000..7f0784e5 --- /dev/null +++ b/1337-the-k-weakest-rows-in-a-matrix/README.md @@ -0,0 +1,61 @@ +

1337. The K Weakest Rows in a Matrix

Easy


You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

+ +

A row i is weaker than a row j if one of the following is true:

+ +
    +
  • The number of soldiers in row i is less than the number of soldiers in row j.
  • +
  • Both rows have the same number of soldiers and i < j.
  • +
+ +

Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

+ +

 

+

Example 1:

+ +
Input: mat = 
+[[1,1,0,0,0],
+ [1,1,1,1,0],
+ [1,0,0,0,0],
+ [1,1,0,0,0],
+ [1,1,1,1,1]], 
+k = 3
+Output: [2,0,3]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 2 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 2 
+- Row 4: 5 
+The rows ordered from weakest to strongest are [2,0,3,1,4].
+
+ +

Example 2:

+ +
Input: mat = 
+[[1,0,0,0],
+ [1,1,1,1],
+ [1,0,0,0],
+ [1,0,0,0]], 
+k = 2
+Output: [0,2]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 1 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 1 
+The rows ordered from weakest to strongest are [0,2,3,1].
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 2 <= n, m <= 100
  • +
  • 1 <= k <= m
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1339-maximum-product-of-splitted-binary-tree/1339-maximum-product-of-splitted-binary-tree.cpp b/1339-maximum-product-of-splitted-binary-tree/1339-maximum-product-of-splitted-binary-tree.cpp new file mode 100644 index 00000000..b65b0497 --- /dev/null +++ b/1339-maximum-product-of-splitted-binary-tree/1339-maximum-product-of-splitted-binary-tree.cpp @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + +private: + + long long total = 0 , ans = 0; + + int mod = 1e9 + 7; + + int helper(TreeNode* root) + { + if(!root) + return 0; + + int left = helper(root->left); + int right = helper(root->right); + + int subTree = left + right + root->val; + + ans = max(ans, ((total - subTree) * subTree)); + + return subTree; + } + + +public: + int maxProduct(TreeNode* root) { + + total = helper(root); + + helper(root); + + return ans % mod;; + + + + } +}; \ No newline at end of file diff --git a/1339-maximum-product-of-splitted-binary-tree/NOTES.md b/1339-maximum-product-of-splitted-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1339-maximum-product-of-splitted-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1339-maximum-product-of-splitted-binary-tree/README.md b/1339-maximum-product-of-splitted-binary-tree/README.md new file mode 100644 index 00000000..06088e64 --- /dev/null +++ b/1339-maximum-product-of-splitted-binary-tree/README.md @@ -0,0 +1,29 @@ +

1339. Maximum Product of Splitted Binary Tree

Medium


Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.

+ +

Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.

+ +

Note that you need to maximize the answer before taking the mod and not after taking it.

+ +

 

+

Example 1:

+ +
Input: root = [1,2,3,4,5,6]
+Output: 110
+Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
+
+ +

Example 2:

+ +
Input: root = [1,null,2,3,4,null,null,5,6]
+Output: 90
+Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 5 * 104].
  • +
  • 1 <= Node.val <= 104
  • +
+
\ No newline at end of file diff --git a/1345-jump-game-iv/1345-jump-game-iv.cpp b/1345-jump-game-iv/1345-jump-game-iv.cpp new file mode 100644 index 00000000..38d0c179 --- /dev/null +++ b/1345-jump-game-iv/1345-jump-game-iv.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minJumps(vector& arr) { + int n = arr.size(); + unordered_map> indicesOfValue; + for (int i = 0; i < n; i++) + indicesOfValue[arr[i]].push_back(i); + vector visited(n); visited[0] = true; + queue q; q.push(0); + int step = 0; + while (!q.empty()) { + for (int size = q.size(); size > 0; --size) { + int i = q.front(); q.pop(); + if (i == n - 1) return step; // Reached to last index + vector& next = indicesOfValue[arr[i]]; + next.push_back(i - 1); next.push_back(i + 1); + for (int j : next) { + if (j >= 0 && j < n && !visited[j]) { + visited[j] = true; + q.push(j); + } + } + next.clear(); // avoid later lookup indicesOfValue arr[i] + } + step++; + } + return 0; + } +}; \ No newline at end of file diff --git a/1345-jump-game-iv/README.md b/1345-jump-game-iv/README.md new file mode 100644 index 00000000..0dd40e5a --- /dev/null +++ b/1345-jump-game-iv/README.md @@ -0,0 +1,44 @@ +

1345. Jump Game IV

Hard


Given an array of integers arr, you are initially positioned at the first index of the array.

+ +

In one step you can jump from index i to index:

+ +
    +
  • i + 1 where: i + 1 < arr.length.
  • +
  • i - 1 where: i - 1 >= 0.
  • +
  • j where: arr[i] == arr[j] and i != j.
  • +
+ +

Return the minimum number of steps to reach the last index of the array.

+ +

Notice that you can not jump outside of the array at any time.

+ +

 

+

Example 1:

+ +
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
+Output: 3
+Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
+
+ +

Example 2:

+ +
Input: arr = [7]
+Output: 0
+Explanation: Start index is the last index. You do not need to jump.
+
+ +

Example 3:

+ +
Input: arr = [7,6,9,6,9,6,9,7]
+Output: 1
+Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 5 * 104
  • +
  • -108 <= arr[i] <= 108
  • +
+
\ No newline at end of file diff --git a/1347-minimum-number-of-steps-to-make-two-strings-anagram/1347-minimum-number-of-steps-to-make-two-strings-anagram.cpp b/1347-minimum-number-of-steps-to-make-two-strings-anagram/1347-minimum-number-of-steps-to-make-two-strings-anagram.cpp new file mode 100644 index 00000000..2a4429de --- /dev/null +++ b/1347-minimum-number-of-steps-to-make-two-strings-anagram/1347-minimum-number-of-steps-to-make-two-strings-anagram.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minSteps(string s, string t) { + + map mp; + + int need = 0; + + for(auto& ele : s) + ++mp[ele]; + + for(auto& ele : t) + { + if(mp[ele] > 0) + { + --mp[ele]; + if(mp[ele] == 0) + mp.erase(ele); + } + else + ++need; + } + + return need; + } +}; \ No newline at end of file diff --git a/1347-minimum-number-of-steps-to-make-two-strings-anagram/NOTES.md b/1347-minimum-number-of-steps-to-make-two-strings-anagram/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1347-minimum-number-of-steps-to-make-two-strings-anagram/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1347-minimum-number-of-steps-to-make-two-strings-anagram/README.md b/1347-minimum-number-of-steps-to-make-two-strings-anagram/README.md new file mode 100644 index 00000000..6838a54f --- /dev/null +++ b/1347-minimum-number-of-steps-to-make-two-strings-anagram/README.md @@ -0,0 +1,37 @@ +

1347. Minimum Number of Steps to Make Two Strings Anagram

Medium


You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

+ +

Return the minimum number of steps to make t an anagram of s.

+ +

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

+ +

 

+

Example 1:

+ +
Input: s = "bab", t = "aba"
+Output: 1
+Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
+
+ +

Example 2:

+ +
Input: s = "leetcode", t = "practice"
+Output: 5
+Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
+
+ +

Example 3:

+ +
Input: s = "anagram", t = "mangaar"
+Output: 0
+Explanation: "anagram" and "mangaar" are anagrams. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s.length == t.length
  • +
  • s and t consist of lowercase English letters only.
  • +
+
\ No newline at end of file diff --git a/1351-count-negative-numbers-in-a-sorted-matrix/1351-count-negative-numbers-in-a-sorted-matrix.cpp b/1351-count-negative-numbers-in-a-sorted-matrix/1351-count-negative-numbers-in-a-sorted-matrix.cpp new file mode 100644 index 00000000..5629b207 --- /dev/null +++ b/1351-count-negative-numbers-in-a-sorted-matrix/1351-count-negative-numbers-in-a-sorted-matrix.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int countNegatives(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + int i = n-1, j = 0; + + int negCnt = 0; + + while(i >= 0 and j < m) + { + if(grid[i][j] >= 0) + ++j; + else + { + negCnt += m - j; + --i; + } + } + + return negCnt; + + } +}; \ No newline at end of file diff --git a/1351-count-negative-numbers-in-a-sorted-matrix/NOTES.md b/1351-count-negative-numbers-in-a-sorted-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1351-count-negative-numbers-in-a-sorted-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1351-count-negative-numbers-in-a-sorted-matrix/README.md b/1351-count-negative-numbers-in-a-sorted-matrix/README.md new file mode 100644 index 00000000..644b880a --- /dev/null +++ b/1351-count-negative-numbers-in-a-sorted-matrix/README.md @@ -0,0 +1,28 @@ +

1351. Count Negative Numbers in a Sorted Matrix

Easy


Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

+ +

 

+

Example 1:

+ +
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
+Output: 8
+Explanation: There are 8 negatives number in the matrix.
+
+ +

Example 2:

+ +
Input: grid = [[3,2],[1,0]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -100 <= grid[i][j] <= 100
  • +
+ +

 

+Follow up: Could you find an O(n + m) solution?
\ No newline at end of file diff --git a/1358-number-of-substrings-containing-all-three-characters/NOTES.md b/1358-number-of-substrings-containing-all-three-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1358-number-of-substrings-containing-all-three-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1358-number-of-substrings-containing-all-three-characters/README.md b/1358-number-of-substrings-containing-all-three-characters/README.md new file mode 100644 index 00000000..fbdc7088 --- /dev/null +++ b/1358-number-of-substrings-containing-all-three-characters/README.md @@ -0,0 +1,33 @@ +

1358. Number of Substrings Containing All Three Characters

Medium


Given a string s consisting only of characters a, b and c.

+ +

Return the number of substrings containing at least one occurrence of all these characters a, b and c.

+ +

 

+

Example 1:

+ +
Input: s = "abcabc"
+Output: 10
+Explanation: The substrings containing at least one occurrence of the characters ab and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). 
+
+ +

Example 2:

+ +
Input: s = "aaacb"
+Output: 3
+Explanation: The substrings containing at least one occurrence of the characters ab and c are "aaacb", "aacb" and "acb". 
+
+ +

Example 3:

+ +
Input: s = "abc"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= s.length <= 5 x 10^4
  • +
  • s only consists of a, b or characters.
  • +
+
\ No newline at end of file diff --git a/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp b/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp new file mode 100644 index 00000000..2958330b --- /dev/null +++ b/1359-count-all-valid-pickup-and-delivery-options/1359-count-all-valid-pickup-and-delivery-options.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countOrders(int n) { + int odd=3, mod=1e9+7; + long long ans=1; + for(int i=2; i<=n; i++) + { + int sum = (odd)*(odd+1)%mod/2; + ans=ans*sum%mod; + odd+=2; + } + return ans%mod; + } +}; \ No newline at end of file diff --git a/1359-count-all-valid-pickup-and-delivery-options/README.md b/1359-count-all-valid-pickup-and-delivery-options/README.md new file mode 100644 index 00000000..35b4e77b --- /dev/null +++ b/1359-count-all-valid-pickup-and-delivery-options/README.md @@ -0,0 +1,36 @@ +

1359. Count All Valid Pickup and Delivery Options

Hard


Given n orders, each order consist in pickup and delivery services. 

+ +

Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). 

+ +

Since the answer may be too large, return it modulo 10^9 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 1
+Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 6
+Explanation: All possible orders: 
+(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
+This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
+
+ +

Example 3:

+ +
Input: n = 3
+Output: 90
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 500
  • +
+
\ No newline at end of file diff --git a/1372-longest-zigzag-path-in-a-binary-tree/1372-longest-zigzag-path-in-a-binary-tree.cpp b/1372-longest-zigzag-path-in-a-binary-tree/1372-longest-zigzag-path-in-a-binary-tree.cpp new file mode 100644 index 00000000..4eb706c6 --- /dev/null +++ b/1372-longest-zigzag-path-in-a-binary-tree/1372-longest-zigzag-path-in-a-binary-tree.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int maxi; + + void helper(TreeNode* root, int dir, int len) + { + if(!root) + return; + + maxi = max(maxi,len); + + if(dir == 0) + { + helper(root->left, dir, 1); + helper(root->right, dir ^ 1, len + 1); + } + else + { + helper(root->left, dir ^ 1, len + 1); + helper(root->right, dir, 1); + } + } + + int longestZigZag(TreeNode* root) { + + maxi = 0; + + helper(root->left, 0, 1); + + helper(root->right, 1, 1); + + return maxi; + + } +}; \ No newline at end of file diff --git a/1372-longest-zigzag-path-in-a-binary-tree/README.md b/1372-longest-zigzag-path-in-a-binary-tree/README.md new file mode 100644 index 00000000..c56b9308 --- /dev/null +++ b/1372-longest-zigzag-path-in-a-binary-tree/README.md @@ -0,0 +1,44 @@ +

1372. Longest ZigZag Path in a Binary Tree

Medium


You are given the root of a binary tree.

+ +

A ZigZag path for a binary tree is defined as follow:

+ +
    +
  • Choose any node in the binary tree and a direction (right or left).
  • +
  • If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
  • +
  • Change the direction from right to left or from left to right.
  • +
  • Repeat the second and third steps until you can't move in the tree.
  • +
+ +

Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).

+ +

Return the longest ZigZag path contained in that tree.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
+Output: 3
+Explanation: Longest ZigZag path in blue nodes (right -> left -> right).
+
+ +

Example 2:

+ +
Input: root = [1,1,1,null,1,null,null,1,1,null,1]
+Output: 4
+Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 5 * 104].
  • +
  • 1 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/1376-time-needed-to-inform-all-employees/1376-time-needed-to-inform-all-employees.cpp b/1376-time-needed-to-inform-all-employees/1376-time-needed-to-inform-all-employees.cpp new file mode 100644 index 00000000..1dee47a8 --- /dev/null +++ b/1376-time-needed-to-inform-all-employees/1376-time-needed-to-inform-all-employees.cpp @@ -0,0 +1,70 @@ +class Solution { + +private: + void dfs(int sv, vector> adj[], vector& visited, int& ans) + { + visited[sv] = true; + + for(auto itr : adj[sv]) + { + int child = itr.first; + int time = itr.second; + + if(!visited[child]) + { + ans += time; + dfs(child, adj, visited, ans); + } + } + } + +public: + int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { + + vector> adj[n+1]; + + for(int i = 0; i < n; ++i) + { + if(manager[i] == -1) + continue; + + adj[manager[i]].push_back({i, informTime[manager[i]]}); + } + + int ans = 0; + + vector visited(n+1, false); + + // dfs(headID, adj, visited, ans); + + queue> q; + + q.push({headID ,0}); + + visited[headID] = true; + + while(!q.empty()) + { + int node = q.front().first; + int time = q.front().second; + + q.pop(); + + ans = max(ans, time); + + for(auto itr : adj[node]) + { + int child = itr.first; + int currTime = itr.second; + + if(!visited[child]) + { + visited[child] = true; + q.push({child, time + currTime}); + } + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1376-time-needed-to-inform-all-employees/NOTES.md b/1376-time-needed-to-inform-all-employees/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1376-time-needed-to-inform-all-employees/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1376-time-needed-to-inform-all-employees/README.md b/1376-time-needed-to-inform-all-employees/README.md new file mode 100644 index 00000000..878da7c5 --- /dev/null +++ b/1376-time-needed-to-inform-all-employees/README.md @@ -0,0 +1,41 @@ +

1376. Time Needed to Inform All Employees

Medium


A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.

+ +

Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.

+ +

The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.

+ +

The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).

+ +

Return the number of minutes needed to inform all the employees about the urgent news.

+ +

 

+

Example 1:

+ +
Input: n = 1, headID = 0, manager = [-1], informTime = [0]
+Output: 0
+Explanation: The head of the company is the only employee in the company.
+
+ +

Example 2:

+ +
Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
+Output: 1
+Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
+The tree structure of the employees in the company is shown.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 0 <= headID < n
  • +
  • manager.length == n
  • +
  • 0 <= manager[i] < n
  • +
  • manager[headID] == -1
  • +
  • informTime.length == n
  • +
  • 0 <= informTime[i] <= 1000
  • +
  • informTime[i] == 0 if employee i has no subordinates.
  • +
  • It is guaranteed that all the employees can be informed.
  • +
+
\ No newline at end of file diff --git a/1378-replace-employee-id-with-the-unique-identifier/1378-replace-employee-id-with-the-unique-identifier.sql b/1378-replace-employee-id-with-the-unique-identifier/1378-replace-employee-id-with-the-unique-identifier.sql new file mode 100644 index 00000000..9fce03ec --- /dev/null +++ b/1378-replace-employee-id-with-the-unique-identifier/1378-replace-employee-id-with-the-unique-identifier.sql @@ -0,0 +1,6 @@ +# Write your MySQL query statement below + + +select e2.unique_id , e1.name from Employees e1 +left join EmployeeUNI e2 +on e1.id = e2.id; \ No newline at end of file diff --git a/1378-replace-employee-id-with-the-unique-identifier/NOTES.md b/1378-replace-employee-id-with-the-unique-identifier/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1378-replace-employee-id-with-the-unique-identifier/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1378-replace-employee-id-with-the-unique-identifier/README.md b/1378-replace-employee-id-with-the-unique-identifier/README.md new file mode 100644 index 00000000..283a0d5d --- /dev/null +++ b/1378-replace-employee-id-with-the-unique-identifier/README.md @@ -0,0 +1,73 @@ +

1378. Replace Employee ID With The Unique Identifier

Easy


Table: Employees

+ +
+---------------+---------+
+| Column Name   | Type    |
++---------------+---------+
+| id            | int     |
+| name          | varchar |
++---------------+---------+
+id is the primary key (column with unique values) for this table.
+Each row of this table contains the id and the name of an employee in a company.
+
+ +

 

+ +

Table: EmployeeUNI

+ +
+---------------+---------+
+| Column Name   | Type    |
++---------------+---------+
+| id            | int     |
+| unique_id     | int     |
++---------------+---------+
+(id, unique_id) is the primary key (combination of columns with unique values) for this table.
+Each row of this table contains the id and the corresponding unique id of an employee in the company.
+
+ +

 

+ +

Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show null.

+ +

Return the result table in any order.

+ +

The result format is in the following example.

+ +

 

+

Example 1:

+ +
Input: 
+Employees table:
++----+----------+
+| id | name     |
++----+----------+
+| 1  | Alice    |
+| 7  | Bob      |
+| 11 | Meir     |
+| 90 | Winston  |
+| 3  | Jonathan |
++----+----------+
+EmployeeUNI table:
++----+-----------+
+| id | unique_id |
++----+-----------+
+| 3  | 1         |
+| 11 | 2         |
+| 90 | 3         |
++----+-----------+
+Output: 
++-----------+----------+
+| unique_id | name     |
++-----------+----------+
+| null      | Alice    |
+| null      | Bob      |
+| 2         | Meir     |
+| 3         | Winston  |
+| 1         | Jonathan |
++-----------+----------+
+Explanation: 
+Alice and Bob do not have a unique ID, We will show null instead.
+The unique ID of Meir is 2.
+The unique ID of Winston is 3.
+The unique ID of Jonathan is 1.
+
+
\ No newline at end of file diff --git a/1380-lucky-numbers-in-a-matrix/1380-lucky-numbers-in-a-matrix.cpp b/1380-lucky-numbers-in-a-matrix/1380-lucky-numbers-in-a-matrix.cpp new file mode 100644 index 00000000..3d76be27 --- /dev/null +++ b/1380-lucky-numbers-in-a-matrix/1380-lucky-numbers-in-a-matrix.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector luckyNumbers (vector>& matrix) { + vector ans; + int r = matrix.size(); + int c = matrix[0].size(); + + vector rmin(r,INT_MAX); + vector cmax(c,INT_MIN); + + for(int i = 0; i1380. Lucky Numbers in a Matrix

Easy


Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

+ +

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

+ +

 

+

Example 1:

+ +
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
+Output: [15]
+Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
+
+ +

Example 2:

+ +
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
+Output: [12]
+Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
+
+ +

Example 3:

+ +
Input: matrix = [[7,8],[1,2]]
+Output: [7]
+Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 1 <= n, m <= 50
  • +
  • 1 <= matrix[i][j] <= 105.
  • +
  • All elements in the matrix are distinct.
  • +
+
\ No newline at end of file diff --git a/1382-balance-a-binary-search-tree/1382-balance-a-binary-search-tree.cpp b/1382-balance-a-binary-search-tree/1382-balance-a-binary-search-tree.cpp new file mode 100644 index 00000000..6ee5d2f7 --- /dev/null +++ b/1382-balance-a-binary-search-tree/1382-balance-a-binary-search-tree.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void inorder(TreeNode* root, vector& arr) + { + if(root) + { + inorder(root->left, arr); + arr.push_back(root->val); + inorder(root->right, arr); + } + } + + TreeNode* balance(vector& arr, int low, int high) + { + if(low > high) + return nullptr; + + int mid = (low + high) / 2; + + TreeNode* root = new TreeNode(arr[mid]); + + root->left = balance(arr, low, mid-1); + + root->right = balance(arr, mid+1, high); + + return root; + + } + + TreeNode* balanceBST(TreeNode* root) { + + vector arr; + + inorder(root, arr); + + return balance(arr, 0, arr.size()-1); + + } +}; \ No newline at end of file diff --git a/1382-balance-a-binary-search-tree/NOTES.md b/1382-balance-a-binary-search-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1382-balance-a-binary-search-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1382-balance-a-binary-search-tree/README.md b/1382-balance-a-binary-search-tree/README.md new file mode 100644 index 00000000..b30659a0 --- /dev/null +++ b/1382-balance-a-binary-search-tree/README.md @@ -0,0 +1,26 @@ +

1382. Balance a Binary Search Tree

Medium


Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.

+ +

A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,null,3,null,4,null,null]
+Output: [2,1,3,null,null,null,4]
+Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
+
+ +

Example 2:

+ +
Input: root = [2,1,3]
+Output: [2,1,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 1 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/1395-count-number-of-teams/README.md b/1395-count-number-of-teams/README.md new file mode 100644 index 00000000..e0ebb7f2 --- /dev/null +++ b/1395-count-number-of-teams/README.md @@ -0,0 +1,42 @@ +

1395. Count Number of Teams

Medium


There are n soldiers standing in a line. Each soldier is assigned a unique rating value.

+ +

You have to form a team of 3 soldiers amongst them under the following rules:

+ +
    +
  • Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
  • +
  • A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
  • +
+ +

Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).

+ +

 

+

Example 1:

+ +
Input: rating = [2,5,3,4,1]
+Output: 3
+Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). 
+
+ +

Example 2:

+ +
Input: rating = [2,1,3]
+Output: 0
+Explanation: We can't form any team given the conditions.
+
+ +

Example 3:

+ +
Input: rating = [1,2,3,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • n == rating.length
  • +
  • 3 <= n <= 1000
  • +
  • 1 <= rating[i] <= 105
  • +
  • All the integers in rating are unique.
  • +
+
\ No newline at end of file diff --git a/1396-design-underground-system/1396-design-underground-system.cpp b/1396-design-underground-system/1396-design-underground-system.cpp new file mode 100644 index 00000000..ee8060bd --- /dev/null +++ b/1396-design-underground-system/1396-design-underground-system.cpp @@ -0,0 +1,59 @@ +class UndergroundSystem { + +private: + map> mp; + map, pair> links; + +public: + + UndergroundSystem() { + + } + + void checkIn(int id, string stationName, int t) { + mp.insert({id, {stationName, t}}); + } + + void checkOut(int id, string stationName, int t) { + + auto inTime = mp[id]; + + string checkInStationName = inTime.first; + double checkInStationTime = inTime.second; + + double currTime = t - checkInStationTime; + + if(links.find({checkInStationName,stationName}) != links.end()) + { + auto here = links[{checkInStationName,stationName}]; + + int cnt = here.first; + + double prevValue = here.second; + + links[{checkInStationName, stationName}]={cnt + 1, prevValue + currTime}; + } + else + { + links.insert({{checkInStationName, stationName},{1, currTime}}); + } + + mp.erase(id); + } + + double getAverageTime(string startStation, string endStation) { + + auto here = links[{startStation, endStation}]; + + return (double)(here.second/here.first); + + } +}; + +/** + * Your UndergroundSystem object will be instantiated and called as such: + * UndergroundSystem* obj = new UndergroundSystem(); + * obj->checkIn(id,stationName,t); + * obj->checkOut(id,stationName,t); + * double param_3 = obj->getAverageTime(startStation,endStation); + */ \ No newline at end of file diff --git a/1396-design-underground-system/NOTES.md b/1396-design-underground-system/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1396-design-underground-system/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1396-design-underground-system/README.md b/1396-design-underground-system/README.md new file mode 100644 index 00000000..552117d8 --- /dev/null +++ b/1396-design-underground-system/README.md @@ -0,0 +1,88 @@ +

1396. Design Underground System

Medium


An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

+ +

Implement the UndergroundSystem class:

+ +
    +
  • void checkIn(int id, string stationName, int t) + +
      +
    • A customer with a card ID equal to id, checks in at the station stationName at time t.
    • +
    • A customer can only be checked into one place at a time.
    • +
    +
  • +
  • void checkOut(int id, string stationName, int t) +
      +
    • A customer with a card ID equal to id, checks out from the station stationName at time t.
    • +
    +
  • +
  • double getAverageTime(string startStation, string endStation) +
      +
    • Returns the average time it takes to travel from startStation to endStation.
    • +
    • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
    • +
    • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
    • +
    • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
    • +
    +
  • +
+ +

You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

+ +

 

+

Example 1:

+ +
Input
+["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
+[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
+
+Output
+[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
+
+Explanation
+UndergroundSystem undergroundSystem = new UndergroundSystem();
+undergroundSystem.checkIn(45, "Leyton", 3);
+undergroundSystem.checkIn(32, "Paradise", 8);
+undergroundSystem.checkIn(27, "Leyton", 10);
+undergroundSystem.checkOut(45, "Waterloo", 15);  // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
+undergroundSystem.checkOut(27, "Waterloo", 20);  // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
+undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
+undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
+undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
+undergroundSystem.checkIn(10, "Leyton", 24);
+undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000
+undergroundSystem.checkOut(10, "Waterloo", 38);  // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
+undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12
+
+ +

Example 2:

+ +
Input
+["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
+[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]
+
+Output
+[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]
+
+Explanation
+UndergroundSystem undergroundSystem = new UndergroundSystem();
+undergroundSystem.checkIn(10, "Leyton", 3);
+undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
+undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
+undergroundSystem.checkIn(5, "Leyton", 10);
+undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
+undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
+undergroundSystem.checkIn(2, "Leyton", 21);
+undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
+undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= id, t <= 106
  • +
  • 1 <= stationName.length, startStation.length, endStation.length <= 10
  • +
  • All strings consist of uppercase and lowercase English letters and digits.
  • +
  • There will be at most 2 * 104 calls in total to checkIn, checkOut, and getAverageTime.
  • +
  • Answers within 10-5 of the actual value will be accepted.
  • +
+
\ No newline at end of file diff --git a/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp b/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp new file mode 100644 index 00000000..3f9ac903 --- /dev/null +++ b/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int numSteps(string s) { + int step = 0; + + while (s != "1") { + + if (s.back() == '0') s.pop_back(); + else { + + while (!s.empty() && s.back() == '1') { + s.pop_back(); + ++step; + } + + if (s.empty()) return step + 1; + else s.back() = '1'; + + } + ++step; + } + + return step; + } +}; \ No newline at end of file diff --git a/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/README.md b/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/README.md new file mode 100644 index 00000000..d5797331 --- /dev/null +++ b/1404-number-of-steps-to-reduce-a-number-in-binary-representation-to-one/README.md @@ -0,0 +1,50 @@ +

1404. Number of Steps to Reduce a Number in Binary Representation to One

Medium


Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:

+ +
    +
  • +

    If the current number is even, you have to divide it by 2.

    +
  • +
  • +

    If the current number is odd, you have to add 1 to it.

    +
  • +
+ +

It is guaranteed that you can always reach one for all test cases.

+ +

 

+

Example 1:

+ +
Input: s = "1101"
+Output: 6
+Explanation: "1101" corressponds to number 13 in their decimal representation.
+Step 1) 13 is odd, add 1 and obtain 14. 
+Step 2) 14 is even, divide by 2 and obtain 7.
+Step 3) 7 is odd, add 1 and obtain 8.
+Step 4) 8 is even, divide by 2 and obtain 4.  
+Step 5) 4 is even, divide by 2 and obtain 2. 
+Step 6) 2 is even, divide by 2 and obtain 1.  
+
+ +

Example 2:

+ +
Input: s = "10"
+Output: 1
+Explanation: "10" corressponds to number 2 in their decimal representation.
+Step 1) 2 is even, divide by 2 and obtain 1.  
+
+ +

Example 3:

+ +
Input: s = "1"
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 500
  • +
  • s consists of characters '0' or '1'
  • +
  • s[0] == '1'
  • +
+
\ No newline at end of file diff --git a/1406-stone-game-iii/1406-stone-game-iii.cpp b/1406-stone-game-iii/1406-stone-game-iii.cpp new file mode 100644 index 00000000..23c3de22 --- /dev/null +++ b/1406-stone-game-iii/1406-stone-game-iii.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + string stoneGameIII(vector& stoneValue) { + int n = stoneValue.size(); + vector dp(3, 0); + + for (int i = n - 1; i >= 0; i--) { + int takeOne = stoneValue[i] - dp[(i + 1) % 3]; + + int takeTwo = INT_MIN; + if (i + 1 < n) takeTwo = stoneValue[i] + stoneValue[i + 1] - dp[(i + 2) % 3]; + + int takeThree = INT_MIN; + if (i + 2 < n) takeThree = stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[(i + 3) % 3]; + + dp[i % 3] = max({takeOne, takeTwo, takeThree}); + } + + int value = dp[0]; + if(value > 0) + return "Alice"; + else if(value < 0) + return "Bob"; + else + return "Tie"; + } +}; \ No newline at end of file diff --git a/1406-stone-game-iii/NOTES.md b/1406-stone-game-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1406-stone-game-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1416-restore-the-array/1416-restore-the-array.cpp b/1416-restore-the-array/1416-restore-the-array.cpp new file mode 100644 index 00000000..17041e34 --- /dev/null +++ b/1416-restore-the-array/1416-restore-the-array.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + + int MOD = 1000000007; + + int solve(string& s, int& k, vector&dp, int startIdx) + { + if (startIdx == s.size()) return 1; + + if (dp[startIdx] != -1) return dp[startIdx]; + long long currNum = 0, ways = 0; + + for (int i = startIdx; i < s.size(); i++) + { + int currDig = s[i] - '0'; + currNum = (currNum * 10) + currDig; + + if (currNum < 1 || currNum > k) break; + int nextWays = solve(s, k, dp, i + 1); + ways = (ways + nextWays) % MOD; + } + + return dp[startIdx] = ways; + } + + int numberOfArrays(string s, int k) + { + vectordp(s.size(), -1); + int ans = solve(s, k, dp, 0); + return ans; + } +}; \ No newline at end of file diff --git a/1416-restore-the-array/NOTES.md b/1416-restore-the-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1416-restore-the-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1422-maximum-score-after-splitting-a-string/1422-maximum-score-after-splitting-a-string.cpp b/1422-maximum-score-after-splitting-a-string/1422-maximum-score-after-splitting-a-string.cpp new file mode 100644 index 00000000..4aa0af90 --- /dev/null +++ b/1422-maximum-score-after-splitting-a-string/1422-maximum-score-after-splitting-a-string.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxScore(string s) { + + int n = s.size(); + + int ones = count(s.begin(), s.end(), '1'); + + int zero = 0, ans = 0; + + for(int i = 0; i < n-1; ++i) + { + if(s[i] == '0') ++zero; + else --ones; + + ans = max(ans, zero + ones); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1422-maximum-score-after-splitting-a-string/NOTES.md b/1422-maximum-score-after-splitting-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1422-maximum-score-after-splitting-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1422-maximum-score-after-splitting-a-string/README.md b/1422-maximum-score-after-splitting-a-string/README.md new file mode 100644 index 00000000..a8524c03 --- /dev/null +++ b/1422-maximum-score-after-splitting-a-string/README.md @@ -0,0 +1,39 @@ +

1422. Maximum Score After Splitting a String

Easy


Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

+ +

The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

+ +

 

+

Example 1:

+ +
Input: s = "011101"
+Output: 5 
+Explanation: 
+All possible ways of splitting s into two non-empty substrings are:
+left = "0" and right = "11101", score = 1 + 4 = 5 
+left = "01" and right = "1101", score = 1 + 3 = 4 
+left = "011" and right = "101", score = 1 + 2 = 3 
+left = "0111" and right = "01", score = 1 + 1 = 2 
+left = "01110" and right = "1", score = 2 + 1 = 3
+
+ +

Example 2:

+ +
Input: s = "00111"
+Output: 5
+Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
+
+ +

Example 3:

+ +
Input: s = "1111"
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 500
  • +
  • The string s consists of characters '0' and '1' only.
  • +
+
\ No newline at end of file diff --git a/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp b/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp new file mode 100644 index 00000000..ef988336 --- /dev/null +++ b/1423-maximum-points-you-can-obtain-from-cards/1423-maximum-points-you-can-obtain-from-cards.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + + void solve(int k, int& ans, vector& pref, vector& suff) + { + int n = pref.size(); + for(int i = 0; i < k; ++i) + { + int end = n-(k-(i+1)); + int endSum = end < n ? suff[end] : 0; + ans = max(ans, pref[i] + endSum); + } + } + + int maxScore(vector& cardPoints, int k) { + + int n = cardPoints.size(); + vector pref(n, 0), suff(n, 0); + + pref[0] = cardPoints[0]; + suff[n-1] = cardPoints[n-1]; + + for(int i = 1; i < n; ++i) + pref[i] = (pref[i-1] + cardPoints[i]); + + for(int i = n-2; i >= 0; --i) + suff[i] = (suff[i+1] + cardPoints[i]); + + int ans = 0; + + solve(k, ans, pref, suff); + swap(pref, suff); + reverse(pref.begin(), pref.end()); + reverse(suff.begin(), suff.end()); + solve(k, ans, pref, suff); + + return ans; + } +}; \ No newline at end of file diff --git a/1423-maximum-points-you-can-obtain-from-cards/NOTES.md b/1423-maximum-points-you-can-obtain-from-cards/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1423-maximum-points-you-can-obtain-from-cards/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1423-maximum-points-you-can-obtain-from-cards/README.md b/1423-maximum-points-you-can-obtain-from-cards/README.md new file mode 100644 index 00000000..89a65089 --- /dev/null +++ b/1423-maximum-points-you-can-obtain-from-cards/README.md @@ -0,0 +1,39 @@ +

1423. Maximum Points You Can Obtain from Cards

Medium


There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.

+ +

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

+ +

Your score is the sum of the points of the cards you have taken.

+ +

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

+ +

 

+

Example 1:

+ +
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
+Output: 12
+Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
+
+ +

Example 2:

+ +
Input: cardPoints = [2,2,2], k = 2
+Output: 4
+Explanation: Regardless of which two cards you take, your score will always be 4.
+
+ +

Example 3:

+ +
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
+Output: 55
+Explanation: You have to take all the cards. Your score is the sum of points of all cards.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= cardPoints.length <= 105
  • +
  • 1 <= cardPoints[i] <= 104
  • +
  • 1 <= k <= cardPoints.length
  • +
+
\ No newline at end of file diff --git a/1425-constrained-subsequence-sum/1425-constrained-subsequence-sum.cpp b/1425-constrained-subsequence-sum/1425-constrained-subsequence-sum.cpp new file mode 100644 index 00000000..0120df06 --- /dev/null +++ b/1425-constrained-subsequence-sum/1425-constrained-subsequence-sum.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int constrainedSubsetSum(vector& nums, int k) { + + int n = nums.size(); + + vector dp(n+1); + + for(int i = 0; i < n; ++i) + dp[i] = nums[i]; + + priority_queue> pq; + + int ans = *max_element(begin(nums), end(nums)); + + pq.push({nums[0], 0}); + + for(int i = 1; i < n; ++i) + { + while(!pq.empty() and i - pq.top().second > k) + pq.pop(); + + dp[i] = max(dp[i], nums[i] + pq.top().first); + + ans = max(ans, dp[i]); + + pq.push({dp[i], i}); + } + + return ans; + } +}; + + \ No newline at end of file diff --git a/1425-constrained-subsequence-sum/NOTES.md b/1425-constrained-subsequence-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1425-constrained-subsequence-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1425-constrained-subsequence-sum/README.md b/1425-constrained-subsequence-sum/README.md new file mode 100644 index 00000000..6afbb1b6 --- /dev/null +++ b/1425-constrained-subsequence-sum/README.md @@ -0,0 +1,34 @@ +

1425. Constrained Subsequence Sum

Hard


Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

+ +

A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

+ +

 

+

Example 1:

+ +
Input: nums = [10,2,-10,5,20], k = 2
+Output: 37
+Explanation: The subsequence is [10, 2, 5, 20].
+
+ +

Example 2:

+ +
Input: nums = [-1,-2,-3], k = 1
+Output: -1
+Explanation: The subsequence must be non-empty, so we choose the largest number.
+
+ +

Example 3:

+ +
Input: nums = [10,-2,-10,-5,20], k = 2
+Output: 23
+Explanation: The subsequence is [10, -2, -5, 20].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+
\ No newline at end of file diff --git a/1431-kids-with-the-greatest-number-of-candies/1431-kids-with-the-greatest-number-of-candies.cpp b/1431-kids-with-the-greatest-number-of-candies/1431-kids-with-the-greatest-number-of-candies.cpp new file mode 100644 index 00000000..4567cd88 --- /dev/null +++ b/1431-kids-with-the-greatest-number-of-candies/1431-kids-with-the-greatest-number-of-candies.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector kidsWithCandies(vector& candies, int extraCandies) { + + int n = candies.size(); + + vector res(n,0); + + int maxi = *max_element(candies.begin(),candies.end()); + + for(int i = 0; i < n; ++i) + { + if(candies[i] + extraCandies >= maxi) + res[i] = 1; + } + + return res; + + } +}; \ No newline at end of file diff --git a/1431-kids-with-the-greatest-number-of-candies/NOTES.md b/1431-kids-with-the-greatest-number-of-candies/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1431-kids-with-the-greatest-number-of-candies/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp new file mode 100644 index 00000000..e129d313 --- /dev/null +++ b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int longestSubarray(vector& nums, int limit) { + + list maxi, mini; + + int i = 0, j = 0, n = nums.size(); + + int ans = 0; + + while(j < n) + { + while(!maxi.empty() and nums[maxi.back()] < nums[j]) + maxi.pop_back(); + + while(!mini.empty() and nums[mini.back()] > nums[j]) + mini.pop_back(); + + maxi.push_back(j); + mini.push_back(j); + + while(!maxi.empty() and !mini.empty() and nums[maxi.front()] - nums[mini.front()] > limit) + { + if(maxi.front() == i) maxi.pop_front(); + if(mini.front() == i) mini.pop_front(); + ++i; + } + + ans = max(ans, j - i + 1); + + ++j; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/NOTES.md b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/README.md b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/README.md new file mode 100644 index 00000000..8081e912 --- /dev/null +++ b/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/README.md @@ -0,0 +1,43 @@ +

1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

Medium


Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.

+ +

 

+

Example 1:

+ +
Input: nums = [8,2,4,7], limit = 4
+Output: 2 
+Explanation: All subarrays are: 
+[8] with maximum absolute diff |8-8| = 0 <= 4.
+[8,2] with maximum absolute diff |8-2| = 6 > 4. 
+[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
+[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
+[2] with maximum absolute diff |2-2| = 0 <= 4.
+[2,4] with maximum absolute diff |2-4| = 2 <= 4.
+[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
+[4] with maximum absolute diff |4-4| = 0 <= 4.
+[4,7] with maximum absolute diff |4-7| = 3 <= 4.
+[7] with maximum absolute diff |7-7| = 0 <= 4. 
+Therefore, the size of the longest subarray is 2.
+
+ +

Example 2:

+ +
Input: nums = [10,1,2,4,7,2], limit = 5
+Output: 4 
+Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
+
+ +

Example 3:

+ +
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 0 <= limit <= 109
  • +
+
\ No newline at end of file diff --git a/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.cpp b/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.cpp new file mode 100644 index 00000000..5136fb83 --- /dev/null +++ b/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/1442-count-triplets-that-can-form-two-arrays-of-equal-xor.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int countTriplets(vector& arr) { + + int n = arr.size(); + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = i+1; j < n; ++j) + { + int curXorF = 0, curXorS = 0; + + for(int k = i; k < j; ++k) + curXorF ^= arr[k]; + + for(int k = j; k < n; ++k) + { + curXorS ^= arr[k]; + if(curXorF == curXorS) + ++cnt; + } + } + } + + return cnt; + } +}; diff --git a/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/README.md b/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/README.md new file mode 100644 index 00000000..5a85fce7 --- /dev/null +++ b/1442-count-triplets-that-can-form-two-arrays-of-equal-xor/README.md @@ -0,0 +1,37 @@ +

1442. Count Triplets That Can Form Two Arrays of Equal XOR

Medium


Given an array of integers arr.

+ +

We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).

+ +

Let's define a and b as follows:

+ +
    +
  • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
  • +
  • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
  • +
+ +

Note that ^ denotes the bitwise-xor operation.

+ +

Return the number of triplets (i, j and k) Where a == b.

+ +

 

+

Example 1:

+ +
Input: arr = [2,3,1,6,7]
+Output: 4
+Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
+
+ +

Example 2:

+ +
Input: arr = [1,1,1,1,1]
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 300
  • +
  • 1 <= arr[i] <= 108
  • +
+
\ No newline at end of file diff --git a/1443-minimum-time-to-collect-all-apples-in-a-tree/1443-minimum-time-to-collect-all-apples-in-a-tree.cpp b/1443-minimum-time-to-collect-all-apples-in-a-tree/1443-minimum-time-to-collect-all-apples-in-a-tree.cpp new file mode 100644 index 00000000..8e6550bd --- /dev/null +++ b/1443-minimum-time-to-collect-all-apples-in-a-tree/1443-minimum-time-to-collect-all-apples-in-a-tree.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector> adjList; + int dfs(vector& hasApple,int node,int d,int prev) + { + int result=0,temp; + for(int &i:adjList[node]) + if(i!=prev) + { + temp=dfs(hasApple,i,d+1,node); + if(temp) //If child has apples it'll return a non zero result which is the distance traveled upto that node. + result+=temp-d; + } + return result||hasApple[node]?result+d:0; //If nothing is added to result and current node doesnt have apple return 0 else return distances of children + current distance from root. + + } + int minTime(int n, vector>& edges, vector& hasApple) + { + adjList.resize(n); + for(vector &e:edges) + adjList[e[0]].push_back(e[1]),adjList[e[1]].push_back(e[0]); + return dfs(hasApple,0,0,-1)*2; //Result is doubled the distance travelled as per our observation. + } +}; \ No newline at end of file diff --git a/1443-minimum-time-to-collect-all-apples-in-a-tree/README.md b/1443-minimum-time-to-collect-all-apples-in-a-tree/README.md new file mode 100644 index 00000000..a9756d97 --- /dev/null +++ b/1443-minimum-time-to-collect-all-apples-in-a-tree/README.md @@ -0,0 +1,37 @@ +

1443. Minimum Time to Collect All Apples in a Tree

Medium


Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.

+ +

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.

+ +

 

+

Example 1:

+ +
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
+Output: 8 
+Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  
+
+ +

Example 2:

+ +
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
+Output: 6
+Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  
+
+ +

Example 3:

+ +
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai < bi <= n - 1
  • +
  • fromi < toi
  • +
  • hasApple.length == n
  • +
+
\ No newline at end of file diff --git a/1444-number-of-ways-of-cutting-a-pizza/1444-number-of-ways-of-cutting-a-pizza.cpp b/1444-number-of-ways-of-cutting-a-pizza/1444-number-of-ways-of-cutting-a-pizza.cpp new file mode 100644 index 00000000..19ac1a2e --- /dev/null +++ b/1444-number-of-ways-of-cutting-a-pizza/1444-number-of-ways-of-cutting-a-pizza.cpp @@ -0,0 +1,69 @@ +class Solution { + + int check(int row, int col, vector& p) + { + for(int i = row ; i < p.size() ; i++){ + for(int j = col ; j < p[0].length() ; j++){ + if( p[i][j] == 'A' ) return true ; + } + } + + return false ; + } + + bool hIsApple(int st, int cur, int c, vector& p) + { + for(int row = st; row < cur ; row++){ + for(int col = c ; col < p[0].length() ; col++){ + if( p[row][col] == 'A' ) return true ; + } + } + return false ; + } + + bool vIsApple(int r, int st, int cur, vector& p) + { + for(int row = r ; row < p.size() ; row++){ + for(int col = st ; col < cur ; col++){ + if( p[row][col] == 'A' ) return true ; + } + } + return false ; + } + + int helper(int &i, int &j, int k, vector& p,vector>> &dp) + { + if( k == 0 ) + { + return check(i,j,p) ; + } + + if( dp[i][j][k] != -1 ) return dp[i][j][k] ; + + int ans = 0 ; + for(int row = i+1 ; row < p.size() ; row++) + { + if( hIsApple( i,row,j,p ) ) + ans = (ans + helper(row,j,k-1,p,dp))%mod ; + } + + for(int col = j+1 ; col < p[0].length() ; col++) + { + if( vIsApple(i,j,col,p) ) + ans = (ans + helper(i,col,k-1,p,dp))%mod ; + } + + return dp[i][j][k] = (ans)%mod ; + } + +public: + int mod = 1e9+7 ; + int ways(vector& pizza, int k) { + + int n = pizza.size(); + int m = pizza[0].length() ; + int i =0,j = 0; + vector>> dp(n+1,vector> (m+1, vector (k+1,-1))) ; + return helper(i,j,k-1,pizza,dp) ; + } +}; \ No newline at end of file diff --git a/1444-number-of-ways-of-cutting-a-pizza/README.md b/1444-number-of-ways-of-cutting-a-pizza/README.md new file mode 100644 index 00000000..e1714ba4 --- /dev/null +++ b/1444-number-of-ways-of-cutting-a-pizza/README.md @@ -0,0 +1,38 @@ +

1444. Number of Ways of Cutting a Pizza

Hard


Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. 

+ +

For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.

+ +

Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.

+ +

 

+

Example 1:

+ +

+ +
Input: pizza = ["A..","AAA","..."], k = 3
+Output: 3 
+Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
+
+ +

Example 2:

+ +
Input: pizza = ["A..","AA.","..."], k = 3
+Output: 1
+
+ +

Example 3:

+ +
Input: pizza = ["A..","A..","..."], k = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= rows, cols <= 50
  • +
  • rows == pizza.length
  • +
  • cols == pizza[i].length
  • +
  • 1 <= k <= 10
  • +
  • pizza consists of characters 'A' and '.' only.
  • +
\ No newline at end of file diff --git a/1456-maximum-number-of-vowels-in-a-substring-of-given-length/1456-maximum-number-of-vowels-in-a-substring-of-given-length.cpp b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/1456-maximum-number-of-vowels-in-a-substring-of-given-length.cpp new file mode 100644 index 00000000..a70abcd2 --- /dev/null +++ b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/1456-maximum-number-of-vowels-in-a-substring-of-given-length.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + int maxVowels(string s, int k) { + + int i = 0, j = 0, n = s.size(); + + int currCnt = 0, ans = 0; + + unordered_map mp; + + + auto isVowel = [&](char ch){ + return (ch == 'a' or ch == 'A' or ch == 'e' or ch == 'E' or ch == 'i' or ch == 'I' or ch == 'o' or ch == 'O' or ch == 'u' or ch == 'U'); + }; + + + while(j < n) + { + ++mp[s[j]]; + + if(isVowel(s[j])) + ++currCnt; + + if(j - i + 1 == k) + { + ans = max(ans, currCnt); + + if(isVowel(s[i])) + --currCnt; + + --mp[s[i]]; + + if(mp[s[i]] == 0) + mp.erase(s[i]); + + ++i; + + } + ++j; + } + + + return ans; + + } +}; diff --git a/1456-maximum-number-of-vowels-in-a-substring-of-given-length/NOTES.md b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1456-maximum-number-of-vowels-in-a-substring-of-given-length/README.md b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/README.md new file mode 100644 index 00000000..ab9e2fee --- /dev/null +++ b/1456-maximum-number-of-vowels-in-a-substring-of-given-length/README.md @@ -0,0 +1,35 @@ +

1456. Maximum Number of Vowels in a Substring of Given Length

Medium


Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.

+ +

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

+ +

 

+

Example 1:

+ +
Input: s = "abciiidef", k = 3
+Output: 3
+Explanation: The substring "iii" contains 3 vowel letters.
+
+ +

Example 2:

+ +
Input: s = "aeiou", k = 2
+Output: 2
+Explanation: Any substring of length 2 contains 2 vowels.
+
+ +

Example 3:

+ +
Input: s = "leetcode", k = 3
+Output: 2
+Explanation: "lee", "eet" and "ode" contain 2 vowels.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase English letters.
  • +
  • 1 <= k <= s.length
  • +
+
\ No newline at end of file diff --git a/1457-pseudo-palindromic-paths-in-a-binary-tree/1457-pseudo-palindromic-paths-in-a-binary-tree.cpp b/1457-pseudo-palindromic-paths-in-a-binary-tree/1457-pseudo-palindromic-paths-in-a-binary-tree.cpp new file mode 100644 index 00000000..1370abd3 --- /dev/null +++ b/1457-pseudo-palindromic-paths-in-a-binary-tree/1457-pseudo-palindromic-paths-in-a-binary-tree.cpp @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + void helper(TreeNode* root, vector freq, int& cnt) + { + if(root) + { + ++freq[root->val]; + + helper(root->left, freq, cnt); + helper(root->right, freq, cnt); + + int odd = 0; + + if(!root->left and !root->right) + { + for(int i = 0; i < 10; ++i) + { + odd += (freq[i] & 1); + } + + cnt += (odd == 1 or odd == 0); + } + + --freq[root->val]; + } + } + + int pseudoPalindromicPaths (TreeNode* root) { + + int cnt = 0; + + vector freq(10, 0); + + helper(root, freq, cnt); + + return cnt; + + } +}; \ No newline at end of file diff --git a/1457-pseudo-palindromic-paths-in-a-binary-tree/README.md b/1457-pseudo-palindromic-paths-in-a-binary-tree/README.md new file mode 100644 index 00000000..746fb259 --- /dev/null +++ b/1457-pseudo-palindromic-paths-in-a-binary-tree/README.md @@ -0,0 +1,37 @@ +

1457. Pseudo-Palindromic Paths in a Binary Tree

Medium


Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.

+ +

Return the number of pseudo-palindromic paths going from the root node to leaf nodes.

+ +

 

+

Example 1:

+ +

+ +
Input: root = [2,3,1,3,1,null,1]
+Output: 2 
+Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
+
+ +

Example 2:

+ +

+ +
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
+Output: 1 
+Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
+
+ +

Example 3:

+ +
Input: root = [9]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 105].
  • +
  • 1 <= Node.val <= 9
  • +
+
\ No newline at end of file diff --git a/1458-max-dot-product-of-two-subsequences/1458-max-dot-product-of-two-subsequences.cpp b/1458-max-dot-product-of-two-subsequences/1458-max-dot-product-of-two-subsequences.cpp new file mode 100644 index 00000000..4413d5c2 --- /dev/null +++ b/1458-max-dot-product-of-two-subsequences/1458-max-dot-product-of-two-subsequences.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + + int helper(int i, int j, int n, int m, vector& nums1, vector& nums2, vector>& dp) + { + if(i == n or j == m) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + int res = INT_MIN; + + int take = nums1[i] * nums2[j] + helper(i+1, j+1, n, m, nums1, nums2, dp); + + int moveI = helper(i+1, j, n, m, nums1, nums2, dp); + + int moveJ = helper(i, j+1, n, m, nums1, nums2, dp); + + return dp[i][j] = max({take, moveI, moveJ}); + + } + + int getMaxPair(vector& nums1, vector& nums2) + { + int ans = INT_MIN; + + for(auto& fir : nums1) + { + for(auto& sec : nums2) + { + ans = max(ans, fir*sec); + } + } + + return ans; + } + + int maxDotProduct(vector& nums1, vector& nums2) { + + int n = nums1.size(); + int m = nums2.size(); + + vector> dp(n+1, vector(m+1, -1)); + + int ans = helper(0, 0, n, m, nums1, nums2, dp); + + int maxPairValue = getMaxPair(nums1, nums2); + + if(ans == 0) + return maxPairValue; + + return ans; + + } +}; \ No newline at end of file diff --git a/1458-max-dot-product-of-two-subsequences/NOTES.md b/1458-max-dot-product-of-two-subsequences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1458-max-dot-product-of-two-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1458-max-dot-product-of-two-subsequences/README.md b/1458-max-dot-product-of-two-subsequences/README.md new file mode 100644 index 00000000..d2dce7b9 --- /dev/null +++ b/1458-max-dot-product-of-two-subsequences/README.md @@ -0,0 +1,36 @@ +

1458. Max Dot Product of Two Subsequences

Hard


Given two arrays nums1 and nums2.

+ +

Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.

+ +

A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).

+ +

 

+

Example 1:

+ +
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
+Output: 18
+Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
+Their dot product is (2*3 + (-2)*(-6)) = 18.
+ +

Example 2:

+ +
Input: nums1 = [3,-2], nums2 = [2,-6,7]
+Output: 21
+Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
+Their dot product is (3*7) = 21.
+ +

Example 3:

+ +
Input: nums1 = [-1,-1], nums2 = [1,1]
+Output: -1
+Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
+Their dot product is -1.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 500
  • +
  • -1000 <= nums1[i], nums2[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1460-make-two-arrays-equal-by-reversing-subarrays/1460-make-two-arrays-equal-by-reversing-subarrays.cpp b/1460-make-two-arrays-equal-by-reversing-subarrays/1460-make-two-arrays-equal-by-reversing-subarrays.cpp new file mode 100644 index 00000000..7b717361 --- /dev/null +++ b/1460-make-two-arrays-equal-by-reversing-subarrays/1460-make-two-arrays-equal-by-reversing-subarrays.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + + sort(arr.begin(), arr.end()); + sort(target.begin(), target.end()); + + return arr == target; + + } +}; \ No newline at end of file diff --git a/1460-make-two-arrays-equal-by-reversing-subarrays/NOTES.md b/1460-make-two-arrays-equal-by-reversing-subarrays/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1460-make-two-arrays-equal-by-reversing-subarrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1463-cherry-pickup-ii/1463-cherry-pickup-ii.cpp b/1463-cherry-pickup-ii/1463-cherry-pickup-ii.cpp new file mode 100644 index 00000000..cfdaff76 --- /dev/null +++ b/1463-cherry-pickup-ii/1463-cherry-pickup-ii.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + + int helper(int i,int j1, int j2, int n, int m, vector>& grid, vector>>& dp) + { + if(j1 < 0 or j1 >= m or j2 < 0 or j2 >= m) + return -1e8; + + if(i == n - 1) + { + if(j1 == j2) + return dp[i][j1][j2] = grid[i][j1]; + else return dp[i][j1][j2] = grid[i][j1] + grid[i][j2]; + } + + if(dp[i][j1][j2] != -1) + return dp[i][j1][j2]; + + int ans = -1e8; + for(int d1 = -1 ; d1 <= +1; ++d1) + { + for(int d2 = -1; d2 <= +1; ++d2) + { + int value = 0; + if(j1 == j2) + value = grid[i][j1]; + else + value = grid[i][j1] + grid[i][j2]; + + value += helper(i+1,j1 + d1 , j2 + d2, n, m, grid, dp); + ans = max(ans, value); + + } + } + return dp[i][j1][j2] = ans; + } + + int cherryPickup(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + vector>> dp(n,vector>(m,vector(m,-1))); + + return helper(0,0,m-1,n,m, grid, dp); + } +}; \ No newline at end of file diff --git a/1463-cherry-pickup-ii/NOTES.md b/1463-cherry-pickup-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1463-cherry-pickup-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1463-cherry-pickup-ii/README.md b/1463-cherry-pickup-ii/README.md new file mode 100644 index 00000000..577af6c0 --- /dev/null +++ b/1463-cherry-pickup-ii/README.md @@ -0,0 +1,50 @@ +

1463. Cherry Pickup II

Hard


You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.

+ +

You have two robots that can collect cherries for you:

+ +
    +
  • Robot #1 is located at the top-left corner (0, 0), and
  • +
  • Robot #2 is located at the top-right corner (0, cols - 1).
  • +
+ +

Return the maximum number of cherries collection using both robots by following the rules below:

+ +
    +
  • From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
  • +
  • When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
  • +
  • When both robots stay in the same cell, only one takes the cherries.
  • +
  • Both robots cannot move outside of the grid at any moment.
  • +
  • Both robots should reach the bottom row in grid.
  • +
+ +

 

+

Example 1:

+ +
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
+Output: 24
+Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
+Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
+Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
+Total of cherries: 12 + 12 = 24.
+
+ +

Example 2:

+ +
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
+Output: 28
+Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
+Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
+Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
+Total of cherries: 17 + 11 = 28.
+
+ +

 

+

Constraints:

+ +
    +
  • rows == grid.length
  • +
  • cols == grid[i].length
  • +
  • 2 <= rows, cols <= 70
  • +
  • 0 <= grid[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp b/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp new file mode 100644 index 00000000..c3d7c4e1 --- /dev/null +++ b/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int maxProduct(vector& nums) { + + sort(nums.begin(), nums.end()); + + return (--nums[nums.size()-1] * --nums[nums.size()-2]); + + } +}; \ No newline at end of file diff --git a/1464-maximum-product-of-two-elements-in-an-array/NOTES.md b/1464-maximum-product-of-two-elements-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1464-maximum-product-of-two-elements-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1464-maximum-product-of-two-elements-in-an-array/README.md b/1464-maximum-product-of-two-elements-in-an-array/README.md new file mode 100644 index 00000000..c3561d41 --- /dev/null +++ b/1464-maximum-product-of-two-elements-in-an-array/README.md @@ -0,0 +1,30 @@ +

1464. Maximum Product of Two Elements in an Array

Easy


Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). +

 

+

Example 1:

+ +
Input: nums = [3,4,5,2]
+Output: 12 
+Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 
+
+ +

Example 2:

+ +
Input: nums = [1,5,4,5]
+Output: 16
+Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
+
+ +

Example 3:

+ +
Input: nums = [3,7]
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 500
  • +
  • 1 <= nums[i] <= 10^3
  • +
+
\ No newline at end of file diff --git a/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp new file mode 100644 index 00000000..f2ec64da --- /dev/null +++ b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + + void dfs(int sv, vector> adj[], vector& visited, int& cnt) + { + visited[sv] = true; + + for(auto itr : adj[sv]) + { + if(!visited[itr.first]) + { + if(itr.second == 1) + ++cnt; + dfs(itr.first,adj,visited,cnt); + } + } + } + + int minReorder(int n, vector>& connections) { + + vector> adj[n+1]; + + for(auto itr : connections) + { + adj[itr[0]].push_back({itr[1],1}); + adj[itr[1]].push_back({itr[0],0}); + } + + vector visited(n+1,false); + int cnt = 0 ; + dfs(0,adj,visited,cnt); + + return cnt; + } +}; \ No newline at end of file diff --git a/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/NOTES.md b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md new file mode 100644 index 00000000..f62d845c --- /dev/null +++ b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md @@ -0,0 +1,42 @@ +

1466. Reorder Routes to Make All Paths Lead to the City Zero

Medium


There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

+ +

Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.

+ +

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

+ +

Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.

+ +

It's guaranteed that each city can reach city 0 after reorder.

+ +

 

+

Example 1:

+ +
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
+Output: 3
+Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
+
+ +

Example 2:

+ +
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
+Output: 2
+Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
+
+ +

Example 3:

+ +
Input: n = 3, connections = [[1,0],[2,0]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 5 * 104
  • +
  • connections.length == n - 1
  • +
  • connections[i].length == 2
  • +
  • 0 <= ai, bi <= n - 1
  • +
  • ai != bi
  • +
+
\ No newline at end of file diff --git a/1470-shuffle-the-array/1470-shuffle-the-array.cpp b/1470-shuffle-the-array/1470-shuffle-the-array.cpp new file mode 100644 index 00000000..db044029 --- /dev/null +++ b/1470-shuffle-the-array/1470-shuffle-the-array.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector shuffle(vector& nums, int n) { + + // storing secNum in next 10 bits and or with first to combine second and first + for(int i = n; i < 2*n; ++i) + { + int secNum = nums[i] << 10; + nums[i-n] |= secNum; + } + + for(int i = n-1; i>= 0; --i) + { + int secNum = nums[i] >> 10; + int firstNum = nums[i] & 1023; + + nums[2*i+1] = secNum; + nums[2*i] = firstNum; + } + return nums; + } +}; \ No newline at end of file diff --git a/1470-shuffle-the-array/NOTES.md b/1470-shuffle-the-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1470-shuffle-the-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1470-shuffle-the-array/README.md b/1470-shuffle-the-array/README.md new file mode 100644 index 00000000..49c3eae9 --- /dev/null +++ b/1470-shuffle-the-array/README.md @@ -0,0 +1,32 @@ +

1470. Shuffle the Array

Easy


Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].

+ +

Return the array in the form [x1,y1,x2,y2,...,xn,yn].

+ +

 

+

Example 1:

+ +
Input: nums = [2,5,1,3,4,7], n = 3
+Output: [2,3,5,4,1,7] 
+Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,4,3,2,1], n = 4
+Output: [1,4,2,3,3,2,4,1]
+
+ +

Example 3:

+ +
Input: nums = [1,1,2,2], n = 2
+Output: [1,2,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 500
  • +
  • nums.length == 2n
  • +
  • 1 <= nums[i] <= 10^3
  • +
\ No newline at end of file diff --git a/1472-design-browser-history/1472-design-browser-history.cpp b/1472-design-browser-history/1472-design-browser-history.cpp new file mode 100644 index 00000000..a657c004 --- /dev/null +++ b/1472-design-browser-history/1472-design-browser-history.cpp @@ -0,0 +1,41 @@ +class BrowserHistory { +public: + stack history; + stack future; + + BrowserHistory(string homepage) { + history.push(homepage); + future = stack(); + } + + void visit(string url) { + history.push(url); + future = stack(); + } + + string back(int steps) { + while(steps > 0 && history.size() > 1) { + future.push(history.top()); + history.pop(); + steps--; + } + return history.top(); + } + + string forward(int steps) { + while(steps > 0 && future.size() > 0) { + history.push(future.top()); + future.pop(); + steps--; + } + return history.top(); + } +}; + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory* obj = new BrowserHistory(homepage); + * obj->visit(url); + * string param_2 = obj->back(steps); + * string param_3 = obj->forward(steps); + */ \ No newline at end of file diff --git a/1472-design-browser-history/README.md b/1472-design-browser-history/README.md new file mode 100644 index 00000000..8a2a83bd --- /dev/null +++ b/1472-design-browser-history/README.md @@ -0,0 +1,45 @@ +

1472. Design Browser History

Medium


You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.

+ +

Implement the BrowserHistory class:

+ +
    +
  • BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
  • +
  • void visit(string url) Visits url from the current page. It clears up all the forward history.
  • +
  • string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
  • +
  • string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.
  • +
+ +

 

+

Example:

+ +
Input:
+["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
+[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
+Output:
+[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
+
+Explanation:
+BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
+browserHistory.visit("google.com");       // You are in "leetcode.com". Visit "google.com"
+browserHistory.visit("facebook.com");     // You are in "google.com". Visit "facebook.com"
+browserHistory.visit("youtube.com");      // You are in "facebook.com". Visit "youtube.com"
+browserHistory.back(1);                   // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
+browserHistory.back(1);                   // You are in "facebook.com", move back to "google.com" return "google.com"
+browserHistory.forward(1);                // You are in "google.com", move forward to "facebook.com" return "facebook.com"
+browserHistory.visit("linkedin.com");     // You are in "facebook.com". Visit "linkedin.com"
+browserHistory.forward(2);                // You are in "linkedin.com", you cannot move forward any steps.
+browserHistory.back(2);                   // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
+browserHistory.back(7);                   // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= homepage.length <= 20
  • +
  • 1 <= url.length <= 20
  • +
  • 1 <= steps <= 100
  • +
  • homepage and url consist of  '.' or lower case English letters.
  • +
  • At most 5000 calls will be made to visit, back, and forward.
  • +
+
\ No newline at end of file diff --git a/1481-least-number-of-unique-integers-after-k-removals/1481-least-number-of-unique-integers-after-k-removals.cpp b/1481-least-number-of-unique-integers-after-k-removals/1481-least-number-of-unique-integers-after-k-removals.cpp new file mode 100644 index 00000000..c378674a --- /dev/null +++ b/1481-least-number-of-unique-integers-after-k-removals/1481-least-number-of-unique-integers-after-k-removals.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int findLeastNumOfUniqueInts(vector& arr, int k) { + + map mp; + + for(auto& ele : arr) + ++mp[ele]; + + priority_queue, vector>, greater>> pq; + + for(auto&[f, e] : mp) + pq.push({e, f}); + + while(!pq.empty()) + { + auto curr = pq.top(); + pq.pop(); + + if(curr.first <= k) + { + k -= curr.first; + } + else + { + pq.push(curr); + break; + } + } + + return (int)pq.size(); + } +}; \ No newline at end of file diff --git a/1481-least-number-of-unique-integers-after-k-removals/README.md b/1481-least-number-of-unique-integers-after-k-removals/README.md new file mode 100644 index 00000000..a8ace42d --- /dev/null +++ b/1481-least-number-of-unique-integers-after-k-removals/README.md @@ -0,0 +1,26 @@ +

1481. Least Number of Unique Integers after K Removals

Medium


Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

+ +
    +
+ +

 

+

Example 1:

+ +
Input: arr = [5,5,4], k = 1
+Output: 1
+Explanation: Remove the single 4, only 5 is left.
+
+Example 2: + +
Input: arr = [4,3,1,1,3,3,2], k = 3
+Output: 2
+Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 10^5
  • +
  • 1 <= arr[i] <= 10^9
  • +
  • 0 <= k <= arr.length
  • +
\ No newline at end of file diff --git a/1482-minimum-number-of-days-to-make-m-bouquets/1482-minimum-number-of-days-to-make-m-bouquets.cpp b/1482-minimum-number-of-days-to-make-m-bouquets/1482-minimum-number-of-days-to-make-m-bouquets.cpp new file mode 100644 index 00000000..df9f3f33 --- /dev/null +++ b/1482-minimum-number-of-days-to-make-m-bouquets/1482-minimum-number-of-days-to-make-m-bouquets.cpp @@ -0,0 +1,45 @@ +using ll = long long; + +class Solution { +public: + + int minimumNumberOfDays(int m, int k, int mid, vector& bloomDay) + { + ll bouquet = 0; + ll currSum = 0; + + for(auto& day : bloomDay) + { + currSum = (day <= mid ? currSum+1 : 0); + bouquet += (currSum / k); + currSum %= k; + } + + return bouquet >= m; + } + + int minDays(vector& bloomDay, int m, int k) { + + int low = *min_element(bloomDay.begin(), bloomDay.end()); + int high = *max_element(bloomDay.begin(), bloomDay.end()); + + int ans = INT_MAX; + + while(low <= high) + { + int mid = (low + high) / 2; + + if(minimumNumberOfDays(m, k, mid, bloomDay)) + { + ans = mid; + high = mid-1; + } + else + { + low = mid+1; + } + } + + return (ans == INT_MAX ? -1 : ans); + } +}; \ No newline at end of file diff --git a/1482-minimum-number-of-days-to-make-m-bouquets/NOTES.md b/1482-minimum-number-of-days-to-make-m-bouquets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1482-minimum-number-of-days-to-make-m-bouquets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1482-minimum-number-of-days-to-make-m-bouquets/README.md b/1482-minimum-number-of-days-to-make-m-bouquets/README.md new file mode 100644 index 00000000..5d2527df --- /dev/null +++ b/1482-minimum-number-of-days-to-make-m-bouquets/README.md @@ -0,0 +1,50 @@ +

1482. Minimum Number of Days to Make m Bouquets

Medium


You are given an integer array bloomDay, an integer m and an integer k.

+ +

You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.

+ +

The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.

+ +

Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.

+ +

 

+

Example 1:

+ +
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
+Output: 3
+Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.
+We need 3 bouquets each should contain 1 flower.
+After day 1: [x, _, _, _, _]   // we can only make one bouquet.
+After day 2: [x, _, _, _, x]   // we can only make two bouquets.
+After day 3: [x, _, x, _, x]   // we can make 3 bouquets. The answer is 3.
+
+ +

Example 2:

+ +
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
+Output: -1
+Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
+
+ +

Example 3:

+ +
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
+Output: 12
+Explanation: We need 2 bouquets each should have 3 flowers.
+Here is the garden after the 7 and 12 days:
+After day 7: [x, x, x, x, _, x, x]
+We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
+After day 12: [x, x, x, x, x, x, x]
+It is obvious that we can make two bouquets in different ways.
+
+ +

 

+

Constraints:

+ +
    +
  • bloomDay.length == n
  • +
  • 1 <= n <= 105
  • +
  • 1 <= bloomDay[i] <= 109
  • +
  • 1 <= m <= 106
  • +
  • 1 <= k <= n
  • +
+
\ No newline at end of file diff --git a/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.cpp b/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.cpp new file mode 100644 index 00000000..4071369d --- /dev/null +++ b/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.cpp @@ -0,0 +1,147 @@ +class Solution { +public: + + int N; + + class DSU{ + + public : + vector parent, size, rank; + + DSU(int n) + { + parent.resize(n+1); + size.resize(n+1, 1); + rank.resize(n+1, 0); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + return u; + + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int nodeX = findParent(u); + int nodeY = findParent(v); + + if(nodeX == nodeY) + return; + + if(rank[nodeX] < rank[nodeY]) + { + parent[nodeX] = nodeY; + } + else if(rank[nodeY] < rank[nodeX]) + { + parent[nodeY] = nodeX; + } + else + { + parent[nodeY] = nodeX; + ++rank[nodeY]; + } + } + + void unionBySize(int u, int v) + { + int nodeX = findParent(u); + int nodeY = findParent(v); + + if(nodeX == nodeY) + return; + + if(size[nodeX] < size[nodeY]) + { + parent[nodeX] = nodeY; + size[nodeY] += size[nodeX]; + } + else + { + parent[nodeY] = nodeX; + size[nodeY] += size[nodeX]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } + }; + + int kruskals(vector>& edges, int skip_edge, int add_edge) + { + DSU dsu(N); + + int edges_cnt = 0; + + int mstWeight = 0; + + if(add_edge != -1) + { + dsu.unionBySize(edges[add_edge][0], edges[add_edge][1]); + mstWeight += edges[add_edge][2]; + ++edges_cnt; + } + + for(int i = 0; i < edges.size(); ++i) + { + if(i == skip_edge) + continue; + + int u = edges[i][0]; + int v = edges[i][1]; + int wt = edges[i][2]; + + if(dsu.isSame(u, v)) + { + continue; + } + else + { + dsu.unionBySize(u, v); + mstWeight += wt; + ++edges_cnt; + } + } + + if(edges_cnt != N-1) + return INT_MAX; + + return mstWeight; + } + + vector> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) { + + // JAI SHREE RAM + + N = n; + + for(int i = 0; i < edges.size(); ++i) + edges[i].push_back(i); + + sort(edges.begin(), edges.end(), [&](const auto &a, const auto &b){ + return a[2] < b[2]; + }); + + int mstWeight = kruskals(edges, -1, -1); + + vector critical, pseudoCritical; + + for(int i = 0; i < edges.size(); ++i) + { + if(kruskals(edges, i, -1) > mstWeight) + critical.push_back(edges[i].back()); + else if(kruskals(edges, -1, i) == mstWeight) + pseudoCritical.push_back(edges[i].back()); + } + + return {critical, pseudoCritical}; + } +}; \ No newline at end of file diff --git a/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/NOTES.md b/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1493-longest-subarray-of-1s-after-deleting-one-element/1493-longest-subarray-of-1s-after-deleting-one-element.cpp b/1493-longest-subarray-of-1s-after-deleting-one-element/1493-longest-subarray-of-1s-after-deleting-one-element.cpp new file mode 100644 index 00000000..ed1b879c --- /dev/null +++ b/1493-longest-subarray-of-1s-after-deleting-one-element/1493-longest-subarray-of-1s-after-deleting-one-element.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int longestSubarray(vector& nums) { + + int i = 0, j = 0, n = nums.size(); + + int ans = 0, zero = 0; + + while(j < n) + { + if(nums[j] == 0) + ++zero; + + while(zero > 1){ + if(nums[i] == 0) + --zero; + ++i; + } + + ans = max(ans, j-i); + + ++j; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1493-longest-subarray-of-1s-after-deleting-one-element/NOTES.md b/1493-longest-subarray-of-1s-after-deleting-one-element/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1493-longest-subarray-of-1s-after-deleting-one-element/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1496-path-crossing/1496-path-crossing.cpp b/1496-path-crossing/1496-path-crossing.cpp new file mode 100644 index 00000000..867b4685 --- /dev/null +++ b/1496-path-crossing/1496-path-crossing.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool isPathCrossing(string path) { + + int n = path.size(); + + set> used; + + int x = 0, y = 0; + + used.insert({x, y}); + + for(int i = 0; i < n; ++i) + { + if(path[i] == 'N') + ++y; + else if(path[i] == 'E') + ++x; + else if(path[i] == 'S') + --y; + else + --x; + if(used.count({x, y})) + return true; + used.insert({x,y}); + } + + return false; + } +}; \ No newline at end of file diff --git a/1496-path-crossing/NOTES.md b/1496-path-crossing/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1496-path-crossing/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1496-path-crossing/README.md b/1496-path-crossing/README.md new file mode 100644 index 00000000..71c6c3b5 --- /dev/null +++ b/1496-path-crossing/README.md @@ -0,0 +1,26 @@ +

1496. Path Crossing

Easy


Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.

+ +

Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.

+ +

 

+

Example 1:

+ +
Input: path = "NES"
+Output: false 
+Explanation: Notice that the path doesn't cross any point more than once.
+
+ +

Example 2:

+ +
Input: path = "NESWW"
+Output: true
+Explanation: Notice that the path visits the origin twice.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= path.length <= 104
  • +
  • path[i] is either 'N', 'S', 'E', or 'W'.
  • +
+
\ No newline at end of file diff --git a/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp new file mode 100644 index 00000000..aaf84d08 --- /dev/null +++ b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp @@ -0,0 +1,49 @@ +class Solution { + +private: + + long long expo(long long x, long long y) + { + long long res = 1; + + while( y > 0) + { + if(y & 1) + res = (res * x) % mod; + + y >>= 1; + + x = (x*x) % mod; + } + + return res % mod; + } + +public: + + int mod = 1e9 + 7; + + int numSubseq(vector& nums, int target) { + + long long cnt = 0, n = nums.size(); + + sort(nums.begin(),nums.end()); + + long long l = 0, r = n - 1; + + while(l <= r) + { + if(nums[l] + nums[r] <= target) + { + cnt += expo(2,(r-l)); + cnt %= mod; + ++l; + } + else + --r; + } + + return cnt; + + } +}; \ No newline at end of file diff --git a/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/NOTES.md b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/README.md b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/README.md new file mode 100644 index 00000000..f6ad7ca1 --- /dev/null +++ b/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/README.md @@ -0,0 +1,41 @@ +

1498. Number of Subsequences That Satisfy the Given Sum Condition

Medium


You are given an array of integers nums and an integer target.

+ +

Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: nums = [3,5,6,7], target = 9
+Output: 4
+Explanation: There are 4 subsequences that satisfy the condition.
+[3] -> Min value + max value <= target (3 + 3 <= 9)
+[3,5] -> (3 + 5 <= 9)
+[3,5,6] -> (3 + 6 <= 9)
+[3,6] -> (3 + 6 <= 9)
+
+ +

Example 2:

+ +
Input: nums = [3,3,6,8], target = 10
+Output: 6
+Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
+[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
+
+ +

Example 3:

+ +
Input: nums = [2,3,3,4,6,7], target = 12
+Output: 61
+Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
+Number of valid subsequences (63 - 2 = 61).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 106
  • +
  • 1 <= target <= 106
  • +
+
\ No newline at end of file diff --git a/1502-can-make-arithmetic-progression-from-sequence/1502-can-make-arithmetic-progression-from-sequence.cpp b/1502-can-make-arithmetic-progression-from-sequence/1502-can-make-arithmetic-progression-from-sequence.cpp new file mode 100644 index 00000000..876efb1a --- /dev/null +++ b/1502-can-make-arithmetic-progression-from-sequence/1502-can-make-arithmetic-progression-from-sequence.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + + int n = arr.size(); + + sort(arr.begin(), arr.end()); + + int diff = arr[1] - arr[0]; + + for(int i = 1; i < n; ++i) + { + if(arr[i] - arr[i-1] != diff) + return false; + } + + return true; + } +}; \ No newline at end of file diff --git a/1502-can-make-arithmetic-progression-from-sequence/NOTES.md b/1502-can-make-arithmetic-progression-from-sequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1502-can-make-arithmetic-progression-from-sequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1502-can-make-arithmetic-progression-from-sequence/README.md b/1502-can-make-arithmetic-progression-from-sequence/README.md new file mode 100644 index 00000000..8f9e143f --- /dev/null +++ b/1502-can-make-arithmetic-progression-from-sequence/README.md @@ -0,0 +1,27 @@ +

1502. Can Make Arithmetic Progression From Sequence

Easy


A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

+ +

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: arr = [3,5,1]
+Output: true
+Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
+
+ +

Example 2:

+ +
Input: arr = [1,2,4]
+Output: false
+Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= arr.length <= 1000
  • +
  • -106 <= arr[i] <= 106
  • +
+
\ No newline at end of file diff --git a/1503-last-moment-before-all-ants-fall-out-of-a-plank/1503-last-moment-before-all-ants-fall-out-of-a-plank.cpp b/1503-last-moment-before-all-ants-fall-out-of-a-plank/1503-last-moment-before-all-ants-fall-out-of-a-plank.cpp new file mode 100644 index 00000000..fb29609d --- /dev/null +++ b/1503-last-moment-before-all-ants-fall-out-of-a-plank/1503-last-moment-before-all-ants-fall-out-of-a-plank.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int getLastMoment(int n, vector& left, vector& right) { + + int maxi = 0; + + for(auto& itr : left) + { + maxi = max(maxi, itr); + } + + for(auto& itr : right) + { + maxi = max(maxi, n - itr); + } + + return maxi; + + } +}; \ No newline at end of file diff --git a/1503-last-moment-before-all-ants-fall-out-of-a-plank/NOTES.md b/1503-last-moment-before-all-ants-fall-out-of-a-plank/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1503-last-moment-before-all-ants-fall-out-of-a-plank/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1503-last-moment-before-all-ants-fall-out-of-a-plank/README.md b/1503-last-moment-before-all-ants-fall-out-of-a-plank/README.md new file mode 100644 index 00000000..0087fe01 --- /dev/null +++ b/1503-last-moment-before-all-ants-fall-out-of-a-plank/README.md @@ -0,0 +1,48 @@ +

1503. Last Moment Before All Ants Fall Out of a Plank

Medium


We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.

+ +

When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.

+ +

When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.

+ +

Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.

+ +

 

+

Example 1:

+ +
Input: n = 4, left = [4,3], right = [0,1]
+Output: 4
+Explanation: In the image above:
+-The ant at index 0 is named A and going to the right.
+-The ant at index 1 is named B and going to the right.
+-The ant at index 3 is named C and going to the left.
+-The ant at index 4 is named D and going to the left.
+The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).
+
+ +

Example 2:

+ +
Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
+Output: 7
+Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.
+
+ +

Example 3:

+ +
Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []
+Output: 7
+Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
  • 0 <= left.length <= n + 1
  • +
  • 0 <= left[i] <= n
  • +
  • 0 <= right.length <= n + 1
  • +
  • 0 <= right[i] <= n
  • +
  • 1 <= left.length + right.length <= n + 1
  • +
  • All values of left and right are unique, and each value can appear only in one of the two arrays.
  • +
+
\ No newline at end of file diff --git a/1508-range-sum-of-sorted-subarray-sums/1508-range-sum-of-sorted-subarray-sums.cpp b/1508-range-sum-of-sorted-subarray-sums/1508-range-sum-of-sorted-subarray-sums.cpp new file mode 100644 index 00000000..a4ebe508 --- /dev/null +++ b/1508-range-sum-of-sorted-subarray-sums/1508-range-sum-of-sorted-subarray-sums.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int rangeSum(vector& nums, int n, int left, int right) { + + vector sums; + + for(int i = 0; i < n; ++i) + { + int sum = 0; + for(int j = i; j < n; ++j) + { + sum += nums[j]; + sums.push_back(sum); + } + } + + sort(sums.begin(), sums.end()); + + vector pref(sums.size()); + + pref[0] = sums[0]; + + const int mod = 1e9+7; + int ans = 0; + + for(int i = left-1; i < right; ++i) + ans = (ans + sums[i]) % mod; + + return ans; + + } +}; \ No newline at end of file diff --git a/1508-range-sum-of-sorted-subarray-sums/NOTES.md b/1508-range-sum-of-sorted-subarray-sums/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1508-range-sum-of-sorted-subarray-sums/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1508-range-sum-of-sorted-subarray-sums/README.md b/1508-range-sum-of-sorted-subarray-sums/README.md new file mode 100644 index 00000000..ac175361 --- /dev/null +++ b/1508-range-sum-of-sorted-subarray-sums/README.md @@ -0,0 +1,35 @@ +

1508. Range Sum of Sorted Subarray Sums

Medium


You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.

+ +

Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
+Output: 13 
+Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. 
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
+Output: 6
+Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
+
+ +

Example 3:

+ +
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
+Output: 50
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 100
  • +
  • 1 <= left <= right <= n * (n + 1) / 2
  • +
+
\ No newline at end of file diff --git a/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp new file mode 100644 index 00000000..f0cfa336 --- /dev/null +++ b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minDifference(vector& nums) { + + int n = nums.size(); + + if(n <= 3) + return 0; + + auto calc = [&](int i, int j) + { + return nums[j] - nums[i]; + }; + + sort(nums.begin(), nums.end()); + + return min({calc(3, n-1), calc(0, n-4), calc(1, n-3), calc(2, n-2)}); + + } +}; \ No newline at end of file diff --git a/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/NOTES.md b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/README.md b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/README.md new file mode 100644 index 00000000..ea8a7485 --- /dev/null +++ b/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves/README.md @@ -0,0 +1,48 @@ +

1509. Minimum Difference Between Largest and Smallest Value in Three Moves

Medium


You are given an integer array nums.

+ +

In one move, you can choose one element of nums and change it to any value.

+ +

Return the minimum difference between the largest and smallest value of nums after performing at most three moves.

+ +

 

+

Example 1:

+ +
Input: nums = [5,3,2,4]
+Output: 0
+Explanation: We can make at most 3 moves.
+In the first move, change 2 to 3. nums becomes [5,3,3,4].
+In the second move, change 4 to 3. nums becomes [5,3,3,3].
+In the third move, change 5 to 3. nums becomes [3,3,3,3].
+After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
+
+ +

Example 2:

+ +
Input: nums = [1,5,0,10,14]
+Output: 1
+Explanation: We can make at most 3 moves.
+In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
+In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
+In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
+After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.
+It can be shown that there is no way to make the difference 0 in 3 moves.
+ +

Example 3:

+ +
Input: nums = [3,100,20]
+Output: 0
+Explanation: We can make at most 3 moves.
+In the first move, change 100 to 7. nums becomes [3,7,20].
+In the second move, change 20 to 7. nums becomes [3,7,7].
+In the third move, change 3 to 7. nums becomes [7,7,7].
+After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/1512-number-of-good-pairs/1512-number-of-good-pairs.cpp b/1512-number-of-good-pairs/1512-number-of-good-pairs.cpp new file mode 100644 index 00000000..1b672930 --- /dev/null +++ b/1512-number-of-good-pairs/1512-number-of-good-pairs.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numIdenticalPairs(vector& nums) { + + int n = nums.size(); + + unordered_map mp; + + for(auto& itr : nums) + ++mp[itr]; + + int count = 0; + + for(auto& [key, value] : mp) + { + count += (value * (value-1))/2; + } + + return count; + } +}; \ No newline at end of file diff --git a/1512-number-of-good-pairs/NOTES.md b/1512-number-of-good-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1512-number-of-good-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1512-number-of-good-pairs/README.md b/1512-number-of-good-pairs/README.md new file mode 100644 index 00000000..8cdeb85f --- /dev/null +++ b/1512-number-of-good-pairs/README.md @@ -0,0 +1,33 @@ +

1512. Number of Good Pairs

Easy


Given an array of integers nums, return the number of good pairs.

+ +

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1,1,3]
+Output: 4
+Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
+
+ +

Example 2:

+ +
Input: nums = [1,1,1,1]
+Output: 6
+Explanation: Each pair in the array are good.
+
+ +

Example 3:

+ +
Input: nums = [1,2,3]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1514-path-with-maximum-probability/1514-path-with-maximum-probability.cpp b/1514-path-with-maximum-probability/1514-path-with-maximum-probability.cpp new file mode 100644 index 00000000..2c1b7ccb --- /dev/null +++ b/1514-path-with-maximum-probability/1514-path-with-maximum-probability.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + + vector> adj[n]; + + for(int i = 0; i < edges.size(); ++i) + { + int u = edges[i][0]; + int v = edges[i][1]; + + adj[u].push_back({v, succProb[i]}); + adj[v].push_back({u , succProb[i]}); + } + + queue q; + + vector dist(n, 0.0); + + dist[start] = 1.0; + + q.push(start); + + while(!q.empty()) + { + int node = q.front(); + + q.pop(); + + for(auto itr : adj[node]) + { + int x = itr.first; + double prob = itr.second; + + double newProb = dist[node] * prob; + + if(newProb > dist[x]) + { + dist[x] = newProb; + q.push(x); + } + } + } + + return dist[end]; + + } +}; \ No newline at end of file diff --git a/1514-path-with-maximum-probability/NOTES.md b/1514-path-with-maximum-probability/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1514-path-with-maximum-probability/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1514-path-with-maximum-probability/README.md b/1514-path-with-maximum-probability/README.md new file mode 100644 index 00000000..01914192 --- /dev/null +++ b/1514-path-with-maximum-probability/README.md @@ -0,0 +1,47 @@ +

1514. Path with Maximum Probability

Medium


You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].

+ +

Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.

+ +

If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

+ +

 

+

Example 1:

+ +

+ +
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
+Output: 0.25000
+Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
+
+ +

Example 2:

+ +

+ +
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
+Output: 0.30000
+
+ +

Example 3:

+ +

+ +
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
+Output: 0.00000
+Explanation: There is no path between 0 and 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 10^4
  • +
  • 0 <= start, end < n
  • +
  • start != end
  • +
  • 0 <= a, b < n
  • +
  • a != b
  • +
  • 0 <= succProb.length == edges.length <= 2*10^4
  • +
  • 0 <= succProb[i] <= 1
  • +
  • There is at most one edge between every two nodes.
  • +
+
\ No newline at end of file diff --git a/1518-water-bottles/1518-water-bottles.cpp b/1518-water-bottles/1518-water-bottles.cpp new file mode 100644 index 00000000..d7fba118 --- /dev/null +++ b/1518-water-bottles/1518-water-bottles.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int numWaterBottles(int numBottles, int numExchange) { + + int ans = numBottles; + + while((numBottles/numExchange) > 0) + { + ans += (numBottles/numExchange); + int rem = (numBottles%numExchange); + numBottles /= numExchange; + numBottles += rem; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1518-water-bottles/NOTES.md b/1518-water-bottles/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1518-water-bottles/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1518-water-bottles/README.md b/1518-water-bottles/README.md new file mode 100644 index 00000000..cb5e9b9e --- /dev/null +++ b/1518-water-bottles/README.md @@ -0,0 +1,31 @@ +

1518. Water Bottles

Easy


There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.

+ +

The operation of drinking a full water bottle turns it into an empty bottle.

+ +

Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.

+ +

 

+

Example 1:

+ +
Input: numBottles = 9, numExchange = 3
+Output: 13
+Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
+Number of water bottles you can drink: 9 + 3 + 1 = 13.
+
+ +

Example 2:

+ +
Input: numBottles = 15, numExchange = 4
+Output: 19
+Explanation: You can exchange 4 empty bottles to get 1 full water bottle. 
+Number of water bottles you can drink: 15 + 3 + 1 = 19.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numBottles <= 100
  • +
  • 2 <= numExchange <= 100
  • +
+
\ No newline at end of file diff --git a/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.cpp b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.cpp new file mode 100644 index 00000000..c60434ce --- /dev/null +++ b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector fun(vector> &adj, string &labels, int i,vector&result){ + vector ans(26, 0); + result[i] = 1; + ans[labels[i] - 'a'] = 1; + + for(int j = 0; j != adj[i].size(); j++) + if(!result[adj[i][j]]){ + vector tmp = fun(adj, labels,adj[i][j],result); + for(int k = 0; k != 26; k++) ans[k] += tmp[k]; + } + + result[i] = ans[labels[i] - 'a']; + + return ans; + } + + vector countSubTrees(int n, vector>& edges, string labels) { + vector> adj(n); + vector result(n,0); + for(int i = 0; i != edges.size(); i++) + {adj[edges[i][0]].push_back(edges[i][1]); + adj[edges[i][1]].push_back(edges[i][0]); + } + + fun(adj, labels, 0,result); + return result; + } +}; \ No newline at end of file diff --git a/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/README.md b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/README.md new file mode 100644 index 00000000..c20a15bc --- /dev/null +++ b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label/README.md @@ -0,0 +1,46 @@ +

1519. Number of Nodes in the Sub-Tree With the Same Label

Medium


You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).

+ +

The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.

+ +

Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.

+ +

A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.

+ +

 

+

Example 1:

+ +
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
+Output: [2,1,1,1,1,1,1]
+Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
+Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
+
+ +

Example 2:

+ +
Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
+Output: [4,2,1,1]
+Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
+The sub-tree of node 3 contains only node 3, so the answer is 1.
+The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
+The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
+
+ +

Example 3:

+ +
Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
+Output: [3,2,1,1,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • labels.length == n
  • +
  • labels is consisting of only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1523-count-odd-numbers-in-an-interval-range/1523-count-odd-numbers-in-an-interval-range.cpp b/1523-count-odd-numbers-in-an-interval-range/1523-count-odd-numbers-in-an-interval-range.cpp new file mode 100644 index 00000000..4bd1e11b --- /dev/null +++ b/1523-count-odd-numbers-in-an-interval-range/1523-count-odd-numbers-in-an-interval-range.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int countOdds(int low, int high) { + + int ans = 0; + bool one = false, two = false; + + if(low & 1) + ++ans, one = true; + if(high & 1) + ++ans, two = true; + ans += (high-low)/2; + + if(one and two) + ans -= 1; + + return ans; + + } +}; \ No newline at end of file diff --git a/1523-count-odd-numbers-in-an-interval-range/NOTES.md b/1523-count-odd-numbers-in-an-interval-range/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1523-count-odd-numbers-in-an-interval-range/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1530-number-of-good-leaf-nodes-pairs/NOTES.md b/1530-number-of-good-leaf-nodes-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1530-number-of-good-leaf-nodes-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1531-string-compression-ii/1531-string-compression-ii.cpp b/1531-string-compression-ii/1531-string-compression-ii.cpp new file mode 100644 index 00000000..a8c534fa --- /dev/null +++ b/1531-string-compression-ii/1531-string-compression-ii.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int dp[101][101]; + int dfs(string &s, int left, int K) { + int k = K; + if(s.size() - left <= k) return 0; + if(dp[left][k] >= 0) return dp[left][k]; + int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1; + for(int i = left + 1; i <= s.size(); ++i) { + res = min(res, dfs(s, i, k) + 1 + (c >= 100 ? 3 : (c >= 10 ? 2 : (c > 1 ? 1 :0)))); + if(i == s.size()) break; + if(s[i] == s[left]) ++c; + else if(--k < 0) break; + } + return dp[left][K] = res; + } + + int getLengthOfOptimalCompression(string s, int k) { + memset(dp, -1, sizeof(dp)); + return dfs(s, 0, k); + } +}; diff --git a/1531-string-compression-ii/README.md b/1531-string-compression-ii/README.md new file mode 100644 index 00000000..74ed32f7 --- /dev/null +++ b/1531-string-compression-ii/README.md @@ -0,0 +1,38 @@ +

1531. String Compression II

Hard


Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".

+ +

Notice that in this problem, we are not adding '1' after single characters.

+ +

Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.

+ +

Find the minimum length of the run-length encoded version of s after deleting at most k characters.

+ +

 

+

Example 1:

+ +
Input: s = "aaabcccd", k = 2
+Output: 4
+Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
+ +

Example 2:

+ +
Input: s = "aabbaa", k = 2
+Output: 2
+Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
+
+ +

Example 3:

+ +
Input: s = "aaaaaaaaaaa", k = 0
+Output: 3
+Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • 0 <= k <= s.length
  • +
  • s contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1539-kth-missing-positive-number/1539-kth-missing-positive-number.cpp b/1539-kth-missing-positive-number/1539-kth-missing-positive-number.cpp new file mode 100644 index 00000000..5fb8b1aa --- /dev/null +++ b/1539-kth-missing-positive-number/1539-kth-missing-positive-number.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findKthPositive(vector& arr, int k) { + int start = 0, end = arr.size(); + while(start < end) + { + int mid = start + (end - start) /2; + if(arr[mid]- mid - 1 < k) + start = mid + 1; + else + end = mid; + } + return start + k; + } +}; \ No newline at end of file diff --git a/1539-kth-missing-positive-number/NOTES.md b/1539-kth-missing-positive-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1539-kth-missing-positive-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1539-kth-missing-positive-number/README.md b/1539-kth-missing-positive-number/README.md new file mode 100644 index 00000000..295a5838 --- /dev/null +++ b/1539-kth-missing-positive-number/README.md @@ -0,0 +1,34 @@ +

1539. Kth Missing Positive Number

Easy


Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

+ +

Return the kth positive integer that is missing from this array.

+ +

 

+

Example 1:

+ +
Input: arr = [2,3,4,7,11], k = 5
+Output: 9
+Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
+
+ +

Example 2:

+ +
Input: arr = [1,2,3,4], k = 2
+Output: 6
+Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • 1 <= arr[i] <= 1000
  • +
  • 1 <= k <= 1000
  • +
  • arr[i] < arr[j] for 1 <= i < j <= arr.length
  • +
+ +

 

+

Follow up:

+ +

Could you solve this problem in less than O(n) complexity?

+
\ No newline at end of file diff --git a/1544-make-the-string-great/1544-make-the-string-great.cpp b/1544-make-the-string-great/1544-make-the-string-great.cpp new file mode 100644 index 00000000..4c9d7994 --- /dev/null +++ b/1544-make-the-string-great/1544-make-the-string-great.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + + string makeGood(string s) { + + string ans; + + ans += s[0]; + + int n = s.size(); + + for(int i = 1; i < n; ++i) + { + if(!ans.empty() and tolower(ans.back()) == tolower(s[i])) + { + if(s[i] != ans.back()) + ans.pop_back(); + else + ans += s[i]; + } + else + ans += s[i]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1544-make-the-string-great/NOTES.md b/1544-make-the-string-great/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1544-make-the-string-great/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1544-make-the-string-great/README.md b/1544-make-the-string-great/README.md new file mode 100644 index 00000000..4ce6592e --- /dev/null +++ b/1544-make-the-string-great/README.md @@ -0,0 +1,46 @@ +

1544. Make The String Great

Easy


Given a string s of lower and upper case English letters.

+ +

A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

+ +
    +
  • 0 <= i <= s.length - 2
  • +
  • s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
  • +
+ +

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

+ +

Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

+ +

Notice that an empty string is also good.

+ +

 

+

Example 1:

+ +
Input: s = "leEeetcode"
+Output: "leetcode"
+Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
+
+ +

Example 2:

+ +
Input: s = "abBAcC"
+Output: ""
+Explanation: We have many possible scenarios, and all lead to the same answer. For example:
+"abBAcC" --> "aAcC" --> "cC" --> ""
+"abBAcC" --> "abBA" --> "aA" --> ""
+
+ +

Example 3:

+ +
Input: s = "s"
+Output: "s"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only lower and upper case English letters.
  • +
+
\ No newline at end of file diff --git a/1547-minimum-cost-to-cut-a-stick/1547-minimum-cost-to-cut-a-stick.cpp b/1547-minimum-cost-to-cut-a-stick/1547-minimum-cost-to-cut-a-stick.cpp new file mode 100644 index 00000000..ec0fb908 --- /dev/null +++ b/1547-minimum-cost-to-cut-a-stick/1547-minimum-cost-to-cut-a-stick.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int dp[101][101]; + int solve(int start_stick, int end_stick, vector& cuts, int left, int right){ + if(left > right) return 0; + + if(dp[left][right] != -1) return dp[left][right]; + + int cost = 1e9; + + for(int i=left; i<=right; i++){ + int left_cost = solve(start_stick, cuts[i], cuts, left, i-1); + int right_cost = solve(cuts[i], end_stick, cuts, i+1, right); + int curr_cost = (end_stick - start_stick) + left_cost + right_cost; + cost = min(cost,curr_cost); + } + + return dp[left][right] = cost; + } + int minCost(int n, vector& cuts) { + memset(dp,-1,sizeof(dp)); + sort(cuts.begin(),cuts.end()); + return solve(0, n, cuts, 0, cuts.size()-1); + } +}; \ No newline at end of file diff --git a/1547-minimum-cost-to-cut-a-stick/README.md b/1547-minimum-cost-to-cut-a-stick/README.md new file mode 100644 index 00000000..3cad0aef --- /dev/null +++ b/1547-minimum-cost-to-cut-a-stick/README.md @@ -0,0 +1,38 @@ +

1547. Minimum Cost to Cut a Stick

Hard


Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:

+ +

Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.

+ +

You should perform the cuts in order, you can change the order of the cuts as you wish.

+ +

The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.

+ +

Return the minimum total cost of the cuts.

+ +

 

+

Example 1:

+ +
Input: n = 7, cuts = [1,3,4,5]
+Output: 16
+Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:
+
+The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
+Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
+ +

Example 2:

+ +
Input: n = 9, cuts = [5,6,1,4,2]
+Output: 22
+Explanation: If you try the given cuts ordering the cost will be 25.
+There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 106
  • +
  • 1 <= cuts.length <= min(n - 1, 100)
  • +
  • 1 <= cuts[i] <= n - 1
  • +
  • All the integers in cuts array are distinct.
  • +
+
\ No newline at end of file diff --git a/1550-three-consecutive-odds/1550-three-consecutive-odds.cpp b/1550-three-consecutive-odds/1550-three-consecutive-odds.cpp new file mode 100644 index 00000000..9d510a25 --- /dev/null +++ b/1550-three-consecutive-odds/1550-three-consecutive-odds.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool threeConsecutiveOdds(vector& arr) { + + int n = arr.size(); + + if(n < 3) + return false; + + for(int i = 2; i < n; ++i) + { + if(arr[i] & 1 and arr[i-1] & 1 and arr[i-2] & 1) return true; + } + + return false; + } +}; \ No newline at end of file diff --git a/1550-three-consecutive-odds/NOTES.md b/1550-three-consecutive-odds/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1550-three-consecutive-odds/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1550-three-consecutive-odds/README.md b/1550-three-consecutive-odds/README.md new file mode 100644 index 00000000..6efb9b86 --- /dev/null +++ b/1550-three-consecutive-odds/README.md @@ -0,0 +1,24 @@ +

1550. Three Consecutive Odds

Easy


Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. +

 

+

Example 1:

+ +
Input: arr = [2,6,4,1]
+Output: false
+Explanation: There are no three consecutive odds.
+
+ +

Example 2:

+ +
Input: arr = [1,2,34,3,4,5,7,23,12]
+Output: true
+Explanation: [5,7,23] are three consecutive odds.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • 1 <= arr[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp b/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp new file mode 100644 index 00000000..b510ea76 --- /dev/null +++ b/1552-magnetic-force-between-two-balls/1552-magnetic-force-between-two-balls.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + + int isPossible(int mid, int m, vector& position) + { + int prev = 0, n = position.size(); + int balls = 1 ; + + for(int i = 1; i < n; ++i) + { + if(position[i] - position[prev] >= mid) + { + ++balls; + prev = i; + } + } + + return balls >= m; + } + + int maxDistance(vector& position, int m) { + + int n = position.size(); + + sort(position.begin(), position.end()); + + int low = 1, high = position.back() - position[0]; + int ans = 0; + + while(low <= high) + { + int mid = (low + high) / 2; + + if(isPossible(mid, m, position)) + { + ans = mid; + low = mid+1; + } + else + high = mid-1; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1552-magnetic-force-between-two-balls/NOTES.md b/1552-magnetic-force-between-two-balls/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1552-magnetic-force-between-two-balls/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1552-magnetic-force-between-two-balls/README.md b/1552-magnetic-force-between-two-balls/README.md new file mode 100644 index 00000000..eee52ed4 --- /dev/null +++ b/1552-magnetic-force-between-two-balls/README.md @@ -0,0 +1,32 @@ +

1552. Magnetic Force Between Two Balls

Medium


In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

+ +

Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

+ +

Given the integer array position and the integer m. Return the required force.

+ +

 

+

Example 1:

+ +
Input: position = [1,2,3,4,7], m = 3
+Output: 3
+Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
+
+ +

Example 2:

+ +
Input: position = [5,4,3,2,1,1000000000], m = 2
+Output: 999999999
+Explanation: We can use baskets 1 and 1000000000.
+
+ +

 

+

Constraints:

+ +
    +
  • n == position.length
  • +
  • 2 <= n <= 105
  • +
  • 1 <= position[i] <= 109
  • +
  • All integers in position are distinct.
  • +
  • 2 <= m <= position.length
  • +
+
\ No newline at end of file diff --git a/1568-minimum-number-of-days-to-disconnect-island/1568-minimum-number-of-days-to-disconnect-island.cpp b/1568-minimum-number-of-days-to-disconnect-island/1568-minimum-number-of-days-to-disconnect-island.cpp new file mode 100644 index 00000000..7c93a1bf --- /dev/null +++ b/1568-minimum-number-of-days-to-disconnect-island/1568-minimum-number-of-days-to-disconnect-island.cpp @@ -0,0 +1,82 @@ +class Solution { +public: + + vector dx = {-1,0,0,+1}; + vector dy = {0,-1,+1,0}; + + void dfs(int i, int j, vector>& grid, vector>& visited) + { + visited[i][j] = 1; + + for(int k = 0; k < 4; ++k) + { + int newx = dx[k] + i; + int newy = dy[k] + j; + + if(newx >= 0 and newy >= 0 and newx < grid.size() and newy < grid[0].size() and grid[newx][newy] == 1 and !visited[newx][newy]) + { + dfs(newx,newy, grid, visited); + } + } + } + + int countNumberofIslands(vector>& grid) + { + int n = grid.size(); + int m = grid[0].size(); + int count = 0; + + vector> visited(n,vector(m,0)); + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1 and !visited[i][j]) + { + ++count; + dfs(i,j,grid,visited); + } + } + } + + return count; + } + + int minDays(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + int island = countNumberofIslands(grid); + + if(island > 1 or island == 0) + return 0; + + int oneCount = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1) + { + grid[i][j] = 0; + + island = countNumberofIslands(grid); + + if(island > 1) + return 1; + + grid[i][j] = 1; + + ++oneCount; + } + } + } + + if(oneCount == 1) + return 1; + + return 2; + + } +}; \ No newline at end of file diff --git a/1568-minimum-number-of-days-to-disconnect-island/README.md b/1568-minimum-number-of-days-to-disconnect-island/README.md new file mode 100644 index 00000000..652dcb78 --- /dev/null +++ b/1568-minimum-number-of-days-to-disconnect-island/README.md @@ -0,0 +1,35 @@ +

1568. Minimum Number of Days to Disconnect Island

Hard


You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.

+ +

The grid is said to be connected if we have exactly one island, otherwise is said disconnected.

+ +

In one day, we are allowed to change any single land cell (1) into a water cell (0).

+ +

Return the minimum number of days to disconnect the grid.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
+
+Output: 2
+Explanation: We need at least 2 days to get a disconnected grid.
+Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
+
+ +

Example 2:

+ +
Input: grid = [[1,1]]
+Output: 2
+Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 30
  • +
  • grid[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1569-number-of-ways-to-reorder-array-to-get-same-bst/1569-number-of-ways-to-reorder-array-to-get-same-bst.cpp b/1569-number-of-ways-to-reorder-array-to-get-same-bst/1569-number-of-ways-to-reorder-array-to-get-same-bst.cpp new file mode 100644 index 00000000..ac145f0a --- /dev/null +++ b/1569-number-of-ways-to-reorder-array-to-get-same-bst/1569-number-of-ways-to-reorder-array-to-get-same-bst.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector < vector < long long > > pascal; + int MOD = 1e9 + 7; + + int numOfWays(vector& nums) { + int N = nums.size(); + pascal = vector < vector < long long > > (N + 1); + for (int i = 0; i < N + 1; i ++){ + pascal[i] = vector < long long > (i + 1, 1); + for (int j = 1; j < i; j ++){ + pascal[i][j] = (pascal[i - 1][j] + pascal[i - 1][j - 1])%MOD; + } + } + return dfs(nums) - 1; + } + + int dfs(vector < int > nums){ + if (nums.size() <= 2) + return 1; + vector < int > left, right; + for (int i = 1; i < int(nums.size()); i ++){ + if (nums[i] < nums[0]) + left.push_back(nums[i]); + else + right.push_back(nums[i]); + } + return (((dfs(left) * pascal[nums.size() - 1][left.size()]) % MOD) * dfs(right))%MOD; + } +}; \ No newline at end of file diff --git a/1569-number-of-ways-to-reorder-array-to-get-same-bst/NOTES.md b/1569-number-of-ways-to-reorder-array-to-get-same-bst/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1569-number-of-ways-to-reorder-array-to-get-same-bst/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1569-number-of-ways-to-reorder-array-to-get-same-bst/README.md b/1569-number-of-ways-to-reorder-array-to-get-same-bst/README.md new file mode 100644 index 00000000..93cf7d10 --- /dev/null +++ b/1569-number-of-ways-to-reorder-array-to-get-same-bst/README.md @@ -0,0 +1,46 @@ +

1569. Number of Ways to Reorder Array to Get Same BST

Hard


Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.

+ +
    +
  • For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.
  • +
+ +

Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.

+ +

Since the answer may be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: nums = [2,1,3]
+Output: 1
+Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
+
+ +

Example 2:

+ +
Input: nums = [3,4,5,1,2]
+Output: 5
+Explanation: The following 5 arrays will yield the same BST: 
+[3,1,2,4,5]
+[3,1,4,2,5]
+[3,1,4,5,2]
+[3,4,1,2,5]
+[3,4,1,5,2]
+
+ +

Example 3:

+ +
Input: nums = [1,2,3]
+Output: 0
+Explanation: There are no other orderings of nums that will yield the same BST.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= nums.length
  • +
  • All integers in nums are distinct.
  • +
+
\ No newline at end of file diff --git a/1572-matrix-diagonal-sum/1572-matrix-diagonal-sum.cpp b/1572-matrix-diagonal-sum/1572-matrix-diagonal-sum.cpp new file mode 100644 index 00000000..7025a6aa --- /dev/null +++ b/1572-matrix-diagonal-sum/1572-matrix-diagonal-sum.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int diagonalSum(vector>& mat) { + + int n = mat.size(), m = mat[0].size(); + + int sum = 0; + + for(int i = 0; i < n; ++i) + { + sum += (mat[i][n-i-1] + mat[i][i]); + } + + sum = (n & 1) ? sum - mat[n/2][n/2] : sum; + + return sum; + + } +}; \ No newline at end of file diff --git a/1572-matrix-diagonal-sum/NOTES.md b/1572-matrix-diagonal-sum/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1572-matrix-diagonal-sum/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1572-matrix-diagonal-sum/README.md b/1572-matrix-diagonal-sum/README.md new file mode 100644 index 00000000..98d612e2 --- /dev/null +++ b/1572-matrix-diagonal-sum/README.md @@ -0,0 +1,39 @@ +

1572. Matrix Diagonal Sum

Easy


Given a square matrix mat, return the sum of the matrix diagonals.

+ +

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

+ +

 

+

Example 1:

+ +
Input: mat = [[1,2,3],
+              [4,5,6],
+              [7,8,9]]
+Output: 25
+Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
+Notice that element mat[1][1] = 5 is counted only once.
+
+ +

Example 2:

+ +
Input: mat = [[1,1,1,1],
+              [1,1,1,1],
+              [1,1,1,1],
+              [1,1,1,1]]
+Output: 8
+
+ +

Example 3:

+ +
Input: mat = [[5]]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • n == mat.length == mat[i].length
  • +
  • 1 <= n <= 100
  • +
  • 1 <= mat[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/1575-count-all-possible-routes/1575-count-all-possible-routes.cpp b/1575-count-all-possible-routes/1575-count-all-possible-routes.cpp new file mode 100644 index 00000000..3bdbcdac --- /dev/null +++ b/1575-count-all-possible-routes/1575-count-all-possible-routes.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int mod=1e9+7; + + int helper(vector>&dp,vector&locations,int current,int &finish,int fuel, int n){ + + if(fuel<0) + return 0; + + if(dp[current][fuel]!=-1) + return dp[current][fuel]; + + int ans=0; + + if(current==finish) + ans++; + + for(int next=0;next& locations, int start, int finish, int fuel) { + + int n=locations.size(); + + vector>dp(n,vector(fuel+1,-1)); + + return helper(dp,locations,start,finish,fuel,n); + } +}; \ No newline at end of file diff --git a/1575-count-all-possible-routes/NOTES.md b/1575-count-all-possible-routes/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1575-count-all-possible-routes/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1575-count-all-possible-routes/README.md b/1575-count-all-possible-routes/README.md new file mode 100644 index 00000000..458260c8 --- /dev/null +++ b/1575-count-all-possible-routes/README.md @@ -0,0 +1,50 @@ +

1575. Count All Possible Routes

Hard


You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.

+ +

At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.

+ +

Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).

+ +

Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
+Output: 4
+Explanation: The following are all possible routes, each uses 5 units of fuel:
+1 -> 3
+1 -> 2 -> 3
+1 -> 4 -> 3
+1 -> 4 -> 2 -> 3
+
+ +

Example 2:

+ +
Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
+Output: 5
+Explanation: The following are all possible routes:
+1 -> 0, used fuel = 1
+1 -> 2 -> 0, used fuel = 5
+1 -> 2 -> 1 -> 0, used fuel = 5
+1 -> 0 -> 1 -> 0, used fuel = 3
+1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
+
+ +

Example 3:

+ +
Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
+Output: 0
+Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= locations.length <= 100
  • +
  • 1 <= locations[i] <= 109
  • +
  • All integers in locations are distinct.
  • +
  • 0 <= start, finish < locations.length
  • +
  • 1 <= fuel <= 200
  • +
+
\ No newline at end of file diff --git a/1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.cpp b/1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.cpp new file mode 100644 index 00000000..7af1455a --- /dev/null +++ b/1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minCost(string colors, vector& neededTime) { + + int n = colors.size(); + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + int cost = neededTime[i], maxSegmentCost = neededTime[i]; + + while(i+1 < n and colors[i] == colors[i+1]) + { + cost += neededTime[i+1]; + maxSegmentCost = max(maxSegmentCost, neededTime[i+1]); + ++i; + } + + cost -= maxSegmentCost; + + ans += cost; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1578-minimum-time-to-make-rope-colorful/NOTES.md b/1578-minimum-time-to-make-rope-colorful/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1578-minimum-time-to-make-rope-colorful/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1578-minimum-time-to-make-rope-colorful/README.md b/1578-minimum-time-to-make-rope-colorful/README.md new file mode 100644 index 00000000..6e5e854a --- /dev/null +++ b/1578-minimum-time-to-make-rope-colorful/README.md @@ -0,0 +1,40 @@ +

1578. Minimum Time to Make Rope Colorful

Medium


Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.

+ +

Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.

+ +

Return the minimum time Bob needs to make the rope colorful.

+ +

 

+

Example 1:

+ +
Input: colors = "abaac", neededTime = [1,2,3,4,5]
+Output: 3
+Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
+Bob can remove the blue balloon at index 2. This takes 3 seconds.
+There are no longer two consecutive balloons of the same color. Total time = 3.
+ +

Example 2:

+ +
Input: colors = "abc", neededTime = [1,2,3]
+Output: 0
+Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
+
+ +

Example 3:

+ +
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
+Output: 2
+Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
+There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
+
+ +

 

+

Constraints:

+ +
    +
  • n == colors.length == neededTime.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= neededTime[i] <= 104
  • +
  • colors contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.cpp b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.cpp new file mode 100644 index 00000000..8a20e1d5 --- /dev/null +++ b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.cpp @@ -0,0 +1,72 @@ +class Solution { +public: + int find(vector &par,int u) + { + if(u==par[u]) + return u; + return par[u]=find(par,par[u]); + } + void unions(vector &par,int u,int v) + { + int pu=find(par,u); + int pv=find(par,v); + par[pu]=pv; + } + int maxNumEdgesToRemove(int n, vector>& edges) + { + vector a(n+1),b(n+1); + int ans=0; + for(int i=0;i<=n;i++) + { + a[i]=i; + b[i]=i; + } + for(auto &e:edges) + { + if(e[0]!=3) + continue; + if(find(a,e[1])==find(a,e[2])) + { + ans++; + continue; + } + unions(a,e[1],e[2]); + unions(b,e[1],e[2]); + } + for(auto &e:edges) + { + int u=e[1],v=e[2]; + if(e[0]==1) + { + if(find(a,u)==find(a,v)) + { + ans++; + } + else + { + unions(a,u,v); + } + } + else if(e[0]==2) + { + if(find(b,u)==find(b,v)) + { + ans++; + } + else + { + unions(b,u,v); + } + } + } + for(int i=1;i<=n;i++) + { + if(find(a,i)!=find(a,n)||find(b,i)!=find(b,n)) + { + return -1; + } + } + return ans; + + } +}; diff --git a/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/NOTES.md b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/README.md b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/README.md new file mode 100644 index 00000000..3aa33f3e --- /dev/null +++ b/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable/README.md @@ -0,0 +1,53 @@ +

1579. Remove Max Number of Edges to Keep Graph Fully Traversable

Hard


Alice and Bob have an undirected graph of n nodes and three types of edges:

+ +
    +
  • Type 1: Can be traversed by Alice only.
  • +
  • Type 2: Can be traversed by Bob only.
  • +
  • Type 3: Can be traversed by both Alice and Bob.
  • +
+ +

Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.

+ +

Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.

+ +

 

+

Example 1:

+ +

+ +
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
+Output: 2
+Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
+
+ +

Example 2:

+ +

+ +
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
+Output: 0
+Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
+
+ +

Example 3:

+ +

+ +
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
+Output: -1
+Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
+ +

 

+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)
  • +
  • edges[i].length == 3
  • +
  • 1 <= typei <= 3
  • +
  • 1 <= ui < vi <= n
  • +
  • All tuples (typei, ui, vi) are distinct.
  • +
+
\ No newline at end of file diff --git a/1582-special-positions-in-a-binary-matrix/1582-special-positions-in-a-binary-matrix.cpp b/1582-special-positions-in-a-binary-matrix/1582-special-positions-in-a-binary-matrix.cpp new file mode 100644 index 00000000..b1c99cf8 --- /dev/null +++ b/1582-special-positions-in-a-binary-matrix/1582-special-positions-in-a-binary-matrix.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int numSpecial(vector>& mat) { + + int n = mat.size(), m = mat[0].size(); + + vector row(n), col(m); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(mat[i][j] == 1) + ++row[i], ++col[j]; + } + } + + int specialPosition = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(mat[i][j] and row[i] == 1 and col[j] == 1) + ++specialPosition; + } + } + + return specialPosition; + } +}; \ No newline at end of file diff --git a/1582-special-positions-in-a-binary-matrix/NOTES.md b/1582-special-positions-in-a-binary-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1582-special-positions-in-a-binary-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1582-special-positions-in-a-binary-matrix/README.md b/1582-special-positions-in-a-binary-matrix/README.md new file mode 100644 index 00000000..c973d914 --- /dev/null +++ b/1582-special-positions-in-a-binary-matrix/README.md @@ -0,0 +1,29 @@ +

1582. Special Positions in a Binary Matrix

Easy


Given an m x n binary matrix mat, return the number of special positions in mat.

+ +

A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

+ +

 

+

Example 1:

+ +
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
+Output: 1
+Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
+
+ +

Example 2:

+ +
Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
+Output: 3
+Explanation: (0, 0), (1, 1) and (2, 2) are special positions.
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • mat[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1584-min-cost-to-connect-all-points/1584-min-cost-to-connect-all-points.cpp b/1584-min-cost-to-connect-all-points/1584-min-cost-to-connect-all-points.cpp new file mode 100644 index 00000000..b131ebcb --- /dev/null +++ b/1584-min-cost-to-connect-all-points/1584-min-cost-to-connect-all-points.cpp @@ -0,0 +1,112 @@ +class DSU{ + private: + vector rank, parent, size; + public: + DSU(int n) + { + rank.resize(n+1, 0); + size.resize(n+1, 1); + parent.resize(n+1); + + for(int i = 0; i <= n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(parent[u] == u) + return parent[u]; + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parV] < rank[parU]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } + +}; + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + + int n = points.size(); + + vector > adj; + + for(int i = 0; i < n; ++i) + { + for(int j = i+1; j < n; ++j) + { + int weight = abs(points[j][0] - points[i][0]) + abs(points[j][1] - points[i][1]); + + adj.push_back({weight, i, j}); + } + } + + + sort(adj.begin(), adj.end()); + + DSU dsu(n+1); + + int minimumCost = 0 ; + + for(auto& edges : adj) + { + int weight = get<0>(edges); + int u = get<1>(edges); + int v = get<2>(edges); + + if(!dsu.isSame(u, v)) + { + minimumCost += weight; + dsu.unionBySize(u, v); + } + } + + return minimumCost; + } +}; \ No newline at end of file diff --git a/1584-min-cost-to-connect-all-points/NOTES.md b/1584-min-cost-to-connect-all-points/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1584-min-cost-to-connect-all-points/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1584-min-cost-to-connect-all-points/README.md b/1584-min-cost-to-connect-all-points/README.md new file mode 100644 index 00000000..87d9ecda --- /dev/null +++ b/1584-min-cost-to-connect-all-points/README.md @@ -0,0 +1,32 @@ +

1584. Min Cost to Connect All Points

Medium


You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].

+ +

The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.

+ +

Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

+ +

 

+

Example 1:

+ +
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
+Output: 20
+Explanation: 
+
+We can connect the points as shown above to get the minimum cost of 20.
+Notice that there is a unique path between every pair of points.
+
+ +

Example 2:

+ +
Input: points = [[3,12],[-2,5],[-4,1]]
+Output: 18
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= points.length <= 1000
  • +
  • -106 <= xi, yi <= 106
  • +
  • All pairs (xi, yi) are distinct.
  • +
+
\ No newline at end of file diff --git a/1601-maximum-number-of-achievable-transfer-requests/1601-maximum-number-of-achievable-transfer-requests.cpp b/1601-maximum-number-of-achievable-transfer-requests/1601-maximum-number-of-achievable-transfer-requests.cpp new file mode 100644 index 00000000..5a6ae294 --- /dev/null +++ b/1601-maximum-number-of-achievable-transfer-requests/1601-maximum-number-of-achievable-transfer-requests.cpp @@ -0,0 +1,41 @@ +class Solution { + +private: + void helper(int idx, int n, int cur, vector>& requests, vector& dp, int& ans) + { + if(idx == n) + { + for(auto itr : dp) + { + if(itr != 0) + return; + } + + ans = max(ans, cur); + return; + } + + helper(idx+1, n, cur, requests, dp , ans); + + --dp[requests[idx][0]]; + ++dp[requests[idx][1]]; + + helper(idx+1, n ,cur+1, requests, dp, ans); + + ++dp[requests[idx][0]]; + --dp[requests[idx][1]]; + } + +public: + int maximumRequests(int n, vector>& requests) { + + int ans = 0, sz = requests.size(); + + vector dp(n, 0); + + helper(0, sz, 0, requests,dp, ans); + + return ans; + + } +}; \ No newline at end of file diff --git a/1601-maximum-number-of-achievable-transfer-requests/README.md b/1601-maximum-number-of-achievable-transfer-requests/README.md new file mode 100644 index 00000000..1752990c --- /dev/null +++ b/1601-maximum-number-of-achievable-transfer-requests/README.md @@ -0,0 +1,49 @@ +

1601. Maximum Number of Achievable Transfer Requests

Hard


We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.

+ +

You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.

+ +

All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.

+ +

Return the maximum number of achievable requests.

+ +

 

+

Example 1:

+ +
Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
+Output: 5
+Explantion: Let's see the requests:
+From building 0 we have employees x and y and both want to move to building 1.
+From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
+From building 2 we have employee z and they want to move to building 0.
+From building 3 we have employee c and they want to move to building 4.
+From building 4 we don't have any requests.
+We can achieve the requests of users x and b by swapping their places.
+We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
+
+ +

Example 2:

+ +
Input: n = 3, requests = [[0,0],[1,2],[2,1]]
+Output: 3
+Explantion: Let's see the requests:
+From building 0 we have employee x and they want to stay in the same building 0.
+From building 1 we have employee y and they want to move to building 2.
+From building 2 we have employee z and they want to move to building 1.
+We can achieve all the requests. 
+ +

Example 3:

+ +
Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 20
  • +
  • 1 <= requests.length <= 16
  • +
  • requests[i].length == 2
  • +
  • 0 <= fromi, toi < n
  • +
+
\ No newline at end of file diff --git a/1603-design-parking-system/1603-design-parking-system.cpp b/1603-design-parking-system/1603-design-parking-system.cpp new file mode 100644 index 00000000..0815e1a0 --- /dev/null +++ b/1603-design-parking-system/1603-design-parking-system.cpp @@ -0,0 +1,31 @@ +class ParkingSystem { +public: + + unordered_map mp; + + ParkingSystem(int big, int medium, int small) { + + mp.insert({1, big}); + mp.insert({2, medium}); + mp.insert({3, small}); + + } + + bool addCar(int carType) { + + if(mp[carType] > 0) + { + --mp[carType]; + return true; + } + + return false; + + } +}; + +/** + * Your ParkingSystem object will be instantiated and called as such: + * ParkingSystem* obj = new ParkingSystem(big, medium, small); + * bool param_1 = obj->addCar(carType); + */ \ No newline at end of file diff --git a/1603-design-parking-system/README.md b/1603-design-parking-system/README.md new file mode 100644 index 00000000..3d8e5446 --- /dev/null +++ b/1603-design-parking-system/README.md @@ -0,0 +1,35 @@ +

1603. Design Parking System

Easy


Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

+ +

Implement the ParkingSystem class:

+ +
    +
  • ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.
  • +
  • bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.
  • +
+ +

 

+

Example 1:

+ +
Input
+["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
+[[1, 1, 0], [1], [2], [3], [1]]
+Output
+[null, true, true, false, false]
+
+Explanation
+ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
+parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
+parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
+parkingSystem.addCar(3); // return false because there is no available slot for a small car
+parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= big, medium, small <= 1000
  • +
  • carType is 1, 2, or 3
  • +
  • At most 1000 calls will be made to addCar
  • +
+
\ No newline at end of file diff --git a/1605-find-valid-matrix-given-row-and-column-sums/1605-find-valid-matrix-given-row-and-column-sums.cpp b/1605-find-valid-matrix-given-row-and-column-sums/1605-find-valid-matrix-given-row-and-column-sums.cpp new file mode 100644 index 00000000..cab3c516 --- /dev/null +++ b/1605-find-valid-matrix-given-row-and-column-sums/1605-find-valid-matrix-given-row-and-column-sums.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector> restoreMatrix(vector& rowSum, vector& colSum) { + + int m = rowSum.size(); + int n = colSum.size(); + vector> ans(m, vector(n, 0)); + + for(int i = 0; i < m; i++) { + for(int j = 0; j < n; j++) { + if (rowSum[i] == 0 || colSum[j] == 0) { + ans[i][j] = 0; + } else { + ans[i][j] = min(rowSum[i], colSum[j]); + rowSum[i] -= ans[i][j]; + colSum[j] -= ans[i][j]; + } + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1605-find-valid-matrix-given-row-and-column-sums/NOTES.md b/1605-find-valid-matrix-given-row-and-column-sums/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1605-find-valid-matrix-given-row-and-column-sums/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1608-special-array-with-x-elements-greater-than-or-equal-x/1608-special-array-with-x-elements-greater-than-or-equal-x.cpp b/1608-special-array-with-x-elements-greater-than-or-equal-x/1608-special-array-with-x-elements-greater-than-or-equal-x.cpp new file mode 100644 index 00000000..2de9660e --- /dev/null +++ b/1608-special-array-with-x-elements-greater-than-or-equal-x/1608-special-array-with-x-elements-greater-than-or-equal-x.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int specialArray(vector& nums) { + + int n = nums.size(); + + vector pref(1001, 0); + + for(auto& ele : nums) + ++pref[ele]; + + for(int i = 999; i >= 0; --i) + pref[i] += pref[i+1]; + + for(int i = 1; i <= 1000; ++i) + { + if(pref[i] == i) + return i; + } + + return -1; + } +}; \ No newline at end of file diff --git a/1608-special-array-with-x-elements-greater-than-or-equal-x/NOTES.md b/1608-special-array-with-x-elements-greater-than-or-equal-x/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1608-special-array-with-x-elements-greater-than-or-equal-x/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1608-special-array-with-x-elements-greater-than-or-equal-x/README.md b/1608-special-array-with-x-elements-greater-than-or-equal-x/README.md new file mode 100644 index 00000000..6ccc0038 --- /dev/null +++ b/1608-special-array-with-x-elements-greater-than-or-equal-x/README.md @@ -0,0 +1,40 @@ +

1608. Special Array With X Elements Greater Than or Equal X

Easy


You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.

+ +

Notice that x does not have to be an element in nums.

+ +

Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

+ +

 

+

Example 1:

+ +
Input: nums = [3,5]
+Output: 2
+Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
+
+ +

Example 2:

+ +
Input: nums = [0,0]
+Output: -1
+Explanation: No numbers fit the criteria for x.
+If x = 0, there should be 0 numbers >= x, but there are 2.
+If x = 1, there should be 1 number >= x, but there are 0.
+If x = 2, there should be 2 numbers >= x, but there are 0.
+x cannot be greater since there are only 2 numbers in nums.
+
+ +

Example 3:

+ +
Input: nums = [0,4,3,0,4]
+Output: 3
+Explanation: There are 3 values that are greater than or equal to 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1609-even-odd-tree/1609-even-odd-tree.cpp b/1609-even-odd-tree/1609-even-odd-tree.cpp new file mode 100644 index 00000000..ccdc9a04 --- /dev/null +++ b/1609-even-odd-tree/1609-even-odd-tree.cpp @@ -0,0 +1,98 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + bool checkAscending(vector& currLevel) + { + int n = currLevel.size(); + + if(currLevel[0] % 2 == 0) + return false; + + for(int i = 1; i < n; ++i) + { + if(currLevel[i] <= currLevel[i-1]) + return false; + if(currLevel[i] % 2 == 0) + return false; + } + return true; + } + + bool checkDescending(vector& currLevel) + { + int n = currLevel.size(); + + if(currLevel[0] & 1) + return false; + for(int i = 1; i < n; ++i) + { + if(currLevel[i] >= currLevel[i-1]) + return false; + if(currLevel[i] & 1) + return false; + } + return true; + } + + bool isEvenOddTree(TreeNode* root) { + + int level = 0; + + queue q; + + q.push(root); + + bool isEvOddTree = true; + + while(!q.empty()) + { + int size = q.size(); + + vector currLevel; + + for(int i = 0; i < size; ++i) + { + TreeNode* curr = q.front(); + q.pop(); + + currLevel.push_back(curr->val); + + if(curr->left) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + + if(level & 1) + { + if(!checkDescending(currLevel)) + { + isEvOddTree = false; + break; + } + } + else + { + if(!checkAscending(currLevel)) + { + isEvOddTree = false; + break; + } + } + } + ++level; + } + + return isEvOddTree; + } +}; \ No newline at end of file diff --git a/1609-even-odd-tree/NOTES.md b/1609-even-odd-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1609-even-odd-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1609-even-odd-tree/README.md b/1609-even-odd-tree/README.md new file mode 100644 index 00000000..706e4f8f --- /dev/null +++ b/1609-even-odd-tree/README.md @@ -0,0 +1,49 @@ +

1609. Even Odd Tree

Medium


A binary tree is named Even-Odd if it meets the following conditions:

+ +
    +
  • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
  • +
  • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
  • +
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
  • +
+ +

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

+ +

 

+

Example 1:

+ +
Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
+Output: true
+Explanation: The node values on each level are:
+Level 0: [1]
+Level 1: [10,4]
+Level 2: [3,7,9]
+Level 3: [12,8,6,2]
+Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
+
+ +

Example 2:

+ +
Input: root = [5,4,2,3,3,7]
+Output: false
+Explanation: The node values on each level are:
+Level 0: [5]
+Level 1: [4,2]
+Level 2: [3,3,7]
+Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
+
+ +

Example 3:

+ +
Input: root = [5,9,1,3,5,7]
+Output: false
+Explanation: Node values in the level 1 should be even integers.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 105].
  • +
  • 1 <= Node.val <= 106
  • +
+
\ No newline at end of file diff --git a/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp b/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp new file mode 100644 index 00000000..9cc248b4 --- /dev/null +++ b/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxDepth(string s) { + + int open = 0, ans = 0; + + for(auto& ch : s) + { + if(ch == '(') + ++open; + else if(ch == ')') + --open; + ans = max(ans, open); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1614-maximum-nesting-depth-of-the-parentheses/NOTES.md b/1614-maximum-nesting-depth-of-the-parentheses/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1614-maximum-nesting-depth-of-the-parentheses/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1614-maximum-nesting-depth-of-the-parentheses/README.md b/1614-maximum-nesting-depth-of-the-parentheses/README.md new file mode 100644 index 00000000..b636dfcb --- /dev/null +++ b/1614-maximum-nesting-depth-of-the-parentheses/README.md @@ -0,0 +1,44 @@ +

1614. Maximum Nesting Depth of the Parentheses

Easy


A string is a valid parentheses string (denoted VPS) if it meets one of the following:

+ +
    +
  • It is an empty string "", or a single character not equal to "(" or ")",
  • +
  • It can be written as AB (A concatenated with B), where A and B are VPS's, or
  • +
  • It can be written as (A), where A is a VPS.
  • +
+ +

We can similarly define the nesting depth depth(S) of any VPS S as follows:

+ +
    +
  • depth("") = 0
  • +
  • depth(C) = 0, where C is a string with a single character not equal to "(" or ")".
  • +
  • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.
  • +
  • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
  • +
+ +

For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

+ +

Given a VPS represented as string s, return the nesting depth of s.

+ +

 

+

Example 1:

+ +
Input: s = "(1+(2*3)+((8)/4))+1"
+Output: 3
+Explanation: Digit 8 is inside of 3 nested parentheses in the string.
+
+ +

Example 2:

+ +
Input: s = "(1)+((2))+(((3)))"
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
  • +
  • It is guaranteed that parentheses expression s is a VPS.
  • +
+
\ No newline at end of file diff --git a/1615-maximal-network-rank/1615-maximal-network-rank.cpp b/1615-maximal-network-rank/1615-maximal-network-rank.cpp new file mode 100644 index 00000000..60a10050 --- /dev/null +++ b/1615-maximal-network-rank/1615-maximal-network-rank.cpp @@ -0,0 +1,56 @@ +class Solution { + +public: + int maximalNetworkRank(int n, vector>& roads) { + + vector adj[n+1]; + + map, int> mp; + + for(auto& itr : roads) + { + int u = itr[0]; + int v = itr[1]; + + adj[u].push_back(v); + adj[v].push_back(u); + + ++mp[{u,v}]; + } + + int maximalNetworkRank = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < n; ++j) + { + if(i == j) + continue; + + int nodeA = i; + int nodeB = j; + + int currRank = adj[nodeA].size() + adj[nodeB].size(); + + // not intitutive + + // for(auto& itr : adj[nodeA]) + // { + // if(itr == nodeB) + // { + // --currRank; + // break; + // } + // } + + if(mp[{nodeA, nodeB}] or mp[{nodeB, nodeA}]) + --currRank; + + maximalNetworkRank = max(maximalNetworkRank, currRank); + } + } + + return maximalNetworkRank; + + } +}; \ No newline at end of file diff --git a/1615-maximal-network-rank/NOTES.md b/1615-maximal-network-rank/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1615-maximal-network-rank/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1615-maximal-network-rank/README.md b/1615-maximal-network-rank/README.md new file mode 100644 index 00000000..b1a5b3f2 --- /dev/null +++ b/1615-maximal-network-rank/README.md @@ -0,0 +1,46 @@ +

1615. Maximal Network Rank

Medium


There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.

+ +

The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.

+ +

The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.

+ +

Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.

+ +

 

+

Example 1:

+ +

+ +
Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
+Output: 4
+Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
+
+ +

Example 2:

+ +

+ +
Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
+Output: 5
+Explanation: There are 5 roads that are connected to cities 1 or 2.
+
+ +

Example 3:

+ +
Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
+Output: 5
+Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 100
  • +
  • 0 <= roads.length <= n * (n - 1) / 2
  • +
  • roads[i].length == 2
  • +
  • 0 <= ai, bi <= n-1
  • +
  • ai != bi
  • +
  • Each pair of cities has at most one road connecting them.
  • +
+
\ No newline at end of file diff --git a/1624-largest-substring-between-two-equal-characters/1624-largest-substring-between-two-equal-characters.cpp b/1624-largest-substring-between-two-equal-characters/1624-largest-substring-between-two-equal-characters.cpp new file mode 100644 index 00000000..64fb29c3 --- /dev/null +++ b/1624-largest-substring-between-two-equal-characters/1624-largest-substring-between-two-equal-characters.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxLengthBetweenEqualCharacters(string s) { + + int n = s.size(); + + int ans = -1; + + vector occurence(26, -1); + + for(int i = 0; i < n; ++i) + { + int firstOccurence = occurence[s[i] - 'a']; + + if(firstOccurence != -1) + ans = max(ans, i - firstOccurence - 1); + else + occurence[s[i] - 'a'] = i; + } + + return ans ; + } +}; \ No newline at end of file diff --git a/1624-largest-substring-between-two-equal-characters/NOTES.md b/1624-largest-substring-between-two-equal-characters/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1624-largest-substring-between-two-equal-characters/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1624-largest-substring-between-two-equal-characters/README.md b/1624-largest-substring-between-two-equal-characters/README.md new file mode 100644 index 00000000..cfc9757d --- /dev/null +++ b/1624-largest-substring-between-two-equal-characters/README.md @@ -0,0 +1,33 @@ +

1624. Largest Substring Between Two Equal Characters

Easy


Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "aa"
+Output: 0
+Explanation: The optimal substring here is an empty substring between the two 'a's.
+ +

Example 2:

+ +
Input: s = "abca"
+Output: 2
+Explanation: The optimal substring here is "bc".
+
+ +

Example 3:

+ +
Input: s = "cbzxy"
+Output: -1
+Explanation: There are no characters that appear twice in s.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 300
  • +
  • s contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1626-best-team-with-no-conflicts/1626-best-team-with-no-conflicts.cpp b/1626-best-team-with-no-conflicts/1626-best-team-with-no-conflicts.cpp new file mode 100644 index 00000000..a0f445e3 --- /dev/null +++ b/1626-best-team-with-no-conflicts/1626-best-team-with-no-conflicts.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + int n = scores.size(); + int dp[n], ans = 0; + vector> players; + for(int i = 0; i < n; i++) + players.push_back({ages[i], scores[i]}); + sort(players.begin(), players.end()); + for(int i = 0; i < n; i++) { + dp[i] = players[i].second; + for(int j = 0; j < i; j++) { + if(players[j].second <= players[i].second) + dp[i] = max(dp[i], dp[j] + players[i].second); + } + ans = max(ans, dp[i]); + } + return ans; + } +}; \ No newline at end of file diff --git a/1626-best-team-with-no-conflicts/README.md b/1626-best-team-with-no-conflicts/README.md new file mode 100644 index 00000000..ec832c60 --- /dev/null +++ b/1626-best-team-with-no-conflicts/README.md @@ -0,0 +1,38 @@ +

1626. Best Team With No Conflicts

Medium


You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.

+ +

However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.

+ +

Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.

+ +

 

+

Example 1:

+ +
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
+Output: 34
+Explanation: You can choose all the players.
+
+ +

Example 2:

+ +
Input: scores = [4,5,6,5], ages = [2,1,2,1]
+Output: 16
+Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
+
+ +

Example 3:

+ +
Input: scores = [1,2,3,5], ages = [8,9,10,1]
+Output: 6
+Explanation: It is best to choose the first 3 players. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= scores.length, ages.length <= 1000
  • +
  • scores.length == ages.length
  • +
  • 1 <= scores[i] <= 106
  • +
  • 1 <= ages[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1636-sort-array-by-increasing-frequency/README.md b/1636-sort-array-by-increasing-frequency/README.md new file mode 100644 index 00000000..cfe5e97a --- /dev/null +++ b/1636-sort-array-by-increasing-frequency/README.md @@ -0,0 +1,32 @@ +

1636. Sort Array by Increasing Frequency

Easy


Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

+ +

Return the sorted array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2,2,2,3]
+Output: [3,1,1,2,2,2]
+Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
+
+ +

Example 2:

+ +
Input: nums = [2,3,1,3,2]
+Output: [1,3,3,2,2]
+Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
+
+ +

Example 3:

+ +
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
+Output: [5,-1,4,4,-6,-6,1,1,1]
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • -100 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1637-widest-vertical-area-between-two-points-containing-no-points/1637-widest-vertical-area-between-two-points-containing-no-points.cpp b/1637-widest-vertical-area-between-two-points-containing-no-points/1637-widest-vertical-area-between-two-points-containing-no-points.cpp new file mode 100644 index 00000000..8da3ae7b --- /dev/null +++ b/1637-widest-vertical-area-between-two-points-containing-no-points/1637-widest-vertical-area-between-two-points-containing-no-points.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + + int n = points.size(); + + sort(points.begin(), points.end()); + + int ans = 0; + + for(int i = 1; i < n; ++i) + ans = max(ans, points[i][0] - points[i-1][0]); + + return ans; + + } +}; \ No newline at end of file diff --git a/1637-widest-vertical-area-between-two-points-containing-no-points/NOTES.md b/1637-widest-vertical-area-between-two-points-containing-no-points/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1637-widest-vertical-area-between-two-points-containing-no-points/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1637-widest-vertical-area-between-two-points-containing-no-points/README.md b/1637-widest-vertical-area-between-two-points-containing-no-points/README.md new file mode 100644 index 00000000..1dd90505 --- /dev/null +++ b/1637-widest-vertical-area-between-two-points-containing-no-points/README.md @@ -0,0 +1,30 @@ +

1637. Widest Vertical Area Between Two Points Containing No Points

Medium


Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.

+ +

A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.

+ +

Note that points on the edge of a vertical area are not considered included in the area.

+ +

 

+

Example 1:

+​ +
Input: points = [[8,7],[9,9],[7,4],[9,7]]
+Output: 1
+Explanation: Both the red and the blue area are optimal.
+
+ +

Example 2:

+ +
Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • n == points.length
  • +
  • 2 <= n <= 105
  • +
  • points[i].length == 2
  • +
  • 0 <= xi, yi <= 109
  • +
+
\ No newline at end of file diff --git a/1639-number-of-ways-to-form-a-target-string-given-a-dictionary/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.cpp b/1639-number-of-ways-to-form-a-target-string-given-a-dictionary/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.cpp new file mode 100644 index 00000000..6b578038 --- /dev/null +++ b/1639-number-of-ways-to-form-a-target-string-given-a-dictionary/1639-number-of-ways-to-form-a-target-string-given-a-dictionary.cpp @@ -0,0 +1,56 @@ +#define ll long long int +class Solution { +public: + + int mod = 1e9+7; + + int helper(int i, int j, int n, int m , vector& words, string& target, vector>& dp, vector>& freq) + { + if(j >= m) + return 1; + + if(i >= n) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + ll take = 0, notTake = 0; + + notTake = helper(i+1, j, n, m, words, target, dp, freq); + + + if(freq[i][target[j] - 'a']) + take = ((freq[i][target[j]-'a']) * (helper(i+1, j+1, n, m, words, target, dp, freq)))%mod; + + + return dp[i][j] = (take + notTake)%mod; + } + + + int numWays(vector& words, string target) { + + int n = words[0].size(), m = target.size(); + + vector> dp(n+1, vector (m+1, -1)); + + vector> freq(n, vector(26,0)); + + for(auto &itr : words) + { + for(int i =0 ; i& heights, int bricks, int ladders) { + priority_queue pq; + + int i = 0; + for(i = 0; i1642. Furthest Building You Can Reach

Medium


You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

+ +

You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

+ +

While moving from building i to building i+1 (0-indexed),

+ +
    +
  • If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
  • +
  • If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
  • +
+ +

Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

+ +

 

+

Example 1:

+ +
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
+Output: 4
+Explanation: Starting at building 0, you can follow these steps:
+- Go to building 1 without using ladders nor bricks since 4 >= 2.
+- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
+- Go to building 3 without using ladders nor bricks since 7 >= 6.
+- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
+It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
+
+ +

Example 2:

+ +
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
+Output: 7
+
+ +

Example 3:

+ +
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 105
  • +
  • 1 <= heights[i] <= 106
  • +
  • 0 <= bricks <= 109
  • +
  • 0 <= ladders <= heights.length
  • +
+
\ No newline at end of file diff --git a/1647-minimum-deletions-to-make-character-frequencies-unique/1647-minimum-deletions-to-make-character-frequencies-unique.cpp b/1647-minimum-deletions-to-make-character-frequencies-unique/1647-minimum-deletions-to-make-character-frequencies-unique.cpp new file mode 100644 index 00000000..32f451d3 --- /dev/null +++ b/1647-minimum-deletions-to-make-character-frequencies-unique/1647-minimum-deletions-to-make-character-frequencies-unique.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minDeletions(string s) { + + unordered_map mp; + + for(auto& itr : s) + ++mp[itr]; + + priority_queue pq; + + for(auto&itr : mp) + { + pq.push(itr.second); + } + + int counter = 0; + + while(pq.size() >= 2) + { + int a = pq.top(); pq.pop(); + int b = pq.top(); pq.pop(); + + if(a == b) + { + ++counter; + if(--a > 0) + pq.push(a); + pq.push(b); + } + else + pq.push(b); + } + + return counter; + } +}; \ No newline at end of file diff --git a/1647-minimum-deletions-to-make-character-frequencies-unique/NOTES.md b/1647-minimum-deletions-to-make-character-frequencies-unique/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1647-minimum-deletions-to-make-character-frequencies-unique/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1647-minimum-deletions-to-make-character-frequencies-unique/README.md b/1647-minimum-deletions-to-make-character-frequencies-unique/README.md new file mode 100644 index 00000000..3cf42be1 --- /dev/null +++ b/1647-minimum-deletions-to-make-character-frequencies-unique/README.md @@ -0,0 +1,37 @@ +

1647. Minimum Deletions to Make Character Frequencies Unique

Medium


A string s is called good if there are no two different characters in s that have the same frequency.

+ +

Given a string s, return the minimum number of characters you need to delete to make s good.

+ +

The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.

+ +

 

+

Example 1:

+ +
Input: s = "aab"
+Output: 0
+Explanation: s is already good.
+
+ +

Example 2:

+ +
Input: s = "aaabbbcc"
+Output: 2
+Explanation: You can delete two 'b's resulting in the good string "aaabcc".
+Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
+ +

Example 3:

+ +
Input: s = "ceabaacb"
+Output: 2
+Explanation: You can delete both 'c's resulting in the good string "eabaab".
+Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s contains only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1653-minimum-deletions-to-make-string-balanced/README.md b/1653-minimum-deletions-to-make-string-balanced/README.md new file mode 100644 index 00000000..8dc82bd2 --- /dev/null +++ b/1653-minimum-deletions-to-make-string-balanced/README.md @@ -0,0 +1,31 @@ +

1653. Minimum Deletions to Make String Balanced

Medium


You are given a string s consisting only of characters 'a' and 'b'​​​​.

+ +

You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.

+ +

Return the minimum number of deletions needed to make s balanced.

+ +

 

+

Example 1:

+ +
Input: s = "aababbab"
+Output: 2
+Explanation: You can either:
+Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
+Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
+
+ +

Example 2:

+ +
Input: s = "bbaaaaabb"
+Output: 2
+Explanation: The only solution is to delete the first two characters.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is 'a' or 'b'​​.
  • +
+
\ No newline at end of file diff --git a/1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.cpp b/1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.cpp new file mode 100644 index 00000000..d70b0dcd --- /dev/null +++ b/1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool closeStrings(string word1, string word2) { + vectorw1(26,0),w2(26,0); + sets1,s2; + for(char c:word1){ + w1[c-'a']++; + s1.insert(c); + } + for(char c:word2){ + w2[c-'a']++; + s2.insert(c); + } + sort(begin(w1),end(w1)); + sort(begin(w2),end(w2)); + return w1==w2&&s1==s2; + } +}; \ No newline at end of file diff --git a/1657-determine-if-two-strings-are-close/NOTES.md b/1657-determine-if-two-strings-are-close/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1657-determine-if-two-strings-are-close/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1657-determine-if-two-strings-are-close/README.md b/1657-determine-if-two-strings-are-close/README.md new file mode 100644 index 00000000..eeaa6e03 --- /dev/null +++ b/1657-determine-if-two-strings-are-close/README.md @@ -0,0 +1,55 @@ +

1657. Determine if Two Strings Are Close

Medium


Two strings are considered close if you can attain one from the other using the following operations:

+ +
    +
  • Operation 1: Swap any two existing characters. + +
      +
    • For example, abcde -> aecdb
    • +
    +
  • +
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. +
      +
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
    • +
    +
  • +
+ +

You can use the operations on either string as many times as necessary.

+ +

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

+ +

 

+

Example 1:

+ +
Input: word1 = "abc", word2 = "bca"
+Output: true
+Explanation: You can attain word2 from word1 in 2 operations.
+Apply Operation 1: "abc" -> "acb"
+Apply Operation 1: "acb" -> "bca"
+
+ +

Example 2:

+ +
Input: word1 = "a", word2 = "aa"
+Output: false
+Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
+
+ +

Example 3:

+ +
Input: word1 = "cabbba", word2 = "abbccc"
+Output: true
+Explanation: You can attain word2 from word1 in 3 operations.
+Apply Operation 1: "cabbba" -> "caabbb"
+Apply Operation 2: "caabbb" -> "baaccc"
+Apply Operation 2: "baaccc" -> "abbccc"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word1.length, word2.length <= 105
  • +
  • word1 and word2 contain only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1669-merge-in-between-linked-lists/1669-merge-in-between-linked-lists.cpp b/1669-merge-in-between-linked-lists/1669-merge-in-between-linked-lists.cpp new file mode 100644 index 00000000..2da26e6b --- /dev/null +++ b/1669-merge-in-between-linked-lists/1669-merge-in-between-linked-lists.cpp @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { + + ListNode* temp = list1, *temp2 = list2, *prev = temp2; + + while(temp2) + { + prev = temp2; + temp2 = temp2->next; + } + + ListNode* half = nullptr, *nex = nullptr; + + int curr = 0; + + while(temp) + { + ++curr; + if(curr == a) + { + half = temp; + } + if(curr == b+2) + { + nex = temp; + } + temp = temp->next; + } + + half->next = list2; + prev->next = nex; + + return list1; + } +}; \ No newline at end of file diff --git a/1669-merge-in-between-linked-lists/README.md b/1669-merge-in-between-linked-lists/README.md new file mode 100644 index 00000000..80ce1897 --- /dev/null +++ b/1669-merge-in-between-linked-lists/README.md @@ -0,0 +1,32 @@ +

1669. Merge In Between Linked Lists

Medium


You are given two linked lists: list1 and list2 of sizes n and m respectively.

+ +

Remove list1's nodes from the ath node to the bth node, and put list2 in their place.

+ +

The blue edges and nodes in the following figure indicate the result:

+ +

Build the result list and return its head.

+ +

 

+

Example 1:

+ +
Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
+Output: [10,1,13,1000000,1000001,1000002,5]
+Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
+
+ +

Example 2:

+ +
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
+Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
+Explanation: The blue edges and nodes in the above figure indicate the result.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= list1.length <= 104
  • +
  • 1 <= a <= b < list1.length - 1
  • +
  • 1 <= list2.length <= 104
  • +
+
\ No newline at end of file diff --git a/1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp b/1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp new file mode 100644 index 00000000..27dc6415 --- /dev/null +++ b/1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minimumDeviation(vector& nums) { + + set s; + + for(auto itr : nums) + { + if(itr & 1) + s.insert(itr*2); + else + s.insert(itr); + } + + int diff = *s.rbegin() - *s.begin(); + + while(*s.rbegin() % 2 == 0) + { + int top = *s.rbegin(); + s.erase(top); + + s.insert(top/2); + + diff = min(diff, *s.rbegin() - *s.begin()); + } + + + return diff; + + } +}; \ No newline at end of file diff --git a/1675-minimize-deviation-in-array/NOTES.md b/1675-minimize-deviation-in-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1675-minimize-deviation-in-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1675-minimize-deviation-in-array/README.md b/1675-minimize-deviation-in-array/README.md new file mode 100644 index 00000000..5d41d8fe --- /dev/null +++ b/1675-minimize-deviation-in-array/README.md @@ -0,0 +1,52 @@ +

1675. Minimize Deviation in Array

Hard


You are given an array nums of n positive integers.

+ +

You can perform two types of operations on any element of the array any number of times:

+ +
    +
  • If the element is even, divide it by 2. + +
      +
    • For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
    • +
    +
  • +
  • If the element is odd, multiply it by 2. +
      +
    • For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
    • +
    +
  • +
+ +

The deviation of the array is the maximum difference between any two elements in the array.

+ +

Return the minimum deviation the array can have after performing some number of operations.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: 1
+Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
+
+ +

Example 2:

+ +
Input: nums = [4,1,5,20,3]
+Output: 3
+Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
+
+ +

Example 3:

+ +
Input: nums = [2,10,8]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 2 <= n <= 5 * 104
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/1683-invalid-tweets/1683-invalid-tweets.sql b/1683-invalid-tweets/1683-invalid-tweets.sql new file mode 100644 index 00000000..122290c0 --- /dev/null +++ b/1683-invalid-tweets/1683-invalid-tweets.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below + +select tweet_id from Tweets +where char_length(content) > 15; + diff --git a/1683-invalid-tweets/NOTES.md b/1683-invalid-tweets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1683-invalid-tweets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1683-invalid-tweets/README.md b/1683-invalid-tweets/README.md new file mode 100644 index 00000000..ffab3320 --- /dev/null +++ b/1683-invalid-tweets/README.md @@ -0,0 +1,42 @@ +

1683. Invalid Tweets

Easy


Table: Tweets

+ +
+----------------+---------+
+| Column Name    | Type    |
++----------------+---------+
+| tweet_id       | int     |
+| content        | varchar |
++----------------+---------+
+tweet_id is the primary key (column with unique values) for this table.
+This table contains all the tweets in a social media app.
+
+ +

 

+ +

Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.

+ +

Return the result table in any order.

+ +

The result format is in the following example.

+ +

 

+

Example 1:

+ +
Input: 
+Tweets table:
++----------+----------------------------------+
+| tweet_id | content                          |
++----------+----------------------------------+
+| 1        | Vote for Biden                   |
+| 2        | Let us make America great again! |
++----------+----------------------------------+
+Output: 
++----------+
+| tweet_id |
++----------+
+| 2        |
++----------+
+Explanation: 
+Tweet 1 has length = 14. It is a valid tweet.
+Tweet 2 has length = 32. It is an invalid tweet.
+
+
\ No newline at end of file diff --git a/1685-sum-of-absolute-differences-in-a-sorted-array/1685-sum-of-absolute-differences-in-a-sorted-array.cpp b/1685-sum-of-absolute-differences-in-a-sorted-array/1685-sum-of-absolute-differences-in-a-sorted-array.cpp new file mode 100644 index 00000000..e25a2d5b --- /dev/null +++ b/1685-sum-of-absolute-differences-in-a-sorted-array/1685-sum-of-absolute-differences-in-a-sorted-array.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector getSumAbsoluteDifferences(vector& nums) { + + int n = nums.size(); + + vector pref(n+1,0); + + for(int i = 1; i <= n; ++i) + pref[i] = pref[i-1] + nums[i-1]; + + vector ans; + + for(int i = 1; i <= n; ++i) + { + long long leftSum = nums[i-1] * 1LL * i; + long long left = leftSum - pref[i]; + + long long rightSum = nums[i-1] * 1LL * (n-i); + long long right = pref[n] - pref[i] - rightSum; + + ans.push_back(left + right); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md b/1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1685-sum-of-absolute-differences-in-a-sorted-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1697-checking-existence-of-edge-length-limited-paths/1697-checking-existence-of-edge-length-limited-paths.cpp b/1697-checking-existence-of-edge-length-limited-paths/1697-checking-existence-of-edge-length-limited-paths.cpp new file mode 100644 index 00000000..d9c04026 --- /dev/null +++ b/1697-checking-existence-of-edge-length-limited-paths/1697-checking-existence-of-edge-length-limited-paths.cpp @@ -0,0 +1,51 @@ +class DSU { + public: + vector Parent, Rank; + DSU(int n) { + Parent.resize(n); + Rank.resize(n, 0); + for (int i = 0; i < n; i++) Parent[i] = i; + } + int Find(int x) { + return Parent[x] = Parent[x] == x ? x : Find(Parent[x]); + } + bool Union(int x, int y) { + int xset = Find(x), yset = Find(y); + if (xset != yset) { + Rank[xset] < Rank[yset] ? Parent[xset] = yset : Parent[yset] = xset; + Rank[xset] += Rank[xset] == Rank[yset]; + return true; + } + return false; + } +}; + +class Solution { +public: + vector distanceLimitedPathsExist(int n, vector>& edgeList, vector>& queries) { + DSU dsu(n); + for(int i=0;i res(queries.size(), false); + for(auto q: queries){ + while(i1697. Checking Existence of Edge Length Limited Paths

Hard


An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes.

+ +

Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj .

+ +

Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.

+ +

 

+

Example 1:

+ +
Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]
+Output: [false,true]
+Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
+For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
+For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
+
+ +

Example 2:

+ +
Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]
+Output: [true,false]
+Exaplanation: The above figure shows the given graph.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 105
  • +
  • 1 <= edgeList.length, queries.length <= 105
  • +
  • edgeList[i].length == 3
  • +
  • queries[j].length == 3
  • +
  • 0 <= ui, vi, pj, qj <= n - 1
  • +
  • ui != vi
  • +
  • pj != qj
  • +
  • 1 <= disi, limitj <= 109
  • +
  • There may be multiple edges between two nodes.
  • +
+
\ No newline at end of file diff --git a/1700-number-of-students-unable-to-eat-lunch/1700-number-of-students-unable-to-eat-lunch.cpp b/1700-number-of-students-unable-to-eat-lunch/1700-number-of-students-unable-to-eat-lunch.cpp new file mode 100644 index 00000000..07c848a7 --- /dev/null +++ b/1700-number-of-students-unable-to-eat-lunch/1700-number-of-students-unable-to-eat-lunch.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countStudents(vector& students, vector& sandwiches) { + + int n = students.size(); + + vector freq(2, 0); + + for(auto& ele : students) + ++freq[ele]; + + int cnt = 0; + + for(auto& ele : sandwiches) + { + if(freq[ele] > 0) + { + ++cnt; + --freq[ele]; + } + else + break; + } + + return n - cnt; + + } +}; \ No newline at end of file diff --git a/1700-number-of-students-unable-to-eat-lunch/NOTES.md b/1700-number-of-students-unable-to-eat-lunch/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1700-number-of-students-unable-to-eat-lunch/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1700-number-of-students-unable-to-eat-lunch/README.md b/1700-number-of-students-unable-to-eat-lunch/README.md new file mode 100644 index 00000000..6d562160 --- /dev/null +++ b/1700-number-of-students-unable-to-eat-lunch/README.md @@ -0,0 +1,46 @@ +

1700. Number of Students Unable to Eat Lunch

Easy


The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.

+ +

The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:

+ +
    +
  • If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.
  • +
  • Otherwise, they will leave it and go to the queue's end.
  • +
+ +

This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

+ +

You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.

+ +

 

+

Example 1:

+ +
Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
+Output: 0 
+Explanation:
+- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
+- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
+- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
+- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
+- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
+- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
+- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
+- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
+Hence all students are able to eat.
+
+ +

Example 2:

+ +
Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= students.length, sandwiches.length <= 100
  • +
  • students.length == sandwiches.length
  • +
  • sandwiches[i] is 0 or 1.
  • +
  • students[i] is 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1704-determine-if-string-halves-are-alike/1704-determine-if-string-halves-are-alike.cpp b/1704-determine-if-string-halves-are-alike/1704-determine-if-string-halves-are-alike.cpp new file mode 100644 index 00000000..adb1de1d --- /dev/null +++ b/1704-determine-if-string-halves-are-alike/1704-determine-if-string-halves-are-alike.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool halvesAreAlike(string s) { + + vector vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + int one = 0 ,two = 0; + + int n = s.size(); + + for(int i = 0; i1704. Determine if String Halves Are Alike

Easy


You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

+ +

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

+ +

Return true if a and b are alike. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: s = "book"
+Output: true
+Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
+
+ +

Example 2:

+ +
Input: s = "textbook"
+Output: false
+Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
+Notice that the vowel o is counted twice.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 1000
  • +
  • s.length is even.
  • +
  • s consists of uppercase and lowercase letters.
  • +
+
\ No newline at end of file diff --git a/1707-maximum-xor-with-an-element-from-array/1707-maximum-xor-with-an-element-from-array.cpp b/1707-maximum-xor-with-an-element-from-array/1707-maximum-xor-with-an-element-from-array.cpp new file mode 100644 index 00000000..e7465886 --- /dev/null +++ b/1707-maximum-xor-with-an-element-from-array/1707-maximum-xor-with-an-element-from-array.cpp @@ -0,0 +1,110 @@ +class Node{ + public: + Node *child[2] = {nullptr}; + + bool containsKey(int bit) + { + return (child[bit] != nullptr); + } + + Node *get(int bit) + { + return child[bit]; + } + + void put(int bit , Node* node) + { + child[bit] = node; + } +}; + +class Trie{ + + private: + Node *root; + public: + Trie(){ + root = new Node(); + } + public: + void insert(int num) + { + Node*temp = root; + + for(int i = 31; i>=0; --i) + { + int bit = (num >> i) & 1; + if(!temp->containsKey(bit)) + { + temp->put(bit,new Node()); + } + temp = temp->get(bit); + } + } + public: + int getMax(int num){ + Node* temp = root; + int maxNum = 0; + for(int i = 31; i>=0; --i) + { + int bit = (num >> i) & 1; + if(temp->containsKey(1-bit)) // opposite + { + maxNum = maxNum | (1 << i); + temp = temp->get(1-bit); + } + else{ + temp = temp->get(bit); + } + } + + return maxNum; + } +}; + + +class Solution { +public: + vector maximizeXor(vector& nums, vector>& queries) { + + vector>> vec; + int n = queries.size(); + + for(int i = 0; i ans(n); + + for(int i = 0; i < n; ++i) + { + int mi = vec[i].first; + int xi = vec[i].second.first; + int idx = vec[i].second.second; + + for(int i = k; i < m; ++i) + { + if(nums[k] <= mi) + obj->insert(nums[k++]); + else + break; + } + + if(k == 0) + ans[idx] = -1; + else + ans[idx] = obj->getMax(xi); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1707-maximum-xor-with-an-element-from-array/README.md b/1707-maximum-xor-with-an-element-from-array/README.md new file mode 100644 index 00000000..5ba8d119 --- /dev/null +++ b/1707-maximum-xor-with-an-element-from-array/README.md @@ -0,0 +1,32 @@ +

1707. Maximum XOR With an Element From Array

Hard


You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

+ +

The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.

+ +

Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

+ +

 

+

Example 1:

+ +
Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
+Output: [3,3,7]
+Explanation:
+1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
+2) 1 XOR 2 = 3.
+3) 5 XOR 2 = 7.
+
+ +

Example 2:

+ +
Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
+Output: [15,-1,5]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length, queries.length <= 105
  • +
  • queries[i].length == 2
  • +
  • 0 <= nums[j], xi, mi <= 109
  • +
+
\ No newline at end of file diff --git a/1716-calculate-money-in-leetcode-bank/1716-calculate-money-in-leetcode-bank.cpp b/1716-calculate-money-in-leetcode-bank/1716-calculate-money-in-leetcode-bank.cpp new file mode 100644 index 00000000..1bba9dac --- /dev/null +++ b/1716-calculate-money-in-leetcode-bank/1716-calculate-money-in-leetcode-bank.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int totalMoney(int n) { + + int totMoney = 0; + int track = 1, day = 0, curr = 1; + + + for(int i = 1; i<=n; ++i) + { + totMoney += curr; + ++curr; + ++day; + + if(day == 7) + { + curr = track+1; + ++track; + day = 0; + } + } + + return totMoney; + } +}; \ No newline at end of file diff --git a/1716-calculate-money-in-leetcode-bank/NOTES.md b/1716-calculate-money-in-leetcode-bank/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1716-calculate-money-in-leetcode-bank/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1716-calculate-money-in-leetcode-bank/README.md b/1716-calculate-money-in-leetcode-bank/README.md new file mode 100644 index 00000000..3ebe921b --- /dev/null +++ b/1716-calculate-money-in-leetcode-bank/README.md @@ -0,0 +1,35 @@ +

1716. Calculate Money in Leetcode Bank

Easy


Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.

+ +

He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.

+ +

Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.

+ +

 

+

Example 1:

+ +
Input: n = 4
+Output: 10
+Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
+
+ +

Example 2:

+ +
Input: n = 10
+Output: 37
+Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
+
+ +

Example 3:

+ +
Input: n = 20
+Output: 96
+Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/1721-swapping-nodes-in-a-linked-list/NOTES.md b/1721-swapping-nodes-in-a-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1721-swapping-nodes-in-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1721-swapping-nodes-in-a-linked-list/README.md b/1721-swapping-nodes-in-a-linked-list/README.md new file mode 100644 index 00000000..2d781629 --- /dev/null +++ b/1721-swapping-nodes-in-a-linked-list/README.md @@ -0,0 +1,26 @@ +

1721. Swapping Nodes in a Linked List

Medium


You are given the head of a linked list, and an integer k.

+ +

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [1,4,3,2,5]
+
+ +

Example 2:

+ +
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
+Output: [7,9,6,6,8,7,3,0,9,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= k <= n <= 105
  • +
  • 0 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/1727-largest-submatrix-with-rearrangements/1727-largest-submatrix-with-rearrangements.cpp b/1727-largest-submatrix-with-rearrangements/1727-largest-submatrix-with-rearrangements.cpp new file mode 100644 index 00000000..3eed51f2 --- /dev/null +++ b/1727-largest-submatrix-with-rearrangements/1727-largest-submatrix-with-rearrangements.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int largestSubmatrix(vector>& matrix) { + + int i, j, ans = 0, n = matrix.size(), m = matrix[0].size(); + + for(i = 0; i < m; i++) + { + for(j = 1; j < n; j++) + { + if(matrix[j][i] == 1) + matrix[j][i] = matrix[j-1][i] + matrix[j][i]; + else + matrix[j][i] = 0; + } + } + + for(i = 0; i < n; i++) + { + sort(matrix[i].begin(), matrix[i].end(), greater()); + + for(j = 0; j < m; j++) + ans = max(ans, matrix[i][j] * (j + 1)); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1727-largest-submatrix-with-rearrangements/NOTES.md b/1727-largest-submatrix-with-rearrangements/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1727-largest-submatrix-with-rearrangements/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1727-largest-submatrix-with-rearrangements/README.md b/1727-largest-submatrix-with-rearrangements/README.md new file mode 100644 index 00000000..e30720f4 --- /dev/null +++ b/1727-largest-submatrix-with-rearrangements/README.md @@ -0,0 +1,38 @@ +

1727. Largest Submatrix With Rearrangements

Medium


You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.

+ +

Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.

+ +

 

+

Example 1:

+ +
Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]
+Output: 4
+Explanation: You can rearrange the columns as shown above.
+The largest submatrix of 1s, in bold, has an area of 4.
+
+ +

Example 2:

+ +
Input: matrix = [[1,0,1,0,1]]
+Output: 3
+Explanation: You can rearrange the columns as shown above.
+The largest submatrix of 1s, in bold, has an area of 3.
+
+ +

Example 3:

+ +
Input: matrix = [[1,1,0],[1,0,1]]
+Output: 2
+Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m * n <= 105
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1732-find-the-highest-altitude/1732-find-the-highest-altitude.cpp b/1732-find-the-highest-altitude/1732-find-the-highest-altitude.cpp new file mode 100644 index 00000000..fbdc0a29 --- /dev/null +++ b/1732-find-the-highest-altitude/1732-find-the-highest-altitude.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int largestAltitude(vector& gain) { + + int sum = 0, ans = 0; + + for(auto itr : gain) + { + sum += itr; + ans = max(ans, sum); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1732-find-the-highest-altitude/NOTES.md b/1732-find-the-highest-altitude/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1732-find-the-highest-altitude/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1732-find-the-highest-altitude/README.md b/1732-find-the-highest-altitude/README.md new file mode 100644 index 00000000..663a3de3 --- /dev/null +++ b/1732-find-the-highest-altitude/README.md @@ -0,0 +1,28 @@ +

1732. Find the Highest Altitude

Easy


There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.

+ +

You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point.

+ +

 

+

Example 1:

+ +
Input: gain = [-5,1,5,0,-7]
+Output: 1
+Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
+
+ +

Example 2:

+ +
Input: gain = [-4,-3,-2,-1,4,3,2]
+Output: 0
+Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • n == gain.length
  • +
  • 1 <= n <= 100
  • +
  • -100 <= gain[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1743-restore-the-array-from-adjacent-pairs/1743-restore-the-array-from-adjacent-pairs.cpp b/1743-restore-the-array-from-adjacent-pairs/1743-restore-the-array-from-adjacent-pairs.cpp new file mode 100644 index 00000000..483ec42c --- /dev/null +++ b/1743-restore-the-array-from-adjacent-pairs/1743-restore-the-array-from-adjacent-pairs.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + + unordered_map> adj; + unordered_map mp; + + int sv = -1; + + for(auto& itr : adjacentPairs) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + + ++mp[itr[0]]; + ++mp[itr[1]]; + } + + for(auto& [f, s] : mp) + { + if(s == 1) + sv = f; + } + + vector ans; + + unordered_set visited; + + function dfs = [&](int sv) + { + ans.push_back(sv); + visited.insert(sv); + + for(auto& itr : adj[sv]) + { + if(!visited.count(itr)) + dfs(itr); + } + }; + + // cout<1743. Restore the Array From Adjacent Pairs

Medium


There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.

+ +

You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.

+ +

It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.

+ +

Return the original array nums. If there are multiple solutions, return any of them.

+ +

 

+

Example 1:

+ +
Input: adjacentPairs = [[2,1],[3,4],[3,2]]
+Output: [1,2,3,4]
+Explanation: This array has all its adjacent pairs in adjacentPairs.
+Notice that adjacentPairs[i] may not be in left-to-right order.
+
+ +

Example 2:

+ +
Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
+Output: [-2,4,1,-3]
+Explanation: There can be negative numbers.
+Another solution is [-3,1,4,-2], which would also be accepted.
+
+ +

Example 3:

+ +
Input: adjacentPairs = [[100000,-100000]]
+Output: [100000,-100000]
+
+ +

 

+

Constraints:

+ +
    +
  • nums.length == n
  • +
  • adjacentPairs.length == n - 1
  • +
  • adjacentPairs[i].length == 2
  • +
  • 2 <= n <= 105
  • +
  • -105 <= nums[i], ui, vi <= 105
  • +
  • There exists some nums that has adjacentPairs as its pairs.
  • +
+
\ No newline at end of file diff --git a/1750-minimum-length-of-string-after-deleting-similar-ends/1750-minimum-length-of-string-after-deleting-similar-ends.cpp b/1750-minimum-length-of-string-after-deleting-similar-ends/1750-minimum-length-of-string-after-deleting-similar-ends.cpp new file mode 100644 index 00000000..b5a5ce2c --- /dev/null +++ b/1750-minimum-length-of-string-after-deleting-similar-ends/1750-minimum-length-of-string-after-deleting-similar-ends.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int minimumLength(string s) { + + int n = s.size(); + int i = 0, j = n-1; + + while(i < j) + { + char pref = s[i]; + char suff = s[j]; + + if(s[i] != s[j]) + break; + + while(j >= 0 and s[j] == pref) + --j; + while(i < j and s[i] == suff) + ++i; + } + + int ans = j - i + 1; + + return max(ans, 0); + } +}; \ No newline at end of file diff --git a/1750-minimum-length-of-string-after-deleting-similar-ends/README.md b/1750-minimum-length-of-string-after-deleting-similar-ends/README.md new file mode 100644 index 00000000..c64aa797 --- /dev/null +++ b/1750-minimum-length-of-string-after-deleting-similar-ends/README.md @@ -0,0 +1,47 @@ +

1750. Minimum Length of String After Deleting Similar Ends

Medium


Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:

+ +
    +
  1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
  2. +
  3. Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
  4. +
  5. The prefix and the suffix should not intersect at any index.
  6. +
  7. The characters from the prefix and suffix must be the same.
  8. +
  9. Delete both the prefix and the suffix.
  10. +
+ +

Return the minimum length of s after performing the above operation any number of times (possibly zero times).

+ +

 

+

Example 1:

+ +
Input: s = "ca"
+Output: 2
+Explanation: You can't remove any characters, so the string stays as is.
+
+ +

Example 2:

+ +
Input: s = "cabaabac"
+Output: 0
+Explanation: An optimal sequence of operations is:
+- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
+- Take prefix = "a" and suffix = "a" and remove them, s = "baab".
+- Take prefix = "b" and suffix = "b" and remove them, s = "aa".
+- Take prefix = "a" and suffix = "a" and remove them, s = "".
+ +

Example 3:

+ +
Input: s = "aabccabba"
+Output: 3
+Explanation: An optimal sequence of operations is:
+- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
+- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s only consists of characters 'a', 'b', and 'c'.
  • +
+
\ No newline at end of file diff --git a/1751-maximum-number-of-events-that-can-be-attended-ii/1751-maximum-number-of-events-that-can-be-attended-ii.cpp b/1751-maximum-number-of-events-that-can-be-attended-ii/1751-maximum-number-of-events-that-can-be-attended-ii.cpp new file mode 100644 index 00000000..24a3725e --- /dev/null +++ b/1751-maximum-number-of-events-that-can-be-attended-ii/1751-maximum-number-of-events-that-can-be-attended-ii.cpp @@ -0,0 +1,42 @@ +class Solution { + +private: + int helper(int idx, int k, int n, vector>& events, vector>& dp) + { + if(idx >= n) + return 0; + + if(dp[idx][k] != -1) + return dp[idx][k]; + + int ans = helper(idx+1, k , n, events, dp); + + if(k) + { + int pos = n; + for(int i = idx+1; i < n; ++i) + { + if(events[i][0] > events[idx][1]) + { + pos = i; + break; + } + } + ans = max(ans , events[idx][2] + helper(pos, k-1, n, events, dp)); + } + + return dp[idx][k] = ans; + } +public: + int maxValue(vector>& events, int k) { + + int n = events.size(); + + sort(events.begin(), events.end()); + + vector> dp(n+1, vector(k+1,-1)); + + return helper(0, k, n, events, dp); + } +}; + \ No newline at end of file diff --git a/1751-maximum-number-of-events-that-can-be-attended-ii/README.md b/1751-maximum-number-of-events-that-can-be-attended-ii/README.md new file mode 100644 index 00000000..58dd30a9 --- /dev/null +++ b/1751-maximum-number-of-events-that-can-be-attended-ii/README.md @@ -0,0 +1,42 @@ +

1751. Maximum Number of Events That Can Be Attended II

Hard


You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.

+ +

You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.

+ +

Return the maximum sum of values that you can receive by attending events.

+ +

 

+

Example 1:

+ +

+ +
Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
+Output: 7
+Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
+ +

Example 2:

+ +

+ +
Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
+Output: 10
+Explanation: Choose event 2 for a total value of 10.
+Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.
+ +

Example 3:

+ +

+ +
Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
+Output: 9
+Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= events.length
  • +
  • 1 <= k * events.length <= 106
  • +
  • 1 <= startDayi <= endDayi <= 109
  • +
  • 1 <= valuei <= 106
  • +
+
\ No newline at end of file diff --git a/1757-recyclable-and-low-fat-products/1757-recyclable-and-low-fat-products.sql b/1757-recyclable-and-low-fat-products/1757-recyclable-and-low-fat-products.sql new file mode 100644 index 00000000..68d567d4 --- /dev/null +++ b/1757-recyclable-and-low-fat-products/1757-recyclable-and-low-fat-products.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below + +select product_id from Products where low_fats = 'Y' and recyclable = 'Y'; diff --git a/1757-recyclable-and-low-fat-products/NOTES.md b/1757-recyclable-and-low-fat-products/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1757-recyclable-and-low-fat-products/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1758-minimum-changes-to-make-alternating-binary-string/1758-minimum-changes-to-make-alternating-binary-string.cpp b/1758-minimum-changes-to-make-alternating-binary-string/1758-minimum-changes-to-make-alternating-binary-string.cpp new file mode 100644 index 00000000..636a953e --- /dev/null +++ b/1758-minimum-changes-to-make-alternating-binary-string/1758-minimum-changes-to-make-alternating-binary-string.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int minOperations(string s) { + + string startZero, startOne; + + int n = s.size(), cnt1 = 0, cnt2 = 0; + + for(int i = 0; i < n; ++i) + { + if(i%2 == 0) + startZero += '0'; + else + startZero += '1'; + + if(i%2 == 0) + startOne += '1'; + else + startOne += '0'; + + if(startZero.back() != s[i]) + ++cnt1; + if(startOne.back() != s[i]) + ++cnt2; + } + + return min(cnt1, cnt2); + + } +}; \ No newline at end of file diff --git a/1758-minimum-changes-to-make-alternating-binary-string/NOTES.md b/1758-minimum-changes-to-make-alternating-binary-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1758-minimum-changes-to-make-alternating-binary-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1758-minimum-changes-to-make-alternating-binary-string/README.md b/1758-minimum-changes-to-make-alternating-binary-string/README.md new file mode 100644 index 00000000..960678e9 --- /dev/null +++ b/1758-minimum-changes-to-make-alternating-binary-string/README.md @@ -0,0 +1,36 @@ +

1758. Minimum Changes To Make Alternating Binary String

Easy


You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

+ +

The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.

+ +

Return the minimum number of operations needed to make s alternating.

+ +

 

+

Example 1:

+ +
Input: s = "0100"
+Output: 1
+Explanation: If you change the last character to '1', s will be "0101", which is alternating.
+
+ +

Example 2:

+ +
Input: s = "10"
+Output: 0
+Explanation: s is already alternating.
+
+ +

Example 3:

+ +
Input: s = "1111"
+Output: 2
+Explanation: You need two operations to reach "0101" or "1010".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s[i] is either '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/1759-count-number-of-homogenous-substrings/1759-count-number-of-homogenous-substrings.cpp b/1759-count-number-of-homogenous-substrings/1759-count-number-of-homogenous-substrings.cpp new file mode 100644 index 00000000..02b8bc5c --- /dev/null +++ b/1759-count-number-of-homogenous-substrings/1759-count-number-of-homogenous-substrings.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int countHomogenous(string s) { + + int n = s.size(), cnt = 0, prev = 0, res = 0; + + const int mod = 1e9 + 7; + + for(auto& itr : s) + { + cnt = (itr == prev ? cnt+1 : 1); + + prev = itr; + + res = (res + cnt) % mod; + } + + return res; + + } +}; \ No newline at end of file diff --git a/1759-count-number-of-homogenous-substrings/NOTES.md b/1759-count-number-of-homogenous-substrings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1759-count-number-of-homogenous-substrings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1759-count-number-of-homogenous-substrings/README.md b/1759-count-number-of-homogenous-substrings/README.md new file mode 100644 index 00000000..2e82ed3b --- /dev/null +++ b/1759-count-number-of-homogenous-substrings/README.md @@ -0,0 +1,40 @@ +

1759. Count Number of Homogenous Substrings

Medium


Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.

+ +

A string is homogenous if all the characters of the string are the same.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "abbcccaa"
+Output: 13
+Explanation: The homogenous substrings are listed as below:
+"a"   appears 3 times.
+"aa"  appears 1 time.
+"b"   appears 2 times.
+"bb"  appears 1 time.
+"c"   appears 3 times.
+"cc"  appears 2 times.
+"ccc" appears 1 time.
+3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
+ +

Example 2:

+ +
Input: s = "xy"
+Output: 2
+Explanation: The homogenous substrings are "x" and "y".
+ +

Example 3:

+ +
Input: s = "zzzzz"
+Output: 15
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase letters.
  • +
\ No newline at end of file diff --git a/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp b/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp new file mode 100644 index 00000000..6789bc84 --- /dev/null +++ b/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string mergeAlternately(string word1, string word2) { + + int n = word1.size(), m = word2.size(); + + int i = 0, j = 0; + + string ans = ""; + + while(i < n and j < m) + { + ans += word1[i++]; + ans += word2[j++]; + } + + while(i < n) + ans += word1[i++]; + + while(j < m) + ans += word2[j++]; + + return ans; + + } +}; \ No newline at end of file diff --git a/1768-merge-strings-alternately/NOTES.md b/1768-merge-strings-alternately/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1768-merge-strings-alternately/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1770-maximum-score-from-performing-multiplication-operations/1770-maximum-score-from-performing-multiplication-operations.cpp b/1770-maximum-score-from-performing-multiplication-operations/1770-maximum-score-from-performing-multiplication-operations.cpp new file mode 100644 index 00000000..695cc6a0 --- /dev/null +++ b/1770-maximum-score-from-performing-multiplication-operations/1770-maximum-score-from-performing-multiplication-operations.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + + int helper(int index,vector& nums, vector& multipliers, int start, int end, vector>& dp) + { + if(index == multipliers.size()) + return 0; + if(dp[index][start] != INT_MIN) + return dp[index][start]; + + return dp[index][start] = max(nums[start] * multipliers[index] + helper(index + 1, nums, multipliers,start+1,end, dp ), nums[end] * multipliers[index] + helper(index + 1,nums,multipliers,start,end-1, dp)); + } + + int maximumScore(vector& nums, vector& multipliers) { + int n = nums.size(); + int m = multipliers.size(); + vector> dp(n+1,vector(m+1,INT_MIN)); + return helper(0,nums,multipliers,0,n-1, dp); + } +}; \ No newline at end of file diff --git a/1770-maximum-score-from-performing-multiplication-operations/README.md b/1770-maximum-score-from-performing-multiplication-operations/README.md new file mode 100644 index 00000000..6a9e22d5 --- /dev/null +++ b/1770-maximum-score-from-performing-multiplication-operations/README.md @@ -0,0 +1,51 @@ +

1770. Maximum Score from Performing Multiplication Operations

Hard


You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.

+ +

You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:

+ +
    +
  • Choose one integer x from either the start or the end of the array nums.
  • +
  • Add multipliers[i] * x to your score. +
      +
    • Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on.
    • +
    +
  • +
  • Remove x from nums.
  • +
+ +

Return the maximum score after performing m operations.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3], multipliers = [3,2,1]
+Output: 14
+Explanation: An optimal solution is as follows:
+- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
+- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
+- Choose from the end, [1], adding 1 * 1 = 1 to the score.
+The total score is 9 + 4 + 1 = 14.
+ +

Example 2:

+ +
Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
+Output: 102
+Explanation: An optimal solution is as follows:
+- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
+- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
+- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
+- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
+- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. 
+The total score is 50 + 15 - 9 + 4 + 42 = 102.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • m == multipliers.length
  • +
  • 1 <= m <= 300
  • +
  • m <= n <= 105
  • +
  • -1000 <= nums[i], multipliers[i] <= 1000
  • +
+
\ No newline at end of file diff --git a/1791-find-center-of-star-graph/1791-find-center-of-star-graph.cpp b/1791-find-center-of-star-graph/1791-find-center-of-star-graph.cpp new file mode 100644 index 00000000..fd3ab8d2 --- /dev/null +++ b/1791-find-center-of-star-graph/1791-find-center-of-star-graph.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int findCenter(vector>& edges) { + + if(edges[0][0]==edges[1][0] || edges[0][0]==edges[1][1]) + return edges[0][0]; + + else return edges[0][1]; + + } +}; \ No newline at end of file diff --git a/1791-find-center-of-star-graph/README.md b/1791-find-center-of-star-graph/README.md new file mode 100644 index 00000000..fc958c58 --- /dev/null +++ b/1791-find-center-of-star-graph/README.md @@ -0,0 +1,30 @@ +

1791. Find Center of Star Graph

Easy


There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.

+ +

You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.

+ +

 

+

Example 1:

+ +
Input: edges = [[1,2],[2,3],[4,2]]
+Output: 2
+Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
+
+ +

Example 2:

+ +
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n <= 105
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 1 <= ui, vi <= n
  • +
  • ui != vi
  • +
  • The given edges represent a valid star graph.
  • +
+
\ No newline at end of file diff --git a/1793-maximum-score-of-a-good-subarray/1793-maximum-score-of-a-good-subarray.cpp b/1793-maximum-score-of-a-good-subarray/1793-maximum-score-of-a-good-subarray.cpp new file mode 100644 index 00000000..1e22038a --- /dev/null +++ b/1793-maximum-score-of-a-good-subarray/1793-maximum-score-of-a-good-subarray.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maximumScore(vector& nums, int k) { + + int n = nums.size(); + + int i = k, j = k; + + int ans = nums[k], currMin = nums[k]; + + while(i > 0 or j < n-1) + { + int left = (i > 0 ? nums[i-1] : 0); + int right = (j < n-1 ? nums[j+1] : 0); + + if(left > right) + { + --i; + currMin = min(currMin, nums[i]); + } + else + { + ++j; + currMin = min(currMin,nums[j]); + } + + ans = max(ans, currMin * (j-i+1)); + } + + return ans; + } +}; \ No newline at end of file diff --git a/1793-maximum-score-of-a-good-subarray/NOTES.md b/1793-maximum-score-of-a-good-subarray/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1793-maximum-score-of-a-good-subarray/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1793-maximum-score-of-a-good-subarray/README.md b/1793-maximum-score-of-a-good-subarray/README.md new file mode 100644 index 00000000..d32c4f68 --- /dev/null +++ b/1793-maximum-score-of-a-good-subarray/README.md @@ -0,0 +1,30 @@ +

1793. Maximum Score of a Good Subarray

Hard


You are given an array of integers nums (0-indexed) and an integer k.

+ +

The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.

+ +

Return the maximum possible score of a good subarray.

+ +

 

+

Example 1:

+ +
Input: nums = [1,4,3,7,4,5], k = 3
+Output: 15
+Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. 
+
+ +

Example 2:

+ +
Input: nums = [5,5,4,5,4,1,1,1], k = 0
+Output: 20
+Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 2 * 104
  • +
  • 0 <= k < nums.length
  • +
+
\ No newline at end of file diff --git a/1797-design-authentication-manager/1797-design-authentication-manager.cpp b/1797-design-authentication-manager/1797-design-authentication-manager.cpp new file mode 100644 index 00000000..0bb54bef --- /dev/null +++ b/1797-design-authentication-manager/1797-design-authentication-manager.cpp @@ -0,0 +1,43 @@ +class AuthenticationManager { +public: + + int timeToLive; + + map mp; + + AuthenticationManager(int timeToLive) { + this->timeToLive = timeToLive; + } + + void generate(string tokenId, int currentTime) { + mp[tokenId] = currentTime + timeToLive; + } + + void renew(string tokenId, int currentTime) { + + if(mp[tokenId] > currentTime) + mp[tokenId] = currentTime + timeToLive; + + } + + int countUnexpiredTokens(int currentTime) { + + int counter = 0; + + for(auto& itr: mp) + { + if(itr.second > currentTime) + ++counter; + } + + return counter; + } +}; + +/** + * Your AuthenticationManager object will be instantiated and called as such: + * AuthenticationManager* obj = new AuthenticationManager(timeToLive); + * obj->generate(tokenId,currentTime); + * obj->renew(tokenId,currentTime); + * int param_3 = obj->countUnexpiredTokens(currentTime); + */ \ No newline at end of file diff --git a/1797-design-authentication-manager/NOTES.md b/1797-design-authentication-manager/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1797-design-authentication-manager/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1797-design-authentication-manager/README.md b/1797-design-authentication-manager/README.md new file mode 100644 index 00000000..032431b0 --- /dev/null +++ b/1797-design-authentication-manager/README.md @@ -0,0 +1,46 @@ +

1797. Design Authentication Manager

Medium


There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.

+ +

Implement the AuthenticationManager class:

+ +
    +
  • AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.
  • +
  • generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.
  • +
  • renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.
  • +
  • countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.
  • +
+ +

Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.

+ +

 

+

Example 1:

+ +
Input
+["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"]
+[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]]
+Output
+[null, null, null, 1, null, null, null, 0]
+
+Explanation
+AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.
+authenticationManager.renew("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens.
+authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2.
+authenticationManager.countUnexpiredTokens(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1.
+authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7.
+authenticationManager.renew("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.
+authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.
+authenticationManager.countUnexpiredTokens(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= timeToLive <= 108
  • +
  • 1 <= currentTime <= 108
  • +
  • 1 <= tokenId.length <= 5
  • +
  • tokenId consists only of lowercase letters.
  • +
  • All calls to generate will contain unique values of tokenId.
  • +
  • The values of currentTime across all the function calls will be strictly increasing.
  • +
  • At most 2000 calls will be made to all functions combined.
  • +
+
\ No newline at end of file diff --git a/1799-maximize-score-after-n-operations/1799-maximize-score-after-n-operations.cpp b/1799-maximize-score-after-n-operations/1799-maximize-score-after-n-operations.cpp new file mode 100644 index 00000000..b2adf2ca --- /dev/null +++ b/1799-maximize-score-after-n-operations/1799-maximize-score-after-n-operations.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int solve(vector&nums, unordered_map, int>&mp, vector&visited, int operation) + { + if (mp.count(visited)) return mp[visited]; //use stored result + + int maxScore = 0; + for (int i = 0; i < nums.size() - 1; i++) + { + if (visited[i]) continue; + for (int j = i + 1; j < nums.size(); j++) + { + if (visited[j]) continue; + visited[i] = true; + visited[j] = true; + + int currScore = operation * __gcd(nums[i], nums[j]); + int nextMaxScore = solve(nums, mp, visited, operation + 1); + int totalScore = currScore + nextMaxScore; + maxScore = max(maxScore, totalScore); + + visited[i] = false; + visited[j] = false; + } + } + return mp[visited] = maxScore; //store the result + } + int maxScore(vector& nums) + { + int n = nums.size(); + vectorvisited(n, false); + unordered_map, int>mp; + int ans = solve(nums, mp, visited, 1); + return ans; + + } +}; \ No newline at end of file diff --git a/1799-maximize-score-after-n-operations/NOTES.md b/1799-maximize-score-after-n-operations/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1799-maximize-score-after-n-operations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1802-maximum-value-at-a-given-index-in-a-bounded-array/1802-maximum-value-at-a-given-index-in-a-bounded-array.cpp b/1802-maximum-value-at-a-given-index-in-a-bounded-array/1802-maximum-value-at-a-given-index-in-a-bounded-array.cpp new file mode 100644 index 00000000..8e2264fb --- /dev/null +++ b/1802-maximum-value-at-a-given-index-in-a-bounded-array/1802-maximum-value-at-a-given-index-in-a-bounded-array.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + long long c(long long n){ + return (n*(n+1))/2; + } + int maxValue(int n, int index, int maxSum) { + long long l=1,r=maxSum; + long long ans=1; + while(l<=r){ + long long mid=(l+r)/2; + long long left = c(mid-1); + if(index>mid-1){ + left += (index-mid+1); + } + else left -= c(mid-1-index); + long long right = c(mid-1) ; + if((n-1-index)>(mid-1)){ + right += (n-1-index-(mid-1)); + } + else right -= c(mid-1-(n-1-index)); + if(left+right<=(maxSum-mid)){ + ans=mid; + l=mid+1; + } + else r=mid-1; + } + return ans; + } +}; \ No newline at end of file diff --git a/1802-maximum-value-at-a-given-index-in-a-bounded-array/NOTES.md b/1802-maximum-value-at-a-given-index-in-a-bounded-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1802-maximum-value-at-a-given-index-in-a-bounded-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1802-maximum-value-at-a-given-index-in-a-bounded-array/README.md b/1802-maximum-value-at-a-given-index-in-a-bounded-array/README.md new file mode 100644 index 00000000..9cfd57cd --- /dev/null +++ b/1802-maximum-value-at-a-given-index-in-a-bounded-array/README.md @@ -0,0 +1,37 @@ +

1802. Maximum Value at a Given Index in a Bounded Array

Medium


You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:

+ +
    +
  • nums.length == n
  • +
  • nums[i] is a positive integer where 0 <= i < n.
  • +
  • abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.
  • +
  • The sum of all the elements of nums does not exceed maxSum.
  • +
  • nums[index] is maximized.
  • +
+ +

Return nums[index] of the constructed array.

+ +

Note that abs(x) equals x if x >= 0, and -x otherwise.

+ +

 

+

Example 1:

+ +
Input: n = 4, index = 2,  maxSum = 6
+Output: 2
+Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions.
+There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
+
+ +

Example 2:

+ +
Input: n = 6, index = 1,  maxSum = 10
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= maxSum <= 109
  • +
  • 0 <= index < n
  • +
+
\ No newline at end of file diff --git a/1822-sign-of-the-product-of-an-array/1822-sign-of-the-product-of-an-array.cpp b/1822-sign-of-the-product-of-an-array/1822-sign-of-the-product-of-an-array.cpp new file mode 100644 index 00000000..7d836b76 --- /dev/null +++ b/1822-sign-of-the-product-of-an-array/1822-sign-of-the-product-of-an-array.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int arraySign(vector& nums) { + + int neg(0), pos(0), rest(0); + + for(auto itr : nums) + { + if(itr < 0) + ++neg; + else if(itr > 0) + ++pos; + else + ++rest; + } + + if(rest) + return 0; + if(neg & 1) + return -1; + return 1; + } +}; \ No newline at end of file diff --git a/1822-sign-of-the-product-of-an-array/NOTES.md b/1822-sign-of-the-product-of-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1822-sign-of-the-product-of-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1822-sign-of-the-product-of-an-array/README.md b/1822-sign-of-the-product-of-an-array/README.md new file mode 100644 index 00000000..f7b477f0 --- /dev/null +++ b/1822-sign-of-the-product-of-an-array/README.md @@ -0,0 +1,42 @@ +

1822. Sign of the Product of an Array

Easy


There is a function signFunc(x) that returns:

+ +
    +
  • 1 if x is positive.
  • +
  • -1 if x is negative.
  • +
  • 0 if x is equal to 0.
  • +
+ +

You are given an integer array nums. Let product be the product of all values in the array nums.

+ +

Return signFunc(product).

+ +

 

+

Example 1:

+ +
Input: nums = [-1,-2,-3,-4,3,2,1]
+Output: 1
+Explanation: The product of all values in the array is 144, and signFunc(144) = 1
+
+ +

Example 2:

+ +
Input: nums = [1,5,0,2,-3]
+Output: 0
+Explanation: The product of all values in the array is 0, and signFunc(0) = 0
+
+ +

Example 3:

+ +
Input: nums = [-1,1,-1,1,-1]
+Output: -1
+Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -100 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.cpp b/1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.cpp new file mode 100644 index 00000000..f12c3ff0 --- /dev/null +++ b/1833-maximum-ice-cream-bars/1833-maximum-ice-cream-bars.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxIceCream(vector& costs, int coins) { + + int ans = 0; + sort(costs.begin(),costs.end()); + + for(auto itr : costs) + { + if(itr <= coins) + { + ++ans; + coins -= itr; + } + else + { + break; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/1833-maximum-ice-cream-bars/NOTES.md b/1833-maximum-ice-cream-bars/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1833-maximum-ice-cream-bars/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1833-maximum-ice-cream-bars/README.md b/1833-maximum-ice-cream-bars/README.md new file mode 100644 index 00000000..c1a4b84f --- /dev/null +++ b/1833-maximum-ice-cream-bars/README.md @@ -0,0 +1,39 @@ +

1833. Maximum Ice Cream Bars

Medium


It is a sweltering summer day, and a boy wants to buy some ice cream bars.

+ +

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 

+ +

Return the maximum number of ice cream bars the boy can buy with coins coins.

+ +

Note: The boy can buy the ice cream bars in any order.

+ +

 

+

Example 1:

+ +
Input: costs = [1,3,2,4,1], coins = 7
+Output: 4
+Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
+
+ +

Example 2:

+ +
Input: costs = [10,6,8,7,7,8], coins = 5
+Output: 0
+Explanation: The boy cannot afford any of the ice cream bars.
+
+ +

Example 3:

+ +
Input: costs = [1,6,3,1,2,5], coins = 20
+Output: 6
+Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
+
+ +

 

+

Constraints:

+ +
    +
  • costs.length == n
  • +
  • 1 <= n <= 105
  • +
  • 1 <= costs[i] <= 105
  • +
  • 1 <= coins <= 108
  • +
\ No newline at end of file diff --git a/1834-single-threaded-cpu/1834-single-threaded-cpu.cpp b/1834-single-threaded-cpu/1834-single-threaded-cpu.cpp new file mode 100644 index 00000000..63215c81 --- /dev/null +++ b/1834-single-threaded-cpu/1834-single-threaded-cpu.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + vector getOrder(vector>& tasks) { + + int n = tasks.size(); + + vector > vp; + for(int i = 0; i < n; ++i) + vp.push_back({tasks[i][0],tasks[i][1],i}); + + sort(vp.begin(),vp.end()); + + priority_queue, vector>, greater> > pq; + + int endTime = vp[0][0], i = 0; + vector ans; + + while(i < n) + { + if(!pq.empty()) + { + endTime += pq.top()[0]; + ans.push_back(pq.top()[1]); + pq.pop(); + } + while(i < n and vp[i][0] <= endTime) + { + pq.push({vp[i][1],vp[i][2],vp[i][1]}); + ++i; + } + if(i < n and endTime < vp[i][0] and pq.empty()) + endTime = vp[i][0]; + } + + while(!pq.empty()) + { + ans.push_back(pq.top()[1]); + pq.pop(); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1834-single-threaded-cpu/README.md b/1834-single-threaded-cpu/README.md new file mode 100644 index 00000000..0c648b29 --- /dev/null +++ b/1834-single-threaded-cpu/README.md @@ -0,0 +1,53 @@ +

1834. Single-Threaded CPU

Medium


You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.

+ +

You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

+ +
    +
  • If the CPU is idle and there are no available tasks to process, the CPU remains idle.
  • +
  • If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
  • +
  • Once a task is started, the CPU will process the entire task without stopping.
  • +
  • The CPU can finish a task then start a new one instantly.
  • +
+ +

Return the order in which the CPU will process the tasks.

+ +

 

+

Example 1:

+ +
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
+Output: [0,2,3,1]
+Explanation: The events go as follows: 
+- At time = 1, task 0 is available to process. Available tasks = {0}.
+- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
+- At time = 2, task 1 is available to process. Available tasks = {1}.
+- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
+- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
+- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
+- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
+- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
+- At time = 10, the CPU finishes task 1 and becomes idle.
+
+ +

Example 2:

+ +
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
+Output: [4,3,2,0,1]
+Explanation: The events go as follows:
+- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
+- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
+- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
+- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
+- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
+- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
+- At time = 40, the CPU finishes task 1 and becomes idle.
+
+ +

 

+

Constraints:

+ +
    +
  • tasks.length == n
  • +
  • 1 <= n <= 105
  • +
  • 1 <= enqueueTimei, processingTimei <= 109
  • +
+
\ No newline at end of file diff --git a/1845-seat-reservation-manager/1845-seat-reservation-manager.cpp b/1845-seat-reservation-manager/1845-seat-reservation-manager.cpp new file mode 100644 index 00000000..1931d631 --- /dev/null +++ b/1845-seat-reservation-manager/1845-seat-reservation-manager.cpp @@ -0,0 +1,46 @@ +class SeatManager { +public: + + set st; + vector seat; + int counter = 1; + int N; + + SeatManager(int n) { + N = n; + seat.resize(n+1, 0); + } + + int reserve() { + + if(!st.empty()) + { + int least = *st.begin(); + st.erase(*st.begin()); + seat[least] = 1; + return least; + } + + if(counter <= N) + { + seat[counter] = 1; + int smallestUnreserved = counter; + ++counter; + return smallestUnreserved; + } + + return -1; + } + + void unreserve(int seatNumber) { + st.insert(seatNumber); + seat[seatNumber] = 0; + } +}; + +/** + * Your SeatManager object will be instantiated and called as such: + * SeatManager* obj = new SeatManager(n); + * int param_1 = obj->reserve(); + * obj->unreserve(seatNumber); + */ \ No newline at end of file diff --git a/1845-seat-reservation-manager/NOTES.md b/1845-seat-reservation-manager/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1845-seat-reservation-manager/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1845-seat-reservation-manager/README.md b/1845-seat-reservation-manager/README.md new file mode 100644 index 00000000..889dd702 --- /dev/null +++ b/1845-seat-reservation-manager/README.md @@ -0,0 +1,42 @@ +

1845. Seat Reservation Manager

Medium


Design a system that manages the reservation state of n seats that are numbered from 1 to n.

+ +

Implement the SeatManager class:

+ +
    +
  • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
  • +
  • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
  • +
  • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.
  • +
+ +

 

+

Example 1:

+ +
Input
+["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
+[[5], [], [], [2], [], [], [], [], [5]]
+Output
+[null, 1, 2, null, 2, 3, 4, 5, null]
+
+Explanation
+SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
+seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.
+seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
+seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].
+seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
+seatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which is 3.
+seatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is 4.
+seatManager.reserve();    // The only available seat is seat 5, so return 5.
+seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 1 <= seatNumber <= n
  • +
  • For each call to reserve, it is guaranteed that there will be at least one unreserved seat.
  • +
  • For each call to unreserve, it is guaranteed that seatNumber will be reserved.
  • +
  • At most 105 calls in total will be made to reserve and unreserve.
  • +
+
\ No newline at end of file diff --git a/1857-largest-color-value-in-a-directed-graph/1857-largest-color-value-in-a-directed-graph.cpp b/1857-largest-color-value-in-a-directed-graph/1857-largest-color-value-in-a-directed-graph.cpp new file mode 100644 index 00000000..b8a82a32 --- /dev/null +++ b/1857-largest-color-value-in-a-directed-graph/1857-largest-color-value-in-a-directed-graph.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int largestPathValue(string colors, vector>& edges) { + int n = colors.size(),k=26; + vector indegrees(n, 0); + vector> graph(n, vector()); + for (auto edge : edges) { + int u = edge[0]; + int v = edge[1]; + graph[u].push_back(v); + indegrees[v]++; + } + unordered_set zero_indegree; + for (int i = 0; i < n; i++) { + if (indegrees[i] == 0) { + zero_indegree.insert(i); + } + } + vector> counts(n, vector(k, 0)); + for (int i = 0; i < n; i++) { + counts[i][colors[i] - 'a']++; + } + int max_count = 0,visited = 0; + while (!zero_indegree.empty()) { + int u = *zero_indegree.begin(); + zero_indegree.erase(u); + visited++; + for (int v : graph[u]) { + for (int i = 0; i < k; i++) + counts[v][i] = max(counts[v][i], counts[u][i] + (colors[v] - 'a' == i ? 1 : 0)); + indegrees[v]--; + if (indegrees[v] == 0) { + zero_indegree.insert(v); + } + } + max_count = max(max_count, *max_element(counts[u].begin(), counts[u].end())); + } + return visited == n ? max_count : -1; + } +}; \ No newline at end of file diff --git a/1857-largest-color-value-in-a-directed-graph/NOTES.md b/1857-largest-color-value-in-a-directed-graph/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1857-largest-color-value-in-a-directed-graph/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1857-largest-color-value-in-a-directed-graph/README.md b/1857-largest-color-value-in-a-directed-graph/README.md new file mode 100644 index 00000000..cd221a6b --- /dev/null +++ b/1857-largest-color-value-in-a-directed-graph/README.md @@ -0,0 +1,38 @@ +

1857. Largest Color Value in a Directed Graph

Hard


There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.

+ +

You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.

+ +

A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.

+ +

Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.

+ +

 

+

Example 1:

+ +

+ +
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
+Output: 3
+Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
+
+ +

Example 2:

+ +

+ +
Input: colors = "a", edges = [[0,0]]
+Output: -1
+Explanation: There is a cycle from 0 to 0.
+
+ +

 

+

Constraints:

+ +
    +
  • n == colors.length
  • +
  • m == edges.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= m <= 105
  • +
  • colors consists of lowercase English letters.
  • +
  • 0 <= aj, bj < n
  • +
\ No newline at end of file diff --git a/1863-sum-of-all-subset-xor-totals/1863-sum-of-all-subset-xor-totals.cpp b/1863-sum-of-all-subset-xor-totals/1863-sum-of-all-subset-xor-totals.cpp new file mode 100644 index 00000000..8aa5e6d0 --- /dev/null +++ b/1863-sum-of-all-subset-xor-totals/1863-sum-of-all-subset-xor-totals.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int subsetXORSum(vector& nums) { + + int n = nums.size(); + + int range = (1 << n); + + int ans = 0; + + for(int i = 0; i < range; ++i) + { + int curXor = 0; + for(int j = 0; j < n; ++j) + { + if(i & (1 << j)) + curXor ^= nums[j]; + } + ans += curXor; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1863-sum-of-all-subset-xor-totals/NOTES.md b/1863-sum-of-all-subset-xor-totals/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1863-sum-of-all-subset-xor-totals/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1863-sum-of-all-subset-xor-totals/README.md b/1863-sum-of-all-subset-xor-totals/README.md new file mode 100644 index 00000000..4468942a --- /dev/null +++ b/1863-sum-of-all-subset-xor-totals/README.md @@ -0,0 +1,56 @@ +

1863. Sum of All Subset XOR Totals

Easy


The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.

+ +
    +
  • For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
  • +
+ +

Given an array nums, return the sum of all XOR totals for every subset of nums

+ +

Note: Subsets with the same elements should be counted multiple times.

+ +

An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3]
+Output: 6
+Explanation: The 4 subsets of [1,3] are:
+- The empty subset has an XOR total of 0.
+- [1] has an XOR total of 1.
+- [3] has an XOR total of 3.
+- [1,3] has an XOR total of 1 XOR 3 = 2.
+0 + 1 + 3 + 2 = 6
+
+ +

Example 2:

+ +
Input: nums = [5,1,6]
+Output: 28
+Explanation: The 8 subsets of [5,1,6] are:
+- The empty subset has an XOR total of 0.
+- [5] has an XOR total of 5.
+- [1] has an XOR total of 1.
+- [6] has an XOR total of 6.
+- [5,1] has an XOR total of 5 XOR 1 = 4.
+- [5,6] has an XOR total of 5 XOR 6 = 3.
+- [1,6] has an XOR total of 1 XOR 6 = 7.
+- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
+0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
+
+ +

Example 3:

+ +
Input: nums = [3,4,5,6,7,8]
+Output: 480
+Explanation: The sum of all XOR totals for every subset is 480.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 12
  • +
  • 1 <= nums[i] <= 20
  • +
+
\ No newline at end of file diff --git a/1870-minimum-speed-to-arrive-on-time/1870-minimum-speed-to-arrive-on-time.cpp b/1870-minimum-speed-to-arrive-on-time/1870-minimum-speed-to-arrive-on-time.cpp new file mode 100644 index 00000000..856e8dbb --- /dev/null +++ b/1870-minimum-speed-to-arrive-on-time/1870-minimum-speed-to-arrive-on-time.cpp @@ -0,0 +1,32 @@ +class Solution +{ + bool canReachInTime(const vector& dist, const double hour, int speed) + { + double time = 0; + for (int i = 0; i < dist.size() - 1; ++i) + time += ((dist[i] + speed - 1) / speed); + + time += ((double)dist.back()) / speed; + return time <= hour; + } + +public: + int minSpeedOnTime(vector& dist, double hour) + { + int N = dist.size(); + if (hour <= (double)(N - 1)) + return -1; + + int lo = 1, hi = 1e7, mi; + while (lo < hi) + { + mi = (lo + hi) / 2; + if (canReachInTime(dist, hour, mi)) + hi = mi; + else + lo = mi + 1; + } + + return hi; + } +}; \ No newline at end of file diff --git a/1870-minimum-speed-to-arrive-on-time/NOTES.md b/1870-minimum-speed-to-arrive-on-time/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1870-minimum-speed-to-arrive-on-time/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1870-minimum-speed-to-arrive-on-time/README.md b/1870-minimum-speed-to-arrive-on-time/README.md new file mode 100644 index 00000000..49497e4c --- /dev/null +++ b/1870-minimum-speed-to-arrive-on-time/README.md @@ -0,0 +1,53 @@ +

1870. Minimum Speed to Arrive on Time

Medium


You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.

+ +

Each train can only depart at an integer hour, so you may need to wait in between each train ride.

+ +
    +
  • For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
  • +
+ +

Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.

+ +

Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.

+ +

 

+

Example 1:

+ +
Input: dist = [1,3,2], hour = 6
+Output: 1
+Explanation: At speed 1:
+- The first train ride takes 1/1 = 1 hour.
+- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
+- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
+- You will arrive at exactly the 6 hour mark.
+
+ +

Example 2:

+ +
Input: dist = [1,3,2], hour = 2.7
+Output: 3
+Explanation: At speed 3:
+- The first train ride takes 1/3 = 0.33333 hours.
+- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
+- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
+- You will arrive at the 2.66667 hour mark.
+
+ +

Example 3:

+ +
Input: dist = [1,3,2], hour = 1.9
+Output: -1
+Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
+
+ +

 

+

Constraints:

+ +
    +
  • n == dist.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= dist[i] <= 105
  • +
  • 1 <= hour <= 109
  • +
  • There will be at most two digits after the decimal point in hour.
  • +
+
\ No newline at end of file diff --git a/1877-minimize-maximum-pair-sum-in-array/NOTES.md b/1877-minimize-maximum-pair-sum-in-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1877-minimize-maximum-pair-sum-in-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1877-minimize-maximum-pair-sum-in-array/README.md b/1877-minimize-maximum-pair-sum-in-array/README.md new file mode 100644 index 00000000..f49c9aa1 --- /dev/null +++ b/1877-minimize-maximum-pair-sum-in-array/README.md @@ -0,0 +1,41 @@ +

1877. Minimize Maximum Pair Sum in Array

Medium


The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.

+ +
    +
  • For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
  • +
+ +

Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:

+ +
    +
  • Each element of nums is in exactly one pair, and
  • +
  • The maximum pair sum is minimized.
  • +
+ +

Return the minimized maximum pair sum after optimally pairing up the elements.

+ +

 

+

Example 1:

+ +
Input: nums = [3,5,2,3]
+Output: 7
+Explanation: The elements can be paired up into pairs (3,3) and (5,2).
+The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
+
+ +

Example 2:

+ +
Input: nums = [3,5,4,2,4,6]
+Output: 8
+Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
+The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 2 <= n <= 105
  • +
  • n is even.
  • +
  • 1 <= nums[i] <= 105
  • +
\ No newline at end of file diff --git a/1887-reduction-operations-to-make-the-array-elements-equal/1887-reduction-operations-to-make-the-array-elements-equal.cpp b/1887-reduction-operations-to-make-the-array-elements-equal/1887-reduction-operations-to-make-the-array-elements-equal.cpp new file mode 100644 index 00000000..894f7ffb --- /dev/null +++ b/1887-reduction-operations-to-make-the-array-elements-equal/1887-reduction-operations-to-make-the-array-elements-equal.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int reductionOperations(vector& nums) { + + int n = nums.size(), ans = 0; + + sort(nums.begin(), nums.end()); + + for(int i = n-1; i > 0; --i) + { + if(nums[i] != nums[i-1]) + { + ans += (n - i); + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/1887-reduction-operations-to-make-the-array-elements-equal/README.md b/1887-reduction-operations-to-make-the-array-elements-equal/README.md new file mode 100644 index 00000000..a2eb1b38 --- /dev/null +++ b/1887-reduction-operations-to-make-the-array-elements-equal/README.md @@ -0,0 +1,47 @@ +

1887. Reduction Operations to Make the Array Elements Equal

Medium


Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:

+ +
    +
  1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
  2. +
  3. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
  4. +
  5. Reduce nums[i] to nextLargest.
  6. +
+ +

Return the number of operations to make all elements in nums equal.

+ +

 

+

Example 1:

+ +
Input: nums = [5,1,3]
+Output: 3
+Explanation: It takes 3 operations to make all elements in nums equal:
+1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
+2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
+3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
+
+ +

Example 2:

+ +
Input: nums = [1,1,1]
+Output: 0
+Explanation: All elements in nums are already equal.
+
+ +

Example 3:

+ +
Input: nums = [1,1,2,2,3]
+Output: 4
+Explanation: It takes 4 operations to make all elements in nums equal:
+1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
+2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
+3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
+4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 1 <= nums[i] <= 5 * 104
  • +
+
\ No newline at end of file diff --git a/1897-redistribute-characters-to-make-all-strings-equal/1897-redistribute-characters-to-make-all-strings-equal.cpp b/1897-redistribute-characters-to-make-all-strings-equal/1897-redistribute-characters-to-make-all-strings-equal.cpp new file mode 100644 index 00000000..38a9b341 --- /dev/null +++ b/1897-redistribute-characters-to-make-all-strings-equal/1897-redistribute-characters-to-make-all-strings-equal.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + bool makeEqual(vector& words) { + + int n = words.size(); + + bool ok = true; + + vector freq(26, 0); + + for(auto& word : words) + { + for(auto& ch : word) + ++freq[ch-'a']; + + } + + for(auto& f : freq) + { + if(f and f % n != 0) + { + ok = false; + break; + } + } + + return ok; + } +}; \ No newline at end of file diff --git a/1897-redistribute-characters-to-make-all-strings-equal/NOTES.md b/1897-redistribute-characters-to-make-all-strings-equal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1897-redistribute-characters-to-make-all-strings-equal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1897-redistribute-characters-to-make-all-strings-equal/README.md b/1897-redistribute-characters-to-make-all-strings-equal/README.md new file mode 100644 index 00000000..a493914d --- /dev/null +++ b/1897-redistribute-characters-to-make-all-strings-equal/README.md @@ -0,0 +1,32 @@ +

1897. Redistribute Characters to Make All Strings Equal

Easy


You are given an array of strings words (0-indexed).

+ +

In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].

+ +

Return true if you can make every string in words equal using any number of operations, and false otherwise.

+ +

 

+

Example 1:

+ +
Input: words = ["abc","aabc","bc"]
+Output: true
+Explanation: Move the first 'a' in words[1] to the front of words[2],
+to make words[1] = "abc" and words[2] = "abc".
+All the strings are now equal to "abc", so return true.
+
+ +

Example 2:

+ +
Input: words = ["ab","a"]
+Output: false
+Explanation: It is impossible to make all the strings equal using the operation.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1903-largest-odd-number-in-string/1903-largest-odd-number-in-string.cpp b/1903-largest-odd-number-in-string/1903-largest-odd-number-in-string.cpp new file mode 100644 index 00000000..3422d3f7 --- /dev/null +++ b/1903-largest-odd-number-in-string/1903-largest-odd-number-in-string.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + string largestOddNumber(string num) { + + int n = num.size(); + + for(int i = n-1; i >= 0; --i) + { + if((num[i] - '0') & 1) + return num.substr(0, i+1); + } + + return ""; + + } +}; \ No newline at end of file diff --git a/1903-largest-odd-number-in-string/NOTES.md b/1903-largest-odd-number-in-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1903-largest-odd-number-in-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1903-largest-odd-number-in-string/README.md b/1903-largest-odd-number-in-string/README.md new file mode 100644 index 00000000..0def66fa --- /dev/null +++ b/1903-largest-odd-number-in-string/README.md @@ -0,0 +1,34 @@ +

1903. Largest Odd Number in String

Easy


You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.

+ +

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

+ +

 

+

Example 1:

+ +
Input: num = "52"
+Output: "5"
+Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
+
+ +

Example 2:

+ +
Input: num = "4206"
+Output: ""
+Explanation: There are no odd numbers in "4206".
+
+ +

Example 3:

+ +
Input: num = "35427"
+Output: "35427"
+Explanation: "35427" is already an odd number.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num.length <= 105
  • +
  • num only consists of digits and does not contain any leading zeros.
  • +
+
\ No newline at end of file diff --git a/1905-count-sub-islands/1905-count-sub-islands.cpp b/1905-count-sub-islands/1905-count-sub-islands.cpp new file mode 100644 index 00000000..bd5ccebd --- /dev/null +++ b/1905-count-sub-islands/1905-count-sub-islands.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + + int n = grid1.size(); + int m = grid1[0].size(); + + vector> visited(n, vector(m, false)); + + function dfs = [&](int i, int j) -> bool{ + if(i < 0 or j < 0 or i >= n or j >= m or visited[i][j] or !grid2[i][j]) + return true; + + if(!grid1[i][j]) return false; + + visited[i][j] = true; + + bool up, left, right, down; + up = left = right = down = true; + + up = dfs(i-1, j); + left = dfs(i, j-1); + down = dfs(i+1, j); + right = dfs(i, j+1); + + return up and left and down and right; + }; + + int subIsland = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(!visited[i][j] and grid2[i][j]) + { + if(dfs(i, j)) + { + ++subIsland; + } + } + } + } + + return subIsland; + } +}; \ No newline at end of file diff --git a/1905-count-sub-islands/NOTES.md b/1905-count-sub-islands/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1905-count-sub-islands/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1905-count-sub-islands/README.md b/1905-count-sub-islands/README.md new file mode 100644 index 00000000..b76cb8e8 --- /dev/null +++ b/1905-count-sub-islands/README.md @@ -0,0 +1,33 @@ +

1905. Count Sub Islands

Medium


You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

+ +

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

+ +

Return the number of islands in grid2 that are considered sub-islands.

+ +

 

+

Example 1:

+ +
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
+Output: 3
+Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
+The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
+
+ +

Example 2:

+ +
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
+Output: 2 
+Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
+The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid1.length == grid2.length
  • +
  • n == grid1[i].length == grid2[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • grid1[i][j] and grid2[i][j] are either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/1913-maximum-product-difference-between-two-pairs/1913-maximum-product-difference-between-two-pairs.cpp b/1913-maximum-product-difference-between-two-pairs/1913-maximum-product-difference-between-two-pairs.cpp new file mode 100644 index 00000000..7488c8e8 --- /dev/null +++ b/1913-maximum-product-difference-between-two-pairs/1913-maximum-product-difference-between-two-pairs.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maxProductDifference(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(),nums.end()); + + return ((nums[n-1] * nums[n-2]) - (nums[0] * nums[1])); + } +}; \ No newline at end of file diff --git a/1913-maximum-product-difference-between-two-pairs/NOTES.md b/1913-maximum-product-difference-between-two-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1913-maximum-product-difference-between-two-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1913-maximum-product-difference-between-two-pairs/README.md b/1913-maximum-product-difference-between-two-pairs/README.md new file mode 100644 index 00000000..3b05b9ed --- /dev/null +++ b/1913-maximum-product-difference-between-two-pairs/README.md @@ -0,0 +1,34 @@ +

1913. Maximum Product Difference Between Two Pairs

Easy


The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

+ +
    +
  • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
  • +
+ +

Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

+ +

Return the maximum such product difference.

+ +

 

+

Example 1:

+ +
Input: nums = [5,6,2,7,4]
+Output: 34
+Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
+The product difference is (6 * 7) - (2 * 4) = 34.
+
+ +

Example 2:

+ +
Input: nums = [4,2,5,9,7,4,8]
+Output: 64
+Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
+The product difference is (9 * 8) - (2 * 4) = 64.
+
+ +

 

+

Constraints:

+ +
    +
  • 4 <= nums.length <= 104
  • +
  • 1 <= nums[i] <= 104
  • +
\ No newline at end of file diff --git a/1915-number-of-wonderful-substrings/1915-number-of-wonderful-substrings.cpp b/1915-number-of-wonderful-substrings/1915-number-of-wonderful-substrings.cpp new file mode 100644 index 00000000..f89c9d77 --- /dev/null +++ b/1915-number-of-wonderful-substrings/1915-number-of-wonderful-substrings.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + long long wonderfulSubstrings(string word) { + + long cnt[1024] = { 1 }, mask = 0, res = 0; + for (auto ch : word) { + mask ^= 1 << (ch - 'a'); + res += cnt[mask]; + for (auto n = 0; n < 10; ++n) + res += cnt[mask ^ (1 << n)]; + ++cnt[mask]; + } + return res; + } +}; \ No newline at end of file diff --git a/1915-number-of-wonderful-substrings/README.md b/1915-number-of-wonderful-substrings/README.md new file mode 100644 index 00000000..c19d9e1f --- /dev/null +++ b/1915-number-of-wonderful-substrings/README.md @@ -0,0 +1,54 @@ +

1915. Number of Wonderful Substrings

Medium


A wonderful string is a string where at most one letter appears an odd number of times.

+ +
    +
  • For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
  • +
+ +

Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.

+ +

A substring is a contiguous sequence of characters in a string.

+ +

 

+

Example 1:

+ +
Input: word = "aba"
+Output: 4
+Explanation: The four wonderful substrings are underlined below:
+- "aba" -> "a"
+- "aba" -> "b"
+- "aba" -> "a"
+- "aba" -> "aba"
+
+ +

Example 2:

+ +
Input: word = "aabb"
+Output: 9
+Explanation: The nine wonderful substrings are underlined below:
+- "aabb" -> "a"
+- "aabb" -> "aa"
+- "aabb" -> "aab"
+- "aabb" -> "aabb"
+- "aabb" -> "a"
+- "aabb" -> "abb"
+- "aabb" -> "b"
+- "aabb" -> "bb"
+- "aabb" -> "b"
+
+ +

Example 3:

+ +
Input: word = "he"
+Output: 2
+Explanation: The two wonderful substrings are underlined below:
+- "he" -> "h"
+- "he" -> "e"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 105
  • +
  • word consists of lowercase English letters from 'a' to 'j'.
  • +
\ No newline at end of file diff --git a/1921-eliminate-maximum-number-of-monsters/1921-eliminate-maximum-number-of-monsters.cpp b/1921-eliminate-maximum-number-of-monsters/1921-eliminate-maximum-number-of-monsters.cpp new file mode 100644 index 00000000..e7a702a0 --- /dev/null +++ b/1921-eliminate-maximum-number-of-monsters/1921-eliminate-maximum-number-of-monsters.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int eliminateMaximum(vector& dist, vector& speed) { + + int n = dist.size(); + + vector vec; + + for(int i = 0; i < n; ++i) + { + vec.push_back((float)dist[i]/speed[i]); + } + + sort(vec.begin(), vec.end()); + + int counter = 1, ans = 1; + + for(int i = 1; i < n; ++i) + { + if(counter < vec[i]) + ++ans; + else + break; + ++counter; + } + + return ans; + } +}; \ No newline at end of file diff --git a/1921-eliminate-maximum-number-of-monsters/README.md b/1921-eliminate-maximum-number-of-monsters/README.md new file mode 100644 index 00000000..53ce3337 --- /dev/null +++ b/1921-eliminate-maximum-number-of-monsters/README.md @@ -0,0 +1,50 @@ +

1921. Eliminate Maximum Number of Monsters

Medium


You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.

+ +

The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.

+ +

You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.

+ +

You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.

+ +

Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.

+ +

 

+

Example 1:

+ +
Input: dist = [1,3,4], speed = [1,1,1]
+Output: 3
+Explanation:
+In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.
+After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.
+All 3 monsters can be eliminated.
+ +

Example 2:

+ +
Input: dist = [1,1,2,3], speed = [1,1,1,1]
+Output: 1
+Explanation:
+In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,0,1,2], so you lose.
+You can only eliminate 1 monster.
+
+ +

Example 3:

+ +
Input: dist = [3,2,4], speed = [5,3,2]
+Output: 1
+Explanation:
+In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.
+After a minute, the distances of the monsters are [X,0,2], so you lose.
+You can only eliminate 1 monster.
+
+ +

 

+

Constraints:

+ +
    +
  • n == dist.length == speed.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= dist[i], speed[i] <= 105
  • +
+
\ No newline at end of file diff --git a/1930-unique-length-3-palindromic-subsequences/1930-unique-length-3-palindromic-subsequences.cpp b/1930-unique-length-3-palindromic-subsequences/1930-unique-length-3-palindromic-subsequences.cpp new file mode 100644 index 00000000..48915358 --- /dev/null +++ b/1930-unique-length-3-palindromic-subsequences/1930-unique-length-3-palindromic-subsequences.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + int countPalindromicSubsequence(string s) { + + int n = s.size(); + + unordered_map> mp; + unordered_map firstOccurence, lastOccurence; + int palindrome = 0; + + for(int i = 0; i < n; ++i) + { + if(firstOccurence.find(s[i]) == firstOccurence.end()) + { + firstOccurence[s[i]] = i; + } + + lastOccurence[s[i]] = i; + + mp[s[i]].push_back(i); + } + + for(int ch = 'a'; ch <= 'z'; ++ch) + { + int left = firstOccurence[ch]; + int right = lastOccurence[ch]; + + if(right - left <= 1) + continue; + + for(char x = 'a'; x <= 'z'; ++x) + { + if(mp.find(x) != mp.end()) + { + int ub = upper_bound(mp[x].begin(), mp[x].end(), left) - mp[x].begin(); + + if(ub == mp[x].size()) + continue; + + int idx = mp[x][ub]; + + if(idx < right) + ++palindrome; + } + } + } + + return palindrome; + } +}; \ No newline at end of file diff --git a/1930-unique-length-3-palindromic-subsequences/NOTES.md b/1930-unique-length-3-palindromic-subsequences/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1930-unique-length-3-palindromic-subsequences/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1930-unique-length-3-palindromic-subsequences/README.md b/1930-unique-length-3-palindromic-subsequences/README.md new file mode 100644 index 00000000..099bc405 --- /dev/null +++ b/1930-unique-length-3-palindromic-subsequences/README.md @@ -0,0 +1,49 @@ +

1930. Unique Length-3 Palindromic Subsequences

Medium


Given a string s, return the number of unique palindromes of length three that are a subsequence of s.

+ +

Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.

+ +

A palindrome is a string that reads the same forwards and backwards.

+ +

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

+ +
    +
  • For example, "ace" is a subsequence of "abcde".
  • +
+ +

 

+

Example 1:

+ +
Input: s = "aabca"
+Output: 3
+Explanation: The 3 palindromic subsequences of length 3 are:
+- "aba" (subsequence of "aabca")
+- "aaa" (subsequence of "aabca")
+- "aca" (subsequence of "aabca")
+
+ +

Example 2:

+ +
Input: s = "adc"
+Output: 0
+Explanation: There are no palindromic subsequences of length 3 in "adc".
+
+ +

Example 3:

+ +
Input: s = "bbcbaba"
+Output: 4
+Explanation: The 4 palindromic subsequences of length 3 are:
+- "bbb" (subsequence of "bbcbaba")
+- "bcb" (subsequence of "bbcbaba")
+- "bab" (subsequence of "bbcbaba")
+- "aba" (subsequence of "bbcbaba")
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= s.length <= 105
  • +
  • s consists of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/1937-maximum-number-of-points-with-cost/README.md b/1937-maximum-number-of-points-with-cost/README.md new file mode 100644 index 00000000..d0709862 --- /dev/null +++ b/1937-maximum-number-of-points-with-cost/README.md @@ -0,0 +1,49 @@ +

1937. Maximum Number of Points with Cost

Medium


You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.

+ +

To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.

+ +

However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.

+ +

Return the maximum number of points you can achieve.

+ +

abs(x) is defined as:

+ +
    +
  • x for x >= 0.
  • +
  • -x for x < 0.
  • +
+ +

 

+

Example 1:

+ +
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
+Output: 9
+Explanation:
+The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
+You add 3 + 5 + 3 = 11 to your score.
+However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
+Your final score is 11 - 2 = 9.
+
+ +

Example 2:

+ +
Input: points = [[1,5],[2,3],[4,2]]
+Output: 11
+Explanation:
+The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
+You add 5 + 3 + 4 = 12 to your score.
+However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
+Your final score is 12 - 1 = 11.
+
+ +

 

+

Constraints:

+ +
    +
  • m == points.length
  • +
  • n == points[r].length
  • +
  • 1 <= m, n <= 105
  • +
  • 1 <= m * n <= 105
  • +
  • 0 <= points[r][c] <= 105
  • +
+
\ No newline at end of file diff --git a/1962-remove-stones-to-minimize-the-total/1962-remove-stones-to-minimize-the-total.cpp b/1962-remove-stones-to-minimize-the-total/1962-remove-stones-to-minimize-the-total.cpp new file mode 100644 index 00000000..c5729186 --- /dev/null +++ b/1962-remove-stones-to-minimize-the-total/1962-remove-stones-to-minimize-the-total.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minStoneSum(vector& piles, int k) { + + priority_queue pq; + + for(auto itr : piles) + pq.push(itr); + + int res = accumulate(begin(piles),end(piles),0); + + while(k--) + { + int here = pq.top(); + pq.pop(); + pq.push(here - here/2); + res -= here/2; + } + + return res; + } +}; \ No newline at end of file diff --git a/1962-remove-stones-to-minimize-the-total/NOTES.md b/1962-remove-stones-to-minimize-the-total/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1962-remove-stones-to-minimize-the-total/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1962-remove-stones-to-minimize-the-total/README.md b/1962-remove-stones-to-minimize-the-total/README.md new file mode 100644 index 00000000..9b307b06 --- /dev/null +++ b/1962-remove-stones-to-minimize-the-total/README.md @@ -0,0 +1,43 @@ +

1962. Remove Stones to Minimize the Total

Medium


You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:

+ +
    +
  • Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
  • +
+ +

Notice that you can apply the operation on the same pile more than once.

+ +

Return the minimum possible total number of stones remaining after applying the k operations.

+ +

floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).

+ +

 

+

Example 1:

+ +
Input: piles = [5,4,9], k = 2
+Output: 12
+Explanation: Steps of a possible scenario are:
+- Apply the operation on pile 2. The resulting piles are [5,4,5].
+- Apply the operation on pile 0. The resulting piles are [3,4,5].
+The total number of stones in [3,4,5] is 12.
+
+ +

Example 2:

+ +
Input: piles = [4,3,6,7], k = 3
+Output: 12
+Explanation: Steps of a possible scenario are:
+- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
+- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
+- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
+The total number of stones in [2,3,3,4] is 12.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= piles.length <= 105
  • +
  • 1 <= piles[i] <= 104
  • +
  • 1 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/1964-find-the-longest-valid-obstacle-course-at-each-position/1964-find-the-longest-valid-obstacle-course-at-each-position.cpp b/1964-find-the-longest-valid-obstacle-course-at-each-position/1964-find-the-longest-valid-obstacle-course-at-each-position.cpp new file mode 100644 index 00000000..94ffaf96 --- /dev/null +++ b/1964-find-the-longest-valid-obstacle-course-at-each-position/1964-find-the-longest-valid-obstacle-course-at-each-position.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + + int helper(int idx, int n, int prev, vector& obstacles) + { + if(idx > n) + return 0; + + int take = 0 , notTake = 0; + + notTake = helper(idx+1, n, prev, obstacles); + + if(prev == -1 or obstacles[idx] >= obstacles[prev] ) + take = max(helper(idx+1, n, prev, obstacles), 1 + helper(idx+1, n, idx, obstacles)); + + return max(take, notTake); + } + + + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + + vector dp (obstacles.size(),1); + int result=1; + vector b(obstacles.size()+1, INT_MAX); + b[0]=INT_MIN; + + for(int i=0; i>&vis,vector>&v,int i,int j){ + vis[i][j]=1; + if(i==n-1)return true; + bool ans = false; + for(int k=0;k<4;k++){ + int ni = i + d[k]; + int nj = j + d[k+1]; + if(ni>=0 && nj>=0 && ni>& cell) { + int l=0,r=cell.size()-1; + n = row; + m = col; + int day=0; + while(l<=r){ + int mid = (l+r)/2; + vector>v(row,vector(col,0)); + for(int i=0;i<=mid;i++){ + v[cell[i][0]-1][cell[i][1]-1]=1; + } + vector>vis(row,vector(col,0)); + bool ans=false; + for(int i=0;i1970. Last Day Where You Can Still Cross

Hard


There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.

+ +

Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).

+ +

You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).

+ +

Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.

+ +

 

+

Example 1:

+ +
Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
+Output: 2
+Explanation: The above image depicts how the matrix changes each day starting from day 0.
+The last day where it is possible to cross from top to bottom is on day 2.
+
+ +

Example 2:

+ +
Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
+Output: 1
+Explanation: The above image depicts how the matrix changes each day starting from day 0.
+The last day where it is possible to cross from top to bottom is on day 1.
+
+ +

Example 3:

+ +
Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]
+Output: 3
+Explanation: The above image depicts how the matrix changes each day starting from day 0.
+The last day where it is possible to cross from top to bottom is on day 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= row, col <= 2 * 104
  • +
  • 4 <= row * col <= 2 * 104
  • +
  • cells.length == row * col
  • +
  • 1 <= ri <= row
  • +
  • 1 <= ci <= col
  • +
  • All the values of cells are unique.
  • +
+
\ No newline at end of file diff --git a/1971-find-if-path-exists-in-graph/README.md b/1971-find-if-path-exists-in-graph/README.md new file mode 100644 index 00000000..d95edbe4 --- /dev/null +++ b/1971-find-if-path-exists-in-graph/README.md @@ -0,0 +1,37 @@ +

1971. Find if Path Exists in Graph

Easy


There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

+ +

You want to determine if there is a valid path that exists from vertex source to vertex destination.

+ +

Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
+Output: true
+Explanation: There are two paths from vertex 0 to vertex 2:
+- 0 → 1 → 2
+- 0 → 2
+
+ +

Example 2:

+ +
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
+Output: false
+Explanation: There is no path from vertex 0 to vertex 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 105
  • +
  • 0 <= edges.length <= 2 * 105
  • +
  • edges[i].length == 2
  • +
  • 0 <= ui, vi <= n - 1
  • +
  • ui != vi
  • +
  • 0 <= source, destination <= n - 1
  • +
  • There are no duplicate edges.
  • +
  • There are no self edges.
  • +
+
\ No newline at end of file diff --git a/1976-number-of-ways-to-arrive-at-destination/1976-number-of-ways-to-arrive-at-destination.cpp b/1976-number-of-ways-to-arrive-at-destination/1976-number-of-ways-to-arrive-at-destination.cpp new file mode 100644 index 00000000..f8b06a11 --- /dev/null +++ b/1976-number-of-ways-to-arrive-at-destination/1976-number-of-ways-to-arrive-at-destination.cpp @@ -0,0 +1,58 @@ +class Solution { + +private: + int mod = 1e9 + 7; + +public: + int countPaths(int n, vector>& roads) { + + vector> adj[n+1]; + + for(auto itr : roads) + { + adj[itr[0]].push_back({itr[1], itr[2]}); + adj[itr[1]].push_back({itr[0], itr[2]}); + } + + vector dist(n, 1e18), ways(n, 0); + + priority_queue, vector> , greater> > pq; + + dist[0] = 0; + + ways[0] = 1; + + pq.push({dist[0], 0}); + + while(!pq.empty()) + { + long long dis = pq.top().first; + long long node = pq.top(). second; + + pq.pop(); + + for(auto itr : adj[node]) + { + long long adjNode = itr.first; + long long adjDis = itr.second; + + if((long long)adjDis + dis < dist[adjNode]) + { + dist[adjNode] = adjDis + dis; + + pq.push({dist[adjNode], adjNode}); + + ways[adjNode] = ways[node]; + } + else if(adjDis + dis == dist[adjNode]) + { + ways[adjNode] = (ways[adjNode] + ways[node]) % mod; + } + } + } + + if(ways[n-1] == 1e18) + return 0; + return ways[n-1] % mod; + } +}; \ No newline at end of file diff --git a/1976-number-of-ways-to-arrive-at-destination/NOTES.md b/1976-number-of-ways-to-arrive-at-destination/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1976-number-of-ways-to-arrive-at-destination/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1980-find-unique-binary-string/1980-find-unique-binary-string.cpp b/1980-find-unique-binary-string/1980-find-unique-binary-string.cpp new file mode 100644 index 00000000..776c6783 --- /dev/null +++ b/1980-find-unique-binary-string/1980-find-unique-binary-string.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + + int n = nums.size(); + + for(int i = 0; i < n; ++i) + { + if(nums[0][i] = nums[i][i] == '0' ? '1' : '0'); + } + + return nums[0]; + } +}; \ No newline at end of file diff --git a/1980-find-unique-binary-string/NOTES.md b/1980-find-unique-binary-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1980-find-unique-binary-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1980-find-unique-binary-string/README.md b/1980-find-unique-binary-string/README.md new file mode 100644 index 00000000..8cdd0a25 --- /dev/null +++ b/1980-find-unique-binary-string/README.md @@ -0,0 +1,35 @@ +

1980. Find Unique Binary String

Medium


Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.

+ +

 

+

Example 1:

+ +
Input: nums = ["01","10"]
+Output: "11"
+Explanation: "11" does not appear in nums. "00" would also be correct.
+
+ +

Example 2:

+ +
Input: nums = ["00","01"]
+Output: "11"
+Explanation: "11" does not appear in nums. "10" would also be correct.
+
+ +

Example 3:

+ +
Input: nums = ["111","011","001"]
+Output: "101"
+Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 16
  • +
  • nums[i].length == n
  • +
  • nums[i] is either '0' or '1'.
  • +
  • All the strings of nums are unique.
  • +
+
\ No newline at end of file diff --git a/1985-find-the-kth-largest-integer-in-the-array/1985-find-the-kth-largest-integer-in-the-array.cpp b/1985-find-the-kth-largest-integer-in-the-array/1985-find-the-kth-largest-integer-in-the-array.cpp new file mode 100644 index 00000000..f551e82a --- /dev/null +++ b/1985-find-the-kth-largest-integer-in-the-array/1985-find-the-kth-largest-integer-in-the-array.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string kthLargestNumber(vector& nums, int k) { + + int n = nums.size(); + + sort(nums.begin(),nums.end(),[&](const auto &a, const auto &b){ + if(a.size() < b.size()) + return 1; + else if(a.size() == b.size()) + return a < b ? 1 : 0; + return 0; + }); + + return nums[n-k]; + + } +}; diff --git a/1985-find-the-kth-largest-integer-in-the-array/NOTES.md b/1985-find-the-kth-largest-integer-in-the-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1985-find-the-kth-largest-integer-in-the-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1992-find-all-groups-of-farmland/1992-find-all-groups-of-farmland.cpp b/1992-find-all-groups-of-farmland/1992-find-all-groups-of-farmland.cpp new file mode 100644 index 00000000..add477bd --- /dev/null +++ b/1992-find-all-groups-of-farmland/1992-find-all-groups-of-farmland.cpp @@ -0,0 +1,145 @@ +class DSU{ + private: + vector size, rank, parent; + public: + DSU(int n) + { + int N = n; + size.resize(N, 1); + rank.resize(N, 0); + parent.resize(N); + for(int i = 0; i < N; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + return u; + return parent[u] = findParent(parent[u]); + } + + void unionByRank(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(rank[parU] < rank[parV]) + { + parent[parU] = parV; + } + else if(rank[parU] > rank[parV]) + { + parent[parV] = parU; + } + else + { + parent[parV] = parU; + ++rank[parU]; + } + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else{ + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + vector> findFarmland(vector>& land) { + + int n = land.size(); + int m = land[0].size(); + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1, 0}; + + auto isValid = [&](int x, int y)->bool + { + return (x >= 0 and y >= 0 and x < n and y < m); + }; + + DSU dsu((n*m) + 1); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(land[i][j] == 1) + { + int node = (i * m) + j; + + for(int k = 0; k < 4; ++k) + { + int nx = dx[k] + i; + int ny = dy[k] + j; + + if(isValid(nx, ny) and land[nx][ny] == 1) + { + int adjNode = (nx * m) + ny; + + if(!dsu.isSame(node, adjNode)) + dsu.unionBySize(node, adjNode); + } + } + } + } + } + + map> mp; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(land[i][j] == 1) + { + int node = (i * m) + j; + int par = dsu.findParent(node); + + if(mp.find(par) == mp.end()) + { + mp[par] = {i, j, i, j}; + } + else + { + mp[par][2] = i; + mp[par][3] = j; + } + + } + } + } + + vector> res; + + for(auto&[_, vec] : mp) + res.push_back(vec); + + return res; + + } +}; \ No newline at end of file diff --git a/1992-find-all-groups-of-farmland/README.md b/1992-find-all-groups-of-farmland/README.md new file mode 100644 index 00000000..783ad402 --- /dev/null +++ b/1992-find-all-groups-of-farmland/README.md @@ -0,0 +1,45 @@ +

1992. Find All Groups of Farmland

Medium


You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.

+ +

To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.

+ +

land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].

+ +

Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: land = [[1,0,0],[0,1,1],[0,1,1]]
+Output: [[0,0,0,0],[1,1,2,2]]
+Explanation:
+The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].
+The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].
+
+ +

Example 2:

+ +
Input: land = [[1,1],[1,1]]
+Output: [[0,0,1,1]]
+Explanation:
+The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].
+
+ +

Example 3:

+ +
Input: land = [[0]]
+Output: []
+Explanation:
+There are no groups of farmland.
+
+ +

 

+

Constraints:

+ +
    +
  • m == land.length
  • +
  • n == land[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • land consists of only 0's and 1's.
  • +
  • Groups of farmland are rectangular in shape.
  • +
+
\ No newline at end of file diff --git a/2000-reverse-prefix-of-word/2000-reverse-prefix-of-word.cpp b/2000-reverse-prefix-of-word/2000-reverse-prefix-of-word.cpp new file mode 100644 index 00000000..b6cb4401 --- /dev/null +++ b/2000-reverse-prefix-of-word/2000-reverse-prefix-of-word.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + string reversePrefix(string word, char ch) { + + int n = word.size(); + string pref, ans; + bool isfound = false; + + for(int i = 0; i < n; ++i) + { + if(!isfound) + pref += word[i]; + else + ans += word[i]; + if(word[i] == ch) + isfound = true; + } + + if(!isfound) + return pref; + + reverse(pref.begin(), pref.end()); + + return pref + ans; + + } +}; \ No newline at end of file diff --git a/2000-reverse-prefix-of-word/NOTES.md b/2000-reverse-prefix-of-word/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2000-reverse-prefix-of-word/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2024-maximize-the-confusion-of-an-exam/2024-maximize-the-confusion-of-an-exam.cpp b/2024-maximize-the-confusion-of-an-exam/2024-maximize-the-confusion-of-an-exam.cpp new file mode 100644 index 00000000..6f15163f --- /dev/null +++ b/2024-maximize-the-confusion-of-an-exam/2024-maximize-the-confusion-of-an-exam.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maxConsecutiveAnswers(string answerKey, int k) { + + int i = 0, j = 0, n = answerKey.size(); + + int t = 0, f = 0, ans = 0; + + while(j < n) + { + if(answerKey[j] == 'T') + ++t; + if(answerKey[j] == 'F') + ++f; + + while(t > k and f > k) + { + if(answerKey[i] == 'T') + --t; + else + --f; + ++i; + } + + ans = max(ans, j - i + 1); + + ++j; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2024-maximize-the-confusion-of-an-exam/NOTES.md b/2024-maximize-the-confusion-of-an-exam/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2024-maximize-the-confusion-of-an-exam/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2024-maximize-the-confusion-of-an-exam/README.md b/2024-maximize-the-confusion-of-an-exam/README.md new file mode 100644 index 00000000..33a9157c --- /dev/null +++ b/2024-maximize-the-confusion-of-an-exam/README.md @@ -0,0 +1,47 @@ +

2024. Maximize the Confusion of an Exam

Medium


A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).

+ +

You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:

+ +
    +
  • Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').
  • +
+ +

Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.

+ +

 

+

Example 1:

+ +
Input: answerKey = "TTFF", k = 2
+Output: 4
+Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
+There are four consecutive 'T's.
+
+ +

Example 2:

+ +
Input: answerKey = "TFFT", k = 1
+Output: 3
+Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
+Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
+In both cases, there are three consecutive 'F's.
+
+ +

Example 3:

+ +
Input: answerKey = "TTFTTFTT", k = 1
+Output: 5
+Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
+Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". 
+In both cases, there are five consecutive 'T's.
+
+ +

 

+

Constraints:

+ +
    +
  • n == answerKey.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • answerKey[i] is either 'T' or 'F'
  • +
  • 1 <= k <= n
  • +
+
\ No newline at end of file diff --git a/2037-minimum-number-of-moves-to-seat-everyone/2037-minimum-number-of-moves-to-seat-everyone.cpp b/2037-minimum-number-of-moves-to-seat-everyone/2037-minimum-number-of-moves-to-seat-everyone.cpp new file mode 100644 index 00000000..ffdf2002 --- /dev/null +++ b/2037-minimum-number-of-moves-to-seat-everyone/2037-minimum-number-of-moves-to-seat-everyone.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minMovesToSeat(vector& seats, vector& students) { + + int n = seats.size(); + + sort(seats.begin(), seats.end()); + sort(students.begin(), students.end()); + + int moves = 0; + + for(int i = 0; i < n; ++i) + { + moves += abs(seats[i] - students[i]); + } + + return moves; + + } +}; \ No newline at end of file diff --git a/2037-minimum-number-of-moves-to-seat-everyone/NOTES.md b/2037-minimum-number-of-moves-to-seat-everyone/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2037-minimum-number-of-moves-to-seat-everyone/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2037-minimum-number-of-moves-to-seat-everyone/README.md b/2037-minimum-number-of-moves-to-seat-everyone/README.md new file mode 100644 index 00000000..04a8e685 --- /dev/null +++ b/2037-minimum-number-of-moves-to-seat-everyone/README.md @@ -0,0 +1,58 @@ +

2037. Minimum Number of Moves to Seat Everyone

Easy


There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.

+ +

You may perform the following move any number of times:

+ +
    +
  • Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)
  • +
+ +

Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.

+ +

Note that there may be multiple seats or students in the same position at the beginning.

+ +

 

+

Example 1:

+ +
Input: seats = [3,1,5], students = [2,7,4]
+Output: 4
+Explanation: The students are moved as follows:
+- The first student is moved from from position 2 to position 1 using 1 move.
+- The second student is moved from from position 7 to position 5 using 2 moves.
+- The third student is moved from from position 4 to position 3 using 1 move.
+In total, 1 + 2 + 1 = 4 moves were used.
+
+ +

Example 2:

+ +
Input: seats = [4,1,5,9], students = [1,3,2,6]
+Output: 7
+Explanation: The students are moved as follows:
+- The first student is not moved.
+- The second student is moved from from position 3 to position 4 using 1 move.
+- The third student is moved from from position 2 to position 5 using 3 moves.
+- The fourth student is moved from from position 6 to position 9 using 3 moves.
+In total, 0 + 1 + 3 + 3 = 7 moves were used.
+
+ +

Example 3:

+ +
Input: seats = [2,2,6,6], students = [1,3,2,6]
+Output: 4
+Explanation: Note that there are two seats at position 2 and two seats at position 6.
+The students are moved as follows:
+- The first student is moved from from position 1 to position 2 using 1 move.
+- The second student is moved from from position 3 to position 6 using 3 moves.
+- The third student is not moved.
+- The fourth student is not moved.
+In total, 1 + 3 + 0 + 0 = 4 moves were used.
+
+ +

 

+

Constraints:

+ +
    +
  • n == seats.length == students.length
  • +
  • 1 <= n <= 100
  • +
  • 1 <= seats[i], students[j] <= 100
  • +
+
\ No newline at end of file diff --git a/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp new file mode 100644 index 00000000..adbdb99b --- /dev/null +++ b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool winnerOfGame(string colors) { + + int n = colors.size(); + + int aliceMoves = 0, bobMoves = 0; + + for(int i = 1; i < n-1; ++i) + { + char prev = colors[i-1]; + char curr = colors[i]; + char next = colors[i+1]; + + if(prev == curr and curr == next) + { + if(curr == 'A') + ++aliceMoves; + else + ++bobMoves; + } + } + + return (aliceMoves >= bobMoves + 1 ? 1 : 0); + + } +}; \ No newline at end of file diff --git a/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/NOTES.md b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md new file mode 100644 index 00000000..a5034a96 --- /dev/null +++ b/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color/README.md @@ -0,0 +1,63 @@ +

2038. Remove Colored Pieces if Both Neighbors are the Same Color

Medium


There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.

+ +

Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.

+ +
    +
  • Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
  • +
  • Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
  • +
  • Alice and Bob cannot remove pieces from the edge of the line.
  • +
  • If a player cannot make a move on their turn, that player loses and the other player wins.
  • +
+ +

Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.

+ +

 

+

Example 1:

+ +
Input: colors = "AAABABB"
+Output: true
+Explanation:
+AAABABB -> AABABB
+Alice moves first.
+She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.
+
+Now it's Bob's turn.
+Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
+Thus, Alice wins, so return true.
+
+ +

Example 2:

+ +
Input: colors = "AA"
+Output: false
+Explanation:
+Alice has her turn first.
+There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
+Thus, Bob wins, so return false.
+
+ +

Example 3:

+ +
Input: colors = "ABBBBBBBAAA"
+Output: false
+Explanation:
+ABBBBBBBAAA -> ABBBBBBBAA
+Alice moves first.
+Her only option is to remove the second to last 'A' from the right.
+
+ABBBBBBBAA -> ABBBBBBAA
+Next is Bob's turn.
+He has many options for which 'B' piece to remove. He can pick any.
+
+On Alice's second turn, she has no more pieces that she can remove.
+Thus, Bob wins, so return false.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= colors.length <= 105
  • +
  • colors consists of only the letters 'A' and 'B'
  • +
+
\ No newline at end of file diff --git a/2045-second-minimum-time-to-reach-destination/2045-second-minimum-time-to-reach-destination.cpp b/2045-second-minimum-time-to-reach-destination/2045-second-minimum-time-to-reach-destination.cpp new file mode 100644 index 00000000..37b28c23 --- /dev/null +++ b/2045-second-minimum-time-to-reach-destination/2045-second-minimum-time-to-reach-destination.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int secondMinimum(int n, vector>& edges, int time, int change) { + + vector> dis (n); + for (int i=0;i adj[n]; + for (auto it:edges){ + adj[it[0]-1].push_back(it[1]-1); + adj[it[1]-1].push_back(it[0]-1); + } + + priority_queue , vector>, greater>> pq; + pq.push({0,0}); // time=0, node=0 + dis[0].pop(); + dis[0].push(0); + + while (pq.empty()==false){ + int dist=pq.top().first; + int node=pq.top().second; + pq.pop(); + int k=dist/change; + if (k%2==1) { + dist=dist+(change-dist%change); + } + + for (auto adjnode:adj[node]){ + int adjdis=dist+time; + + if (dis[adjnode].top()==1e8){ + dis[adjnode].pop(); + dis[adjnode].push(adjdis); + pq.push({adjdis,adjnode}); + } + else if (dis[adjnode].size()<2 && dis[adjnode].top()!= adjdis){ + dis[adjnode].push(adjdis); + pq.push({adjdis,adjnode}); + } + else { + if (dis[adjnode].top() > adjdis){ + dis[adjnode].pop(); + dis[adjnode].push(adjdis); + pq.push({adjdis,adjnode}); + } + } + } + } + + return dis[n-1].top(); + } +}; \ No newline at end of file diff --git a/2045-second-minimum-time-to-reach-destination/NOTES.md b/2045-second-minimum-time-to-reach-destination/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2045-second-minimum-time-to-reach-destination/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2053-kth-distinct-string-in-an-array/2053-kth-distinct-string-in-an-array.cpp b/2053-kth-distinct-string-in-an-array/2053-kth-distinct-string-in-an-array.cpp new file mode 100644 index 00000000..fa609201 --- /dev/null +++ b/2053-kth-distinct-string-in-an-array/2053-kth-distinct-string-in-an-array.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + string kthDistinct(vector& arr, int k) { + + map mp; + vector vec; + + for(auto& str : arr) + ++mp[str]; + + for(auto& str : arr) + { + if(mp[str] == 1) + { + vec.push_back(str); + } + } + + return (vec.size() < k ? "" : vec[k-1]); + + } +}; \ No newline at end of file diff --git a/2053-kth-distinct-string-in-an-array/NOTES.md b/2053-kth-distinct-string-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2053-kth-distinct-string-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2053-kth-distinct-string-in-an-array/README.md b/2053-kth-distinct-string-in-an-array/README.md new file mode 100644 index 00000000..30e7edf5 --- /dev/null +++ b/2053-kth-distinct-string-in-an-array/README.md @@ -0,0 +1,43 @@ +

2053. Kth Distinct String in an Array

Easy


A distinct string is a string that is present only once in an array.

+ +

Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".

+ +

Note that the strings are considered in the order in which they appear in the array.

+ +

 

+

Example 1:

+ +
Input: arr = ["d","b","c","b","c","a"], k = 2
+Output: "a"
+Explanation:
+The only distinct strings in arr are "d" and "a".
+"d" appears 1st, so it is the 1st distinct string.
+"a" appears 2nd, so it is the 2nd distinct string.
+Since k == 2, "a" is returned. 
+
+ +

Example 2:

+ +
Input: arr = ["aaa","aa","a"], k = 1
+Output: "aaa"
+Explanation:
+All strings in arr are distinct, so the 1st string "aaa" is returned.
+
+ +

Example 3:

+ +
Input: arr = ["a","b","a"], k = 3
+Output: ""
+Explanation:
+The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= arr.length <= 1000
  • +
  • 1 <= arr[i].length <= 5
  • +
  • arr[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.cpp b/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.cpp new file mode 100644 index 00000000..5e5ca5a6 --- /dev/null +++ b/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points.cpp @@ -0,0 +1,49 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + vector nodesBetweenCriticalPoints(ListNode* head) { + + ListNode* prev = nullptr; + + int leftEnd = -1, nearestEnd = -1; + int minDist = INT_MAX, maxDist = INT_MIN; + int pos = 1; + + while(head) + { + if(head->next and prev) + { + if((prev->val < head->val and head->next->val < head->val) or (prev->val > head->val and head->next->val > head->val)) + { + if(leftEnd == -1) + { + leftEnd = pos; + nearestEnd = pos; + } + else + { + minDist = min(minDist, pos - nearestEnd); + maxDist = max(maxDist, pos - leftEnd); + nearestEnd = pos; + } + } + } + prev = head; + head = head->next; + ++pos; + } + + if(minDist == INT_MAX or maxDist == INT_MIN) + return {-1, -1}; + return {minDist, maxDist}; + } +}; \ No newline at end of file diff --git a/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/NOTES.md b/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2063-vowels-of-all-substrings/2063-vowels-of-all-substrings.cpp b/2063-vowels-of-all-substrings/2063-vowels-of-all-substrings.cpp new file mode 100644 index 00000000..4d878b50 --- /dev/null +++ b/2063-vowels-of-all-substrings/2063-vowels-of-all-substrings.cpp @@ -0,0 +1,19 @@ +#define ll long long int +class Solution { +public: + long long countVowels(string word) { + + // char at i will appear in (i+1) * (size - i) substrings + + ll n = word.size(), ans = 0; + + vector count = {1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0}; + + for(int i = 0 ; i < n; ++i){ + ans += count[word[i] - 'a'] * (i+1) * (n-i); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2063-vowels-of-all-substrings/README.md b/2063-vowels-of-all-substrings/README.md new file mode 100644 index 00000000..f4081a44 --- /dev/null +++ b/2063-vowels-of-all-substrings/README.md @@ -0,0 +1,45 @@ +

2063. Vowels of All Substrings

Medium


Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.

+ +

A substring is a contiguous (non-empty) sequence of characters within a string.

+ +

Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.

+ +

 

+

Example 1:

+ +
Input: word = "aba"
+Output: 6
+Explanation: 
+All possible substrings are: "a", "ab", "aba", "b", "ba", and "a".
+- "b" has 0 vowels in it
+- "a", "ab", "ba", and "a" have 1 vowel each
+- "aba" has 2 vowels in it
+Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. 
+
+ +

Example 2:

+ +
Input: word = "abc"
+Output: 3
+Explanation: 
+All possible substrings are: "a", "ab", "abc", "b", "bc", and "c".
+- "a", "ab", and "abc" have 1 vowel each
+- "b", "bc", and "c" have 0 vowels each
+Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.
+
+ +

Example 3:

+ +
Input: word = "ltcd"
+Output: 0
+Explanation: There are no vowels in any substring of "ltcd".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 105
  • +
  • word consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2073-time-needed-to-buy-tickets/2073-time-needed-to-buy-tickets.cpp b/2073-time-needed-to-buy-tickets/2073-time-needed-to-buy-tickets.cpp new file mode 100644 index 00000000..3f1fb25d --- /dev/null +++ b/2073-time-needed-to-buy-tickets/2073-time-needed-to-buy-tickets.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int timeRequiredToBuy(vector& tickets, int k) { + + int n = tickets.size(); + int time = 0; + + for(int i = 0; i < n; ++i) + { + if(i <= k) + { + time += (tickets[i] <= tickets[k] ? tickets[i] : tickets[k]); + } + else + { + time += (tickets[i] < tickets[k] ? tickets[i] : max(0, tickets[k] - 1)); + } + } + + return time; + } +}; \ No newline at end of file diff --git a/2073-time-needed-to-buy-tickets/NOTES.md b/2073-time-needed-to-buy-tickets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2073-time-needed-to-buy-tickets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2073-time-needed-to-buy-tickets/README.md b/2073-time-needed-to-buy-tickets/README.md new file mode 100644 index 00000000..5c998ffc --- /dev/null +++ b/2073-time-needed-to-buy-tickets/README.md @@ -0,0 +1,39 @@ +

2073. Time Needed to Buy Tickets

Easy


There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.

+ +

You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].

+ +

Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.

+ +

Return the time taken for the person at position k (0-indexed) to finish buying tickets.

+ +

 

+

Example 1:

+ +
Input: tickets = [2,3,2], k = 2
+Output: 6
+Explanation: 
+- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
+- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
+The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
+
+ +

Example 2:

+ +
Input: tickets = [5,1,1,1], k = 0
+Output: 8
+Explanation:
+- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
+- In the next 4 passes, only the person in position 0 is buying tickets.
+The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
+
+ +

 

+

Constraints:

+ +
    +
  • n == tickets.length
  • +
  • 1 <= n <= 100
  • +
  • 1 <= tickets[i] <= 100
  • +
  • 0 <= k < n
  • +
+
\ No newline at end of file diff --git a/2090-k-radius-subarray-averages/2090-k-radius-subarray-averages.cpp b/2090-k-radius-subarray-averages/2090-k-radius-subarray-averages.cpp new file mode 100644 index 00000000..38568f27 --- /dev/null +++ b/2090-k-radius-subarray-averages/2090-k-radius-subarray-averages.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector getAverages(vector& nums, int k) { + + int win = 2 * k + 1; + + int i = 0, j = 0, n = nums.size(); + + vector ans(n, -1); + + long long sum = 0; + + while(j < n) + { + sum += nums[j]; + + if(j - i + 1 == win) + { + ans[j-k] = sum/win; + + sum -= nums[i++]; + } + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2090-k-radius-subarray-averages/NOTES.md b/2090-k-radius-subarray-averages/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2090-k-radius-subarray-averages/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2090-k-radius-subarray-averages/README.md b/2090-k-radius-subarray-averages/README.md new file mode 100644 index 00000000..53f12651 --- /dev/null +++ b/2090-k-radius-subarray-averages/README.md @@ -0,0 +1,52 @@ +

2090. K Radius Subarray Averages

Medium


You are given a 0-indexed array nums of n integers, and an integer k.

+ +

The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1.

+ +

Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.

+ +

The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.

+ +
    +
  • For example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [7,4,3,9,1,8,5,2,6], k = 3
+Output: [-1,-1,-1,5,4,4,-1,-1,-1]
+Explanation:
+- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.
+- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.
+  Using integer division, avg[3] = 37 / 7 = 5.
+- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.
+- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.
+- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.
+
+ +

Example 2:

+ +
Input: nums = [100000], k = 0
+Output: [100000]
+Explanation:
+- The sum of the subarray centered at index 0 with radius 0 is: 100000.
+  avg[0] = 100000 / 1 = 100000.
+
+ +

Example 3:

+ +
Input: nums = [8], k = 100000
+Output: [-1]
+Explanation: 
+- avg[0] is -1 because there are less than k elements before and after index 0.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= nums[i], k <= 105
  • +
+
\ No newline at end of file diff --git a/2091-removing-minimum-and-maximum-from-array/2091-removing-minimum-and-maximum-from-array.cpp b/2091-removing-minimum-and-maximum-from-array/2091-removing-minimum-and-maximum-from-array.cpp new file mode 100644 index 00000000..6b4b650e --- /dev/null +++ b/2091-removing-minimum-and-maximum-from-array/2091-removing-minimum-and-maximum-from-array.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minimumDeletions(vector& nums) { + + int n = nums.size(); + + int minIdx = min_element(nums.begin(), nums.end()) - nums.begin(); + int maxIdx = max_element(nums.begin(), nums.end()) - nums.begin(); + + int fromFirst = max(minIdx, maxIdx) + 1; + + int fromLast = n - min(minIdx, maxIdx); + + int bothSide = min(minIdx, maxIdx) + 1 + n - max(minIdx, maxIdx); + + // cout<2091. Removing Minimum and Maximum From Array

Medium


You are given a 0-indexed array of distinct integers nums.

+ +

There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.

+ +

A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.

+ +

Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.

+ +

 

+

Example 1:

+ +
Input: nums = [2,10,7,5,4,1,8,6]
+Output: 5
+Explanation: 
+The minimum element in the array is nums[5], which is 1.
+The maximum element in the array is nums[1], which is 10.
+We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.
+This results in 2 + 3 = 5 deletions, which is the minimum number possible.
+
+ +

Example 2:

+ +
Input: nums = [0,-4,19,1,8,-2,-3,5]
+Output: 3
+Explanation: 
+The minimum element in the array is nums[1], which is -4.
+The maximum element in the array is nums[2], which is 19.
+We can remove both the minimum and maximum by removing 3 elements from the front.
+This results in only 3 deletions, which is the minimum number possible.
+
+ +

Example 3:

+ +
Input: nums = [101]
+Output: 1
+Explanation:  
+There is only one element in the array, which makes it both the minimum and maximum element.
+We can remove it with 1 deletion.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -105 <= nums[i] <= 105
  • +
  • The integers in nums are distinct.
  • +
+
\ No newline at end of file diff --git a/2092-find-all-people-with-secret/2092-find-all-people-with-secret.cpp b/2092-find-all-people-with-secret/2092-find-all-people-with-secret.cpp new file mode 100644 index 00000000..a5443361 --- /dev/null +++ b/2092-find-all-people-with-secret/2092-find-all-people-with-secret.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + vector findAllPeople(int n, vector>& meetings, int firstPerson) { + + vector> adj[n+1]; + + int currTime = 0; + + for(auto& meet : meetings) + { + int person1 = meet[0]; + int person2 = meet[1]; + int meetingTime = meet[2]; + + adj[person1].push_back({person2, meetingTime}); + adj[person2].push_back({person1, meetingTime}); + } + + priority_queue, vector>, greater>> q; // currTime node + + vector visited(n+1, false); + + vector ans; + + q.push({0, 0}); + q.push({0, firstPerson}); + + while(!q.empty()) + { + int currTime = q.top().first; + int person1 = q.top().second; + + q.pop(); + + if(visited[person1]) + continue; + + visited[person1] = true; + + for(auto& meets : adj[person1]) + { + int person2 = meets.first; + int meetingTime = meets.second; + + if(!visited[person2] and currTime <= meetingTime) + { + q.push({meetingTime, person2}); + } + } + } + + for(int i = 0; i < n; ++i) + { + if(visited[i]) + ans.push_back(i); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2092-find-all-people-with-secret/NOTES.md b/2092-find-all-people-with-secret/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2092-find-all-people-with-secret/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2092-find-all-people-with-secret/README.md b/2092-find-all-people-with-secret/README.md new file mode 100644 index 00000000..3a4f6ecb --- /dev/null +++ b/2092-find-all-people-with-secret/README.md @@ -0,0 +1,57 @@ +

2092. Find All People With Secret

Hard


You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson.

+ +

Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa.

+ +

The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.

+ +

Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1
+Output: [0,1,2,3,5]
+Explanation:
+At time 0, person 0 shares the secret with person 1.
+At time 5, person 1 shares the secret with person 2.
+At time 8, person 2 shares the secret with person 3.
+At time 10, person 1 shares the secret with person 5.​​​​
+Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.
+
+ +

Example 2:

+ +
Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3
+Output: [0,1,3]
+Explanation:
+At time 0, person 0 shares the secret with person 3.
+At time 2, neither person 1 nor person 2 know the secret.
+At time 3, person 3 shares the secret with person 0 and person 1.
+Thus, people 0, 1, and 3 know the secret after all the meetings.
+
+ +

Example 3:

+ +
Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1
+Output: [0,1,2,3,4]
+Explanation:
+At time 0, person 0 shares the secret with person 1.
+At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.
+Note that person 2 can share the secret at the same time as receiving it.
+At time 2, person 3 shares the secret with person 4.
+Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 105
  • +
  • 1 <= meetings.length <= 105
  • +
  • meetings[i].length == 3
  • +
  • 0 <= xi, yi <= n - 1
  • +
  • xi != yi
  • +
  • 1 <= timei <= 105
  • +
  • 1 <= firstPerson <= n - 1
  • +
+
\ No newline at end of file diff --git a/2096-step-by-step-directions-from-a-binary-tree-node-to-another/2096-step-by-step-directions-from-a-binary-tree-node-to-another.cpp b/2096-step-by-step-directions-from-a-binary-tree-node-to-another/2096-step-by-step-directions-from-a-binary-tree-node-to-another.cpp new file mode 100644 index 00000000..54cbc44b --- /dev/null +++ b/2096-step-by-step-directions-from-a-binary-tree-node-to-another/2096-step-by-step-directions-from-a-binary-tree-node-to-another.cpp @@ -0,0 +1,56 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + +private: + void rootToNode(TreeNode* root,int &n,int &m,string &temp,string &s,string &d){ + if(!root) return; + + if(root->val == n) s=temp; + if(root->val == m) d=temp; + + temp.push_back('L'); + rootToNode(root->left, n, m, temp, s, d); + temp.pop_back(); + + temp.push_back('R'); + rootToNode(root->right, n, m, temp, s, d); + temp.pop_back(); + } + + +public: + string getDirections(TreeNode* root, int n, int m) { + + string s,d,temp; + rootToNode(root,n,m,temp,s,d); + + int ind = 0; + + for(int i=0;i2096. Step-By-Step Directions From a Binary Tree Node to Another

Medium


You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.

+ +

Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction:

+ +
    +
  • 'L' means to go from a node to its left child node.
  • +
  • 'R' means to go from a node to its right child node.
  • +
  • 'U' means to go from a node to its parent node.
  • +
+ +

Return the step-by-step directions of the shortest path from node s to node t.

+ +

 

+

Example 1:

+ +
Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
+Output: "UURL"
+Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6.
+
+ +

Example 2:

+ +
Input: root = [2,1], startValue = 2, destValue = 1
+Output: "L"
+Explanation: The shortest path is: 2 → 1.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is n.
  • +
  • 2 <= n <= 105
  • +
  • 1 <= Node.val <= n
  • +
  • All the values in the tree are unique.
  • +
  • 1 <= startValue, destValue <= n
  • +
  • startValue != destValue
  • +
+
\ No newline at end of file diff --git a/2101-detonate-the-maximum-bombs/2101-detonate-the-maximum-bombs.cpp b/2101-detonate-the-maximum-bombs/2101-detonate-the-maximum-bombs.cpp new file mode 100644 index 00000000..d8a33911 --- /dev/null +++ b/2101-detonate-the-maximum-bombs/2101-detonate-the-maximum-bombs.cpp @@ -0,0 +1,67 @@ +#define ll long long int + +class Solution { + +private: + void dfs(int sv, vector adj[], vector& visited, ll& c) + { + visited[sv] = true; + + ++c; + + for(auto itr : adj[sv]) + { + if(!visited[itr]) + dfs(itr, adj, visited, c); + } + } + +public: + int maximumDetonation(vector>& bombs) { + + int n = bombs.size(); + + vector adj[n]; + + for(int i = 0; i < n; ++i) + { + ll x1 = bombs[i][0]; + ll y1 = bombs[i][1]; + ll rad = bombs[i][2]; + + for(int j = 0; j < n; ++j) + { + if(i != j) + { + ll x2 = bombs[j][0]; + ll y2 = bombs[j][1]; + + + ll x = abs(x1 - x2); + ll y = abs(y1 - y2); + + if((x*x) + (y*y) <= (rad*rad)) + { + adj[i].push_back(j); + } + } + } + } + + ll ans = 0; + + for(int i = 0; i < n; ++i) + { + vector visited(n, false); + + ll c = 0; + + dfs(i, adj, visited, c); + + ans = max(ans, c); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2101-detonate-the-maximum-bombs/NOTES.md b/2101-detonate-the-maximum-bombs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2101-detonate-the-maximum-bombs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2101-detonate-the-maximum-bombs/README.md b/2101-detonate-the-maximum-bombs/README.md new file mode 100644 index 00000000..3cf611be --- /dev/null +++ b/2101-detonate-the-maximum-bombs/README.md @@ -0,0 +1,49 @@ +

2101. Detonate the Maximum Bombs

Medium


You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.

+ +

The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.

+ +

You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.

+ +

Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.

+ +

 

+

Example 1:

+ +
Input: bombs = [[2,1,3],[6,1,4]]
+Output: 2
+Explanation:
+The above figure shows the positions and ranges of the 2 bombs.
+If we detonate the left bomb, the right bomb will not be affected.
+But if we detonate the right bomb, both bombs will be detonated.
+So the maximum bombs that can be detonated is max(1, 2) = 2.
+
+ +

Example 2:

+ +
Input: bombs = [[1,1,5],[10,10,5]]
+Output: 1
+Explanation:
+Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.
+
+ +

Example 3:

+ +
Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]
+Output: 5
+Explanation:
+The best bomb to detonate is bomb 0 because:
+- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.
+- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.
+- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.
+Thus all 5 bombs are detonated.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bombs.length <= 100
  • +
  • bombs[i].length == 3
  • +
  • 1 <= xi, yi, ri <= 105
  • +
+
\ No newline at end of file diff --git a/2108-find-first-palindromic-string-in-the-array/2108-find-first-palindromic-string-in-the-array.cpp b/2108-find-first-palindromic-string-in-the-array/2108-find-first-palindromic-string-in-the-array.cpp new file mode 100644 index 00000000..51c0d7d2 --- /dev/null +++ b/2108-find-first-palindromic-string-in-the-array/2108-find-first-palindromic-string-in-the-array.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + string firstPalindrome(vector& words) { + + for(auto& word : words) + { + int i = 0, j = word.size()-1; + bool ok = true; + + while(i < j) + { + if(word[i] != word[j]) + { + ok = false; + break; + } + ++i, --j; + } + + if(ok) return word; + } + + return ""; + } +}; \ No newline at end of file diff --git a/2108-find-first-palindromic-string-in-the-array/README.md b/2108-find-first-palindromic-string-in-the-array/README.md new file mode 100644 index 00000000..cdaba2f0 --- /dev/null +++ b/2108-find-first-palindromic-string-in-the-array/README.md @@ -0,0 +1,36 @@ +

2108. Find First Palindromic String in the Array

Easy


Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

+ +

A string is palindromic if it reads the same forward and backward.

+ +

 

+

Example 1:

+ +
Input: words = ["abc","car","ada","racecar","cool"]
+Output: "ada"
+Explanation: The first string that is palindromic is "ada".
+Note that "racecar" is also palindromic, but it is not the first.
+
+ +

Example 2:

+ +
Input: words = ["notapalindrome","racecar"]
+Output: "racecar"
+Explanation: The first and only string that is palindromic is "racecar".
+
+ +

Example 3:

+ +
Input: words = ["def","ghi"]
+Output: ""
+Explanation: There are no palindromic strings, so the empty string is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp b/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp new file mode 100644 index 00000000..371b3993 --- /dev/null +++ b/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int numberOfBeams(vector& bank) { + + int n = bank.size(); + + int ans = 0, i = 0; + + while(i < n) + { + int cnt = count(bank[i].begin(), bank[i].end(), '1'); + + int j = i+1; + + while(j < n) + { + int cnt2 = count(bank[j].begin(), bank[j].end(), '1'); + + if(cnt2 >= 1) + { + ans += (cnt * cnt2); + break; + } + ++j; + } + + i = j++; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2125-number-of-laser-beams-in-a-bank/NOTES.md b/2125-number-of-laser-beams-in-a-bank/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2125-number-of-laser-beams-in-a-bank/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2125-number-of-laser-beams-in-a-bank/README.md b/2125-number-of-laser-beams-in-a-bank/README.md new file mode 100644 index 00000000..6b3c5a3f --- /dev/null +++ b/2125-number-of-laser-beams-in-a-bank/README.md @@ -0,0 +1,48 @@ +

2125. Number of Laser Beams in a Bank

Medium


Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.

+ +

There is one laser beam between any two security devices if both conditions are met:

+ +
    +
  • The two devices are located on two different rows: r1 and r2, where r1 < r2.
  • +
  • For each row i where r1 < i < r2, there are no security devices in the ith row.
  • +
+ +

Laser beams are independent, i.e., one beam does not interfere nor join with another.

+ +

Return the total number of laser beams in the bank.

+ +

 

+

Example 1:

+ +
Input: bank = ["011001","000000","010100","001000"]
+Output: 8
+Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:
+ * bank[0][1] -- bank[2][1]
+ * bank[0][1] -- bank[2][3]
+ * bank[0][2] -- bank[2][1]
+ * bank[0][2] -- bank[2][3]
+ * bank[0][5] -- bank[2][1]
+ * bank[0][5] -- bank[2][3]
+ * bank[2][1] -- bank[3][2]
+ * bank[2][3] -- bank[3][2]
+Note that there is no beam between any device on the 0th row with any on the 3rd row.
+This is because the 2nd row contains security devices, which breaks the second condition.
+
+ +

Example 2:

+ +
Input: bank = ["000","111","000"]
+Output: 0
+Explanation: There does not exist two devices located on two different rows.
+
+ +

 

+

Constraints:

+ +
    +
  • m == bank.length
  • +
  • n == bank[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • bank[i][j] is either '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/2134-minimum-swaps-to-group-all-1s-together-ii/2134-minimum-swaps-to-group-all-1s-together-ii.cpp b/2134-minimum-swaps-to-group-all-1s-together-ii/2134-minimum-swaps-to-group-all-1s-together-ii.cpp new file mode 100644 index 00000000..276805cd --- /dev/null +++ b/2134-minimum-swaps-to-group-all-1s-together-ii/2134-minimum-swaps-to-group-all-1s-together-ii.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int minSwaps(vector& nums) { + + int n = nums.size(); + int cnt = 0; + + for(auto& ele : nums) + cnt += ele; + + for(int i = 0; i < n; ++i) + nums.push_back(nums[i]); + + int ans = INT_MAX, curCnt = 0, j = 0, i = 0; + + while(j < 2*n) + { + curCnt += nums[j]; + + if(j - i + 1 == cnt) + { + ans = min(ans, cnt - curCnt); + curCnt -= nums[i++]; + } + ++j; + } + + return ans == INT_MAX ? 0 : ans; + } +}; \ No newline at end of file diff --git a/2134-minimum-swaps-to-group-all-1s-together-ii/NOTES.md b/2134-minimum-swaps-to-group-all-1s-together-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2134-minimum-swaps-to-group-all-1s-together-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2134-minimum-swaps-to-group-all-1s-together-ii/README.md b/2134-minimum-swaps-to-group-all-1s-together-ii/README.md new file mode 100644 index 00000000..2c4dc53e --- /dev/null +++ b/2134-minimum-swaps-to-group-all-1s-together-ii/README.md @@ -0,0 +1,46 @@ +

2134. Minimum Swaps to Group All 1's Together II

Medium


A swap is defined as taking two distinct positions in an array and swapping the values in them.

+ +

A circular array is defined as an array where we consider the first element and the last element to be adjacent.

+ +

Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.

+ +

 

+

Example 1:

+ +
Input: nums = [0,1,0,1,1,0,0]
+Output: 1
+Explanation: Here are a few of the ways to group all the 1's together:
+[0,0,1,1,1,0,0] using 1 swap.
+[0,1,1,1,0,0,0] using 1 swap.
+[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).
+There is no way to group all 1's together with 0 swaps.
+Thus, the minimum number of swaps required is 1.
+
+ +

Example 2:

+ +
Input: nums = [0,1,1,1,0,0,1,1,0]
+Output: 2
+Explanation: Here are a few of the ways to group all the 1's together:
+[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).
+[1,1,1,1,1,0,0,0,0] using 2 swaps.
+There is no way to group all 1's together with 0 or 1 swaps.
+Thus, the minimum number of swaps required is 2.
+
+ +

Example 3:

+ +
Input: nums = [1,1,0,0,1]
+Output: 0
+Explanation: All the 1's are already grouped together due to the circular property of the array.
+Thus, the minimum number of swaps required is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/2140-solving-questions-with-brainpower/2140-solving-questions-with-brainpower.cpp b/2140-solving-questions-with-brainpower/2140-solving-questions-with-brainpower.cpp new file mode 100644 index 00000000..df489838 --- /dev/null +++ b/2140-solving-questions-with-brainpower/2140-solving-questions-with-brainpower.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + + long long helper(int i, int n, vector>& questions, vector& dp) + { + if(i >= n) + return 0; + + if(dp[i] != -1) + return dp[i]; + + long long sum = 0; + + long long take = questions[i][0] + helper(i + questions[i][1] + 1, n, questions, dp); + + long long notTake = helper(i+1, n, questions, dp); + + return dp[i] = max(take , notTake); + } + + long long mostPoints(vector>& questions) { + + int n = questions.size(); + + vector dp(n+1, -1); + + return helper(0, n, questions, dp); + + } +}; \ No newline at end of file diff --git a/2140-solving-questions-with-brainpower/README.md b/2140-solving-questions-with-brainpower/README.md new file mode 100644 index 00000000..f93585af --- /dev/null +++ b/2140-solving-questions-with-brainpower/README.md @@ -0,0 +1,49 @@ +

2140. Solving Questions With Brainpower

Medium


You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].

+ +

The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question.

+ +
    +
  • For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]: + +
      +
    • If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2.
    • +
    • If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3.
    • +
    +
  • +
+ +

Return the maximum points you can earn for the exam.

+ +

 

+

Example 1:

+ +
Input: questions = [[3,2],[4,3],[4,4],[2,5]]
+Output: 5
+Explanation: The maximum points can be earned by solving questions 0 and 3.
+- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions
+- Unable to solve questions 1 and 2
+- Solve question 3: Earn 2 points
+Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.
+
+ +

Example 2:

+ +
Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]
+Output: 7
+Explanation: The maximum points can be earned by solving questions 1 and 4.
+- Skip question 0
+- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions
+- Unable to solve questions 2 and 3
+- Solve question 4: Earn 5 points
+Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= questions.length <= 105
  • +
  • questions[i].length == 2
  • +
  • 1 <= pointsi, brainpoweri <= 105
  • +
+
\ No newline at end of file diff --git a/2141-maximum-running-time-of-n-computers/2141-maximum-running-time-of-n-computers.cpp b/2141-maximum-running-time-of-n-computers/2141-maximum-running-time-of-n-computers.cpp new file mode 100644 index 00000000..a6e3efc9 --- /dev/null +++ b/2141-maximum-running-time-of-n-computers/2141-maximum-running-time-of-n-computers.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + bool isPossible(vector& batteries, long long time, int computers){ + long long totTime = time*computers; + + for(long long bTime : batteries) + totTime -= min(time, bTime); + + return (totTime <= 0); + } + long long maxRunTime(int n, vector& batteries) { + long long low = 0, high = 0; + int si = batteries.size(); + + for(int i = 0; i < si; i++){ + high += batteries[i]; + } + + long long ans = 0; + while(low <= high){ + + long long mid = low + (high-low)/2; + + if(isPossible(batteries, mid, n)){ + ans = mid; + low = mid+1; + } + else{ + high = mid-1; + } + } + + return ans; + } + +}; \ No newline at end of file diff --git a/2141-maximum-running-time-of-n-computers/NOTES.md b/2141-maximum-running-time-of-n-computers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2141-maximum-running-time-of-n-computers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp b/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp new file mode 100644 index 00000000..156fbe4d --- /dev/null +++ b/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector rearrangeArray(vector& nums) { + + int n = nums.size(); + vector ans(n); + + int even = 0, odd = 1; + + for(int i = 0; i < n; ++i) + { + if(nums[i] < 0) + { + ans[odd] = nums[i]; + odd += 2; + } + else + { + ans[even] = nums[i]; + even += 2; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/2149-rearrange-array-elements-by-sign/NOTES.md b/2149-rearrange-array-elements-by-sign/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2149-rearrange-array-elements-by-sign/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2149-rearrange-array-elements-by-sign/README.md b/2149-rearrange-array-elements-by-sign/README.md new file mode 100644 index 00000000..06869c95 --- /dev/null +++ b/2149-rearrange-array-elements-by-sign/README.md @@ -0,0 +1,42 @@ +

2149. Rearrange Array Elements by Sign

Medium


You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

+ +

You should rearrange the elements of nums such that the modified array follows the given conditions:

+ +
    +
  1. Every consecutive pair of integers have opposite signs.
  2. +
  3. For all integers with the same sign, the order in which they were present in nums is preserved.
  4. +
  5. The rearranged array begins with a positive integer.
  6. +
+ +

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,-2,-5,2,-4]
+Output: [3,-2,1,-5,2,-4]
+Explanation:
+The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
+The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
+Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  
+
+ +

Example 2:

+ +
Input: nums = [-1,1]
+Output: [1,-1]
+Explanation:
+1 is the only positive integer and -1 the only negative integer in nums.
+So nums is rearranged to [1,-1].
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 2 * 105
  • +
  • nums.length is even
  • +
  • 1 <= |nums[i]| <= 105
  • +
  • nums consists of equal number of positive and negative integers.
  • +
+
\ No newline at end of file diff --git a/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp b/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp new file mode 100644 index 00000000..26bc8244 --- /dev/null +++ b/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeNodes(ListNode* head) { + + ListNode* dummy = new ListNode(), *ptr = dummy; + + int curSum = 0; + + head = head->next; + + while(head) + { + curSum += head->val; + if(head->val == 0) + { + head->val = curSum; + ptr->next = head; + ptr = ptr->next; + curSum = 0 ; + } + head = head->next; + } + + ptr->next = nullptr; + + return dummy->next; + + } +}; \ No newline at end of file diff --git a/2181-merge-nodes-in-between-zeros/README.md b/2181-merge-nodes-in-between-zeros/README.md new file mode 100644 index 00000000..b70d21cf --- /dev/null +++ b/2181-merge-nodes-in-between-zeros/README.md @@ -0,0 +1,38 @@ +

2181. Merge Nodes in Between Zeros

Medium


You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.

+ +

For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.

+ +

Return the head of the modified linked list.

+ +

 

+

Example 1:

+ +
Input: head = [0,3,1,0,4,5,2,0]
+Output: [4,11]
+Explanation: 
+The above figure represents the given linked list. The modified list contains
+- The sum of the nodes marked in green: 3 + 1 = 4.
+- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
+
+ +

Example 2:

+ +
Input: head = [0,1,0,3,0,2,2,0]
+Output: [1,3,4]
+Explanation: 
+The above figure represents the given linked list. The modified list contains
+- The sum of the nodes marked in green: 1 = 1.
+- The sum of the nodes marked in red: 3 = 3.
+- The sum of the nodes marked in yellow: 2 + 2 = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [3, 2 * 105].
  • +
  • 0 <= Node.val <= 1000
  • +
  • There are no two consecutive nodes with Node.val == 0.
  • +
  • The beginning and end of the linked list have Node.val == 0.
  • +
+
\ No newline at end of file diff --git a/2187-minimum-time-to-complete-trips/2187-minimum-time-to-complete-trips.cpp b/2187-minimum-time-to-complete-trips/2187-minimum-time-to-complete-trips.cpp new file mode 100644 index 00000000..9f3978f2 --- /dev/null +++ b/2187-minimum-time-to-complete-trips/2187-minimum-time-to-complete-trips.cpp @@ -0,0 +1,38 @@ +#define ll long long int +class Solution { +public: + + ll check(vector& time, int totalTrips, ll mid) + { + ll ans = 0, n = time.size(); + for(int i =0 ; i& time, int totalTrips) { + + ll mini = *min_element(time.begin(),time.end()); + ll start = 0, end = (ll)(mini * totalTrips); // maxTime; + ll ans = end; + + + while(start <= end) + { + ll mid = start + (end - start)/2; + if(check(time,totalTrips,mid) >= totalTrips) + { + ans = mid; + end = mid-1; + } + else + start = mid + 1; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2187-minimum-time-to-complete-trips/NOTES.md b/2187-minimum-time-to-complete-trips/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2187-minimum-time-to-complete-trips/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2191-sort-the-jumbled-numbers/2191-sort-the-jumbled-numbers.cpp b/2191-sort-the-jumbled-numbers/2191-sort-the-jumbled-numbers.cpp new file mode 100644 index 00000000..1cc4d93d --- /dev/null +++ b/2191-sort-the-jumbled-numbers/2191-sort-the-jumbled-numbers.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector sortJumbled(vector& mapping, vector& nums) { + + map mp; + + for(int i = 0; i < mapping.size(); ++i) + mp[i+'0'] = mapping[i]+'0'; + + vector> vp; + + for(int i = 0; i < nums.size(); ++i) + { + string str = to_string(nums[i]); + for(int i = 0; i < str.size(); ++i) + str[i] = mp[str[i]]; + vp.push_back({stoi(str), i}); + } + + sort(vp.begin(), vp.end()); + + vector ans; + + for(auto&[f,e] : vp) + { + ans.push_back(nums[e]); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2191-sort-the-jumbled-numbers/README.md b/2191-sort-the-jumbled-numbers/README.md new file mode 100644 index 00000000..c230b1a8 --- /dev/null +++ b/2191-sort-the-jumbled-numbers/README.md @@ -0,0 +1,47 @@ +

2191. Sort the Jumbled Numbers

Medium


You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.

+ +

The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9.

+ +

You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.

+ +

Notes:

+ +
    +
  • Elements with the same mapped values should appear in the same relative order as in the input.
  • +
  • The elements of nums should only be sorted based on their mapped values and not be replaced by them.
  • +
+ +

 

+

Example 1:

+ +
Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]
+Output: [338,38,991]
+Explanation: 
+Map the number 991 as follows:
+1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.
+2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.
+Therefore, the mapped value of 991 is 669.
+338 maps to 007, or 7 after removing the leading zeros.
+38 maps to 07, which is also 7 after removing leading zeros.
+Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.
+Thus, the sorted array is [338,38,991].
+
+ +

Example 2:

+ +
Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]
+Output: [123,456,789]
+Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].
+
+ +

 

+

Constraints:

+ +
    +
  • mapping.length == 10
  • +
  • 0 <= mapping[i] <= 9
  • +
  • All the values of mapping[i] are unique.
  • +
  • 1 <= nums.length <= 3 * 104
  • +
  • 0 <= nums[i] < 109
  • +
+
\ No newline at end of file diff --git a/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.cpp b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.cpp new file mode 100644 index 00000000..f2780c4f --- /dev/null +++ b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + vector> getAncestors(int n, vector>& edges) { + + + vector adj[n]; + + for(auto& edge : edges) + { + int u = edge[0]; + int v = edge[1]; + + adj[v].push_back(u); + } + + vector> ans(n); + + vector visited(n, false); + + function dfs = [&](int sv, int idx) -> void{ + + visited[sv] = true; + + for(auto& node : adj[sv]) + { + if(!visited[node]) + { + ans[idx].push_back(node); + dfs(node, idx); + } + } + }; + + for(int i = 0; i < n; ++i) + { + dfs(i, i); + + fill(visited.begin(), visited.end(), false); + + sort(ans[i].begin(), ans[i].end()); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/NOTES.md b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/README.md b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/README.md new file mode 100644 index 00000000..8831f995 --- /dev/null +++ b/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/README.md @@ -0,0 +1,49 @@ +

2192. All Ancestors of a Node in a Directed Acyclic Graph

Medium


You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).

+ +

You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph.

+ +

Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order.

+ +

A node u is an ancestor of another node v if u can reach v via a set of edges.

+ +

 

+

Example 1:

+ +
Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
+Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
+Explanation:
+The above diagram represents the input graph.
+- Nodes 0, 1, and 2 do not have any ancestors.
+- Node 3 has two ancestors 0 and 1.
+- Node 4 has two ancestors 0 and 2.
+- Node 5 has three ancestors 0, 1, and 3.
+- Node 6 has five ancestors 0, 1, 2, 3, and 4.
+- Node 7 has four ancestors 0, 1, 2, and 3.
+
+ +

Example 2:

+ +
Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
+Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]
+Explanation:
+The above diagram represents the input graph.
+- Node 0 does not have any ancestor.
+- Node 1 has one ancestor 0.
+- Node 2 has two ancestors 0 and 1.
+- Node 3 has three ancestors 0, 1, and 2.
+- Node 4 has four ancestors 0, 1, 2, and 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
  • 0 <= edges.length <= min(2000, n * (n - 1) / 2)
  • +
  • edges[i].length == 2
  • +
  • 0 <= fromi, toi <= n - 1
  • +
  • fromi != toi
  • +
  • There are no duplicate edges.
  • +
  • The graph is directed and acyclic.
  • +
+
\ No newline at end of file diff --git a/2196-create-binary-tree-from-descriptions/2196-create-binary-tree-from-descriptions.cpp b/2196-create-binary-tree-from-descriptions/2196-create-binary-tree-from-descriptions.cpp new file mode 100644 index 00000000..ac310fa9 --- /dev/null +++ b/2196-create-binary-tree-from-descriptions/2196-create-binary-tree-from-descriptions.cpp @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* createBinaryTree(vector>& descriptions) { + TreeNode* map[100001] = {}; + bool child[100001] = {}; + for (auto& d : descriptions){ + if (map[d[0]] == nullptr) map[d[0]] = new TreeNode(d[0]); + TreeNode* node = (map[d[1]] == nullptr ? new TreeNode(d[1]) : map[d[1]]); + if (d[2]) + map[d[0]]->left = node; + else + map[d[0]]->right = node; + map[node->val] = node; + child[d[1]] = true; + } + for (auto& d : descriptions) + if (!child[d[0]]) + return map[d[0]]; + return nullptr; + } +}; \ No newline at end of file diff --git a/2196-create-binary-tree-from-descriptions/README.md b/2196-create-binary-tree-from-descriptions/README.md new file mode 100644 index 00000000..3d44829b --- /dev/null +++ b/2196-create-binary-tree-from-descriptions/README.md @@ -0,0 +1,39 @@ +

2196. Create Binary Tree From Descriptions

Medium


You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,

+ +
    +
  • If isLefti == 1, then childi is the left child of parenti.
  • +
  • If isLefti == 0, then childi is the right child of parenti.
  • +
+ +

Construct the binary tree described by descriptions and return its root.

+ +

The test cases will be generated such that the binary tree is valid.

+ +

 

+

Example 1:

+ +
Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
+Output: [50,20,80,15,17,19]
+Explanation: The root node is the node with value 50 since it has no parent.
+The resulting binary tree is shown in the diagram.
+
+ +

Example 2:

+ +
Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]]
+Output: [1,2,null,null,3,4]
+Explanation: The root node is the node with value 1 since it has no parent.
+The resulting binary tree is shown in the diagram.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= descriptions.length <= 104
  • +
  • descriptions[i].length == 3
  • +
  • 1 <= parenti, childi <= 105
  • +
  • 0 <= isLefti <= 1
  • +
  • The binary tree described by descriptions is valid.
  • +
+
\ No newline at end of file diff --git a/2218-maximum-value-of-k-coins-from-piles/2218-maximum-value-of-k-coins-from-piles.cpp b/2218-maximum-value-of-k-coins-from-piles/2218-maximum-value-of-k-coins-from-piles.cpp new file mode 100644 index 00000000..532b5af4 --- /dev/null +++ b/2218-maximum-value-of-k-coins-from-piles/2218-maximum-value-of-k-coins-from-piles.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + + int helper(int i, int n, vector>& piles, int k, vector>& dp) + { + if(i >= n or k == 0) + return 0; + + if(dp[i][k] != -1) + return dp[i][k]; + + int take = 0, notTake = 0; + int sum = 0; + int size = piles[i].size(); + + notTake = helper(i+1, n , piles, k, dp); + + for(int j = 0; j < min(k,size); ++j ) + { + sum += piles[i][j]; + take = max(take, sum + helper(i+1, n, piles, k-j-1, dp)); + } + + return dp[i][k] = max(take,notTake); + } + + int maxValueOfCoins(vector>& piles, int k) { + + int n = piles.size(); + vector> dp(n+1, vector(k+1,-1)); + return helper(0, n, piles, k, dp); + + } +}; \ No newline at end of file diff --git a/2218-maximum-value-of-k-coins-from-piles/NOTES.md b/2218-maximum-value-of-k-coins-from-piles/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2218-maximum-value-of-k-coins-from-piles/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2225-find-players-with-zero-or-one-losses/2225-find-players-with-zero-or-one-losses.cpp b/2225-find-players-with-zero-or-one-losses/2225-find-players-with-zero-or-one-losses.cpp new file mode 100644 index 00000000..106472ac --- /dev/null +++ b/2225-find-players-with-zero-or-one-losses/2225-find-players-with-zero-or-one-losses.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + vector> findWinners(vector>& matches) { + + vector not_lost, one_lost; + vector> ans; + map win, loss; + int n = matches.size(); + + for(int i = 0; i2225. Find Players With Zero or One Losses

Medium


You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.

+ +

Return a list answer of size 2 where:

+ +
    +
  • answer[0] is a list of all players that have not lost any matches.
  • +
  • answer[1] is a list of all players that have lost exactly one match.
  • +
+ +

The values in the two lists should be returned in increasing order.

+ +

Note:

+ +
    +
  • You should only consider the players that have played at least one match.
  • +
  • The testcases will be generated such that no two matches will have the same outcome.
  • +
+ +

 

+

Example 1:

+ +
Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
+Output: [[1,2,10],[4,5,7,8]]
+Explanation:
+Players 1, 2, and 10 have not lost any matches.
+Players 4, 5, 7, and 8 each have lost one match.
+Players 3, 6, and 9 each have lost two matches.
+Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
+
+ +

Example 2:

+ +
Input: matches = [[2,3],[1,3],[5,4],[6,4]]
+Output: [[1,2,5,6],[]]
+Explanation:
+Players 1, 2, 5, and 6 have not lost any matches.
+Players 3 and 4 each have lost two matches.
+Thus, answer[0] = [1,2,5,6] and answer[1] = [].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= matches.length <= 105
  • +
  • matches[i].length == 2
  • +
  • 1 <= winneri, loseri <= 105
  • +
  • winneri != loseri
  • +
  • All matches[i] are unique.
  • +
+
\ No newline at end of file diff --git a/2231-largest-number-after-digit-swaps-by-parity/2231-largest-number-after-digit-swaps-by-parity.cpp b/2231-largest-number-after-digit-swaps-by-parity/2231-largest-number-after-digit-swaps-by-parity.cpp new file mode 100644 index 00000000..299d4d95 --- /dev/null +++ b/2231-largest-number-after-digit-swaps-by-parity/2231-largest-number-after-digit-swaps-by-parity.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + + // atmost 2 + int largestInteger(int num) { + + int cnt = 0; + vector v, even, odd; + + while(num > 0) + { + v.push_back(num%10); + num /= 10; + } + + for(auto itr : v) + { + if(itr & 1) + odd.push_back(itr); + else + even.push_back(itr); + } + + reverse(v.begin(),v.end()); + sort(even.begin(),even.end(),greater()); + sort(odd.begin(),odd.end(),greater()); + + int k = 0, l = 0; + + string ans; + + for(auto itr : v) + { + if(itr & 1) + ans += to_string(odd[k++]); + else + ans += to_string(even[l++]); + } + + // cout<2231. Largest Number After Digit Swaps by Parity

Easy


You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).

+ +

Return the largest possible value of num after any number of swaps.

+ +

 

+

Example 1:

+ +
Input: num = 1234
+Output: 3412
+Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
+Swap the digit 2 with the digit 4, this results in the number 3412.
+Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
+Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
+
+ +

Example 2:

+ +
Input: num = 65875
+Output: 87655
+Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
+Swap the first digit 5 with the digit 7, this results in the number 87655.
+Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num <= 109
  • +
+
\ No newline at end of file diff --git a/2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.cpp b/2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.cpp new file mode 100644 index 00000000..8dee4506 --- /dev/null +++ b/2244-minimum-rounds-to-complete-all-tasks/2244-minimum-rounds-to-complete-all-tasks.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minimumRounds(vector& tasks) { + + unordered_map mp; + + int ans = 0; + + for(auto itr : tasks) + ++mp[itr]; + + for(auto itr : mp) + { + if(itr.second == 1) + return -1; + else if(itr.second % 3 == 0) + ans += itr.second/3; + else + ans += itr.second/3 + 1; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2244-minimum-rounds-to-complete-all-tasks/README.md b/2244-minimum-rounds-to-complete-all-tasks/README.md new file mode 100644 index 00000000..b1d05378 --- /dev/null +++ b/2244-minimum-rounds-to-complete-all-tasks/README.md @@ -0,0 +1,32 @@ +

2244. Minimum Rounds to Complete All Tasks

Medium


You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.

+ +

Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.

+ +

 

+

Example 1:

+ +
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
+Output: 4
+Explanation: To complete all the tasks, a possible plan is:
+- In the first round, you complete 3 tasks of difficulty level 2. 
+- In the second round, you complete 2 tasks of difficulty level 3. 
+- In the third round, you complete 3 tasks of difficulty level 4. 
+- In the fourth round, you complete 2 tasks of difficulty level 4.  
+It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
+
+ +

Example 2:

+ +
Input: tasks = [2,3,3]
+Output: -1
+Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tasks.length <= 105
  • +
  • 1 <= tasks[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2246-longest-path-with-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.cpp b/2246-longest-path-with-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.cpp new file mode 100644 index 00000000..bb3fc6f6 --- /dev/null +++ b/2246-longest-path-with-different-adjacent-characters/2246-longest-path-with-different-adjacent-characters.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + vector child[100001]; + int ans; + int dfs(string &s, int curr_node) + { + if(child[curr_node].empty())return 1; + int mx1 = 0, mx2 =0; + // traversing over all the child nodes of the curr_node + for(auto &child_node : child[curr_node]) + { + // recursively trying for child nodes + int len = dfs(s, child_node); + ans = max(ans , len); + // rejecting the current node if it's of same character + if(s[curr_node] == s[child_node])continue; + // updating the mx1 and mx2 paths that we can take from all the children of the given node + if(len > mx1) + { + mx2 = mx1; + mx1 = len; + } + //seecond max will be updated + else mx2 = max(mx2 , len); + } + // Update the result. + //Again, max1+mx2+1 means the length of the longest valid path + //going through this node in the sub-tree rooted at this node + ans = max(ans, 1 + mx1 + mx2); + //Adding 1 for the current node + return 1 + mx1; + } + int longestPath(vector& parent, string s){ + int n = parent.size(); + for(int i=1;i2246. Longest Path With Different Adjacent Characters

Hard


You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

+ +

You are also given a string s of length n, where s[i] is the character assigned to node i.

+ +

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

+ +

 

+

Example 1:

+ +
Input: parent = [-1,0,0,1,1,2], s = "abacbe"
+Output: 3
+Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
+It can be proven that there is no longer path that satisfies the conditions. 
+
+ +

Example 2:

+ +
Input: parent = [-1,0,0,0], s = "aabc"
+Output: 3
+Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • n == parent.length == s.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= parent[i] <= n - 1 for all i >= 1
  • +
  • parent[0] == -1
  • +
  • parent represents a valid tree.
  • +
  • s consists of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2251-number-of-flowers-in-full-bloom/2251-number-of-flowers-in-full-bloom.cpp b/2251-number-of-flowers-in-full-bloom/2251-number-of-flowers-in-full-bloom.cpp new file mode 100644 index 00000000..b4d8e152 --- /dev/null +++ b/2251-number-of-flowers-in-full-bloom/2251-number-of-flowers-in-full-bloom.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& persons) { + vector start, end; + for (auto& t : flowers) + start.push_back(t[0]), end.push_back(t[1]); + sort(start.begin(), start.end()); + sort(end.begin(), end.end()); + vector res; + for (int t : persons) { + int started = upper_bound(start.begin(), start.end(), t) - start.begin(); + int ended = lower_bound(end.begin(), end.end(), t) - end.begin(); + res.push_back(started - ended); + } + return res; + } +}; \ No newline at end of file diff --git a/2251-number-of-flowers-in-full-bloom/NOTES.md b/2251-number-of-flowers-in-full-bloom/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2251-number-of-flowers-in-full-bloom/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2251-number-of-flowers-in-full-bloom/README.md b/2251-number-of-flowers-in-full-bloom/README.md new file mode 100644 index 00000000..e6a39513 --- /dev/null +++ b/2251-number-of-flowers-in-full-bloom/README.md @@ -0,0 +1,32 @@ +

2251. Number of Flowers in Full Bloom

Hard


You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers.

+ +

Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.

+ +

 

+

Example 1:

+ +
Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11]
+Output: [1,2,2,2]
+Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
+For each person, we return the number of flowers in full bloom during their arrival.
+
+ +

Example 2:

+ +
Input: flowers = [[1,10],[3,3]], poeple = [3,3,2]
+Output: [2,2,1]
+Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.
+For each person, we return the number of flowers in full bloom during their arrival.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= flowers.length <= 5 * 104
  • +
  • flowers[i].length == 2
  • +
  • 1 <= starti <= endi <= 109
  • +
  • 1 <= people.length <= 5 * 104
  • +
  • 1 <= people[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2256-minimum-average-difference/2256-minimum-average-difference.cpp b/2256-minimum-average-difference/2256-minimum-average-difference.cpp new file mode 100644 index 00000000..0ce8d91b --- /dev/null +++ b/2256-minimum-average-difference/2256-minimum-average-difference.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minimumAverageDifference(vector& nums) { + + int n = nums.size(), ans = INT_MAX, idx; + + long long sumFromFront = 0, sumFromEnd = 0; + + for(auto itr : nums) + sumFromEnd += itr; + + for(int i= 0; i2256. Minimum Average Difference

Medium


You are given a 0-indexed integer array nums of length n.

+ +

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

+ +

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

+ +

Note:

+ +
    +
  • The absolute difference of two numbers is the absolute value of their difference.
  • +
  • The average of n elements is the sum of the n elements divided (integer division) by n.
  • +
  • The average of 0 elements is considered to be 0.
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [2,5,3,9,5,3]
+Output: 3
+Explanation:
+- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
+- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
+- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
+- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
+- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
+- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
+The average difference of index 3 is the minimum average difference so return 3.
+
+ +

Example 2:

+ +
Input: nums = [0]
+Output: 0
+Explanation:
+The only index is 0 so return 0.
+The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/2262-total-appeal-of-a-string/2262-total-appeal-of-a-string.cpp b/2262-total-appeal-of-a-string/2262-total-appeal-of-a-string.cpp new file mode 100644 index 00000000..5f5d6b36 --- /dev/null +++ b/2262-total-appeal-of-a-string/2262-total-appeal-of-a-string.cpp @@ -0,0 +1,21 @@ +#define ll long long int +class Solution { +public: + long long appealSum(string s) { + + ll ans = 0, n = s.size(); + vector prev(26,0); + + for(int i = 0; i < n; ++i) + { + // removig prev + ans += (i+1 - prev[s[i] - 'a']) * (n - i); + prev[s[i] - 'a'] = i+1; + } + + return ans; + + + } +}; + diff --git a/2262-total-appeal-of-a-string/NOTES.md b/2262-total-appeal-of-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2262-total-appeal-of-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2262-total-appeal-of-a-string/README.md b/2262-total-appeal-of-a-string/README.md new file mode 100644 index 00000000..36d55121 --- /dev/null +++ b/2262-total-appeal-of-a-string/README.md @@ -0,0 +1,44 @@ +

2262. Total Appeal of A String

Hard


The appeal of a string is the number of distinct characters found in the string.

+ +
    +
  • For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.
  • +
+ +

Given a string s, return the total appeal of all of its substrings.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "abbca"
+Output: 28
+Explanation: The following are the substrings of "abbca":
+- Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.
+- Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.
+- Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7.
+- Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6.
+- Substrings of length 5: "abbca" has an appeal of 3. The sum is 3.
+The total sum is 5 + 7 + 7 + 6 + 3 = 28.
+
+ +

Example 2:

+ +
Input: s = "code"
+Output: 20
+Explanation: The following are the substrings of "code":
+- Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.
+- Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6.
+- Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6.
+- Substrings of length 4: "code" has an appeal of 4. The sum is 4.
+The total sum is 4 + 6 + 6 + 4 = 20.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2264-largest-3-same-digit-number-in-string/2264-largest-3-same-digit-number-in-string.cpp b/2264-largest-3-same-digit-number-in-string/2264-largest-3-same-digit-number-in-string.cpp new file mode 100644 index 00000000..2dc69092 --- /dev/null +++ b/2264-largest-3-same-digit-number-in-string/2264-largest-3-same-digit-number-in-string.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + string largestGoodInteger(string num) { + + int n = num.size(); + + string ans; + + int i = 0, j = 0, k = 3; + + string curr; + + while(j < n) + { + curr += num[j]; + + if(curr.size() == 3) + { + if(j>=2 and num[j] == num[j-1] and num[j-1] == num[j-2]) + { + ans = max(ans, curr); + } + curr.erase(curr.begin()); + } + + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2264-largest-3-same-digit-number-in-string/NOTES.md b/2264-largest-3-same-digit-number-in-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2264-largest-3-same-digit-number-in-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2264-largest-3-same-digit-number-in-string/README.md b/2264-largest-3-same-digit-number-in-string/README.md new file mode 100644 index 00000000..6dfcc6a6 --- /dev/null +++ b/2264-largest-3-same-digit-number-in-string/README.md @@ -0,0 +1,47 @@ +

2264. Largest 3-Same-Digit Number in String

Easy


You are given a string num representing a large integer. An integer is good if it meets the following conditions:

+ +
    +
  • It is a substring of num with length 3.
  • +
  • It consists of only one unique digit.
  • +
+ +

Return the maximum good integer as a string or an empty string "" if no such integer exists.

+ +

Note:

+ +
    +
  • A substring is a contiguous sequence of characters within a string.
  • +
  • There may be leading zeroes in num or a good integer.
  • +
+ +

 

+

Example 1:

+ +
Input: num = "6777133339"
+Output: "777"
+Explanation: There are two distinct good integers: "777" and "333".
+"777" is the largest, so we return "777".
+
+ +

Example 2:

+ +
Input: num = "2300019"
+Output: "000"
+Explanation: "000" is the only good integer.
+
+ +

Example 3:

+ +
Input: num = "42352338"
+Output: ""
+Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= num.length <= 1000
  • +
  • num only consists of digits.
  • +
+
\ No newline at end of file diff --git a/2265-count-nodes-equal-to-average-of-subtree/2265-count-nodes-equal-to-average-of-subtree.cpp b/2265-count-nodes-equal-to-average-of-subtree/2265-count-nodes-equal-to-average-of-subtree.cpp new file mode 100644 index 00000000..19d7070b --- /dev/null +++ b/2265-count-nodes-equal-to-average-of-subtree/2265-count-nodes-equal-to-average-of-subtree.cpp @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + int ans = 0; + + pair helper(TreeNode* root) + { + if(!root) + { + return {0, 0}; + } + + auto left = helper(root->left); + auto right = helper(root->right); + + int sum = left.first + right.first + root->val; + int cnt = left.second + right.second + 1; + + // cout<val<<" " <val) + { + ++ans; + } + + return {sum, cnt}; + } + + int averageOfSubtree(TreeNode* root) { + + helper(root); + + return ans; + + } +}; \ No newline at end of file diff --git a/2265-count-nodes-equal-to-average-of-subtree/README.md b/2265-count-nodes-equal-to-average-of-subtree/README.md new file mode 100644 index 00000000..d9972242 --- /dev/null +++ b/2265-count-nodes-equal-to-average-of-subtree/README.md @@ -0,0 +1,37 @@ +

2265. Count Nodes Equal to Average of Subtree

Medium


Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.

+ +

Note:

+ +
    +
  • The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
  • +
  • A subtree of root is a tree consisting of root and all of its descendants.
  • +
+ +

 

+

Example 1:

+ +
Input: root = [4,8,5,0,1,null,6]
+Output: 5
+Explanation: 
+For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
+For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
+For the node with value 0: The average of its subtree is 0 / 1 = 0.
+For the node with value 1: The average of its subtree is 1 / 1 = 1.
+For the node with value 6: The average of its subtree is 6 / 1 = 6.
+
+ +

Example 2:

+ +
Input: root = [1]
+Output: 1
+Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 1000
  • +
+
\ No newline at end of file diff --git a/2272-substring-with-largest-variance/2272-substring-with-largest-variance.cpp b/2272-substring-with-largest-variance/2272-substring-with-largest-variance.cpp new file mode 100644 index 00000000..1b3624fb --- /dev/null +++ b/2272-substring-with-largest-variance/2272-substring-with-largest-variance.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int largestVariance(string s) { + int ans = 0; + vector freq(26); + for(auto& c:s){ + freq[c-'a']++; + } + for(char ch1='a';ch1<='z';ch1++){ + for(char ch2='a';ch2<='z';ch2++){ + if(ch1==ch2 or !freq[ch1-'a'] or !freq[ch2-'a']){ + continue; + } + for(int rev=1;rev<=2;rev++){ + int cnt1 = 0,cnt2 = 0; + for(auto& c:s){ + cnt1 += c==ch1; + cnt2 += c==ch2; + if(cnt10 and cnt2>0){ + ans = max(ans,cnt1-cnt2); + } + } + reverse(s.begin(),s.end()); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/2272-substring-with-largest-variance/NOTES.md b/2272-substring-with-largest-variance/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2272-substring-with-largest-variance/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2272-substring-with-largest-variance/README.md b/2272-substring-with-largest-variance/README.md new file mode 100644 index 00000000..d8050e50 --- /dev/null +++ b/2272-substring-with-largest-variance/README.md @@ -0,0 +1,36 @@ +

2272. Substring With Largest Variance

Hard


The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.

+ +

Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "aababbb"
+Output: 3
+Explanation:
+All possible variances along with their respective substrings are listed below:
+- Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb".
+- Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab".
+- Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb".
+- Variance 3 for substring "babbb".
+Since the largest possible variance is 3, we return it.
+
+ +

Example 2:

+ +
Input: s = "abcde"
+Output: 0
+Explanation:
+No letter occurs more than once in s, so the variance of every substring is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2279-maximum-bags-with-full-capacity-of-rocks/2279-maximum-bags-with-full-capacity-of-rocks.cpp b/2279-maximum-bags-with-full-capacity-of-rocks/2279-maximum-bags-with-full-capacity-of-rocks.cpp new file mode 100644 index 00000000..281227ff --- /dev/null +++ b/2279-maximum-bags-with-full-capacity-of-rocks/2279-maximum-bags-with-full-capacity-of-rocks.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maximumBags(vector& capacity, vector& rocks, int additionalRocks) { + + int n = capacity.size(), count = 0; + + for(int i = 0; i2279. Maximum Bags With Full Capacity of Rocks

Medium


You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.

+ +

Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.

+ +

 

+

Example 1:

+ +
Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2
+Output: 3
+Explanation:
+Place 1 rock in bag 0 and 1 rock in bag 1.
+The number of rocks in each bag are now [2,3,4,4].
+Bags 0, 1, and 2 have full capacity.
+There are 3 bags at full capacity, so we return 3.
+It can be shown that it is not possible to have more than 3 bags at full capacity.
+Note that there may be other ways of placing the rocks that result in an answer of 3.
+
+ +

Example 2:

+ +
Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100
+Output: 3
+Explanation:
+Place 8 rocks in bag 0 and 2 rocks in bag 2.
+The number of rocks in each bag are now [10,2,2].
+Bags 0, 1, and 2 have full capacity.
+There are 3 bags at full capacity, so we return 3.
+It can be shown that it is not possible to have more than 3 bags at full capacity.
+Note that we did not use all of the additional rocks.
+
+ +

 

+

Constraints:

+ +
    +
  • n == capacity.length == rocks.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • 1 <= capacity[i] <= 109
  • +
  • 0 <= rocks[i] <= capacity[i]
  • +
  • 1 <= additionalRocks <= 109
  • +
+
\ No newline at end of file diff --git a/2285-maximum-total-importance-of-roads/2285-maximum-total-importance-of-roads.cpp b/2285-maximum-total-importance-of-roads/2285-maximum-total-importance-of-roads.cpp new file mode 100644 index 00000000..b992faad --- /dev/null +++ b/2285-maximum-total-importance-of-roads/2285-maximum-total-importance-of-roads.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + long long maximumImportance(int n, vector>& roads) { + + vector adj[n+1]; + vector indegree(n, 0); + map, int> have; + + for(auto& edge : roads) + { + ++indegree[edge[0]]; + ++indegree[edge[1]]; + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } + + vector> vp; + + for(int i = 0; i < n; ++i) + { + vp.push_back({indegree[i], i}); + } + + sort(vp.begin(), vp.end()); + + vector vals(n, 0); + + for(int i = 0; i < n; ++i) + { + vals[vp[i].second] = i+1; + } + + vector visited(n, false); + + long long ans = 0; + + for(int i = 0; i < n; ++i) + { + for(auto& node : adj[i]) + { + int a = i, b = node; + if(a > b) swap(a, b); + + if(have.find({a, b}) == have.end()) + { + ans += vals[a]; + ans += vals[b]; + ++have[{a, b}]; + } + } + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2285-maximum-total-importance-of-roads/README.md b/2285-maximum-total-importance-of-roads/README.md new file mode 100644 index 00000000..c5b07133 --- /dev/null +++ b/2285-maximum-total-importance-of-roads/README.md @@ -0,0 +1,48 @@ +

2285. Maximum Total Importance of Roads

Medium


You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.

+ +

You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

+ +

You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.

+ +

Return the maximum total importance of all roads possible after assigning the values optimally.

+ +

 

+

Example 1:

+ +
Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
+Output: 43
+Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1].
+- The road (0,1) has an importance of 2 + 4 = 6.
+- The road (1,2) has an importance of 4 + 5 = 9.
+- The road (2,3) has an importance of 5 + 3 = 8.
+- The road (0,2) has an importance of 2 + 5 = 7.
+- The road (1,3) has an importance of 4 + 3 = 7.
+- The road (2,4) has an importance of 5 + 1 = 6.
+The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.
+It can be shown that we cannot obtain a greater total importance than 43.
+
+ +

Example 2:

+ +
Input: n = 5, roads = [[0,3],[2,4],[1,3]]
+Output: 20
+Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1].
+- The road (0,3) has an importance of 4 + 5 = 9.
+- The road (2,4) has an importance of 2 + 1 = 3.
+- The road (1,3) has an importance of 3 + 5 = 8.
+The total importance of all roads is 9 + 3 + 8 = 20.
+It can be shown that we cannot obtain a greater total importance than 20.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 5 * 104
  • +
  • 1 <= roads.length <= 5 * 104
  • +
  • roads[i].length == 2
  • +
  • 0 <= ai, bi <= n - 1
  • +
  • ai != bi
  • +
  • There are no duplicate roads.
  • +
+
\ No newline at end of file diff --git a/2290-minimum-obstacle-removal-to-reach-corner/2290-minimum-obstacle-removal-to-reach-corner.cpp b/2290-minimum-obstacle-removal-to-reach-corner/2290-minimum-obstacle-removal-to-reach-corner.cpp new file mode 100644 index 00000000..793c71bb --- /dev/null +++ b/2290-minimum-obstacle-removal-to-reach-corner/2290-minimum-obstacle-removal-to-reach-corner.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minimumObstacles(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + queue> q; + + vector dx = {1,0,0,-1}; + vector dy = {0,-1,+1,0}; + + vector> dp(n, vector(m,INT_MAX)); + + q.push({0,0}); + dp[0][0] = 0; + + while(!q.empty()) + { + int x = q.front().first; + int y = q.front().second; + q.pop(); + + for(int i = 0; i<4; ++i) + { + int newx = x + dx[i]; + int newy = y + dy[i]; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and dp[x][y] + grid[newx][newy] < dp[newx][newy]) + { + dp[newx][newy] = dp[x][y] + grid[newx][newy]; + q.push({newx,newy}); + } + } + } + + return dp[n-1][m-1]; + } +}; \ No newline at end of file diff --git a/2290-minimum-obstacle-removal-to-reach-corner/NOTES.md b/2290-minimum-obstacle-removal-to-reach-corner/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2290-minimum-obstacle-removal-to-reach-corner/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2290-minimum-obstacle-removal-to-reach-corner/README.md b/2290-minimum-obstacle-removal-to-reach-corner/README.md new file mode 100644 index 00000000..6a6de649 --- /dev/null +++ b/2290-minimum-obstacle-removal-to-reach-corner/README.md @@ -0,0 +1,40 @@ +

2290. Minimum Obstacle Removal to Reach Corner

Hard


You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:

+ +
    +
  • 0 represents an empty cell,
  • +
  • 1 represents an obstacle that may be removed.
  • +
+ +

You can move up, down, left, or right from and to an empty cell.

+ +

Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1,1],[1,1,0],[1,1,0]]
+Output: 2
+Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).
+It can be shown that we need to remove at least 2 obstacles, so we return 2.
+Note that there may be other ways to remove 2 obstacles to create a path.
+
+ +

Example 2:

+ +
Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]
+Output: 0
+Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 105
  • +
  • 2 <= m * n <= 105
  • +
  • grid[i][j] is either 0 or 1.
  • +
  • grid[0][0] == grid[m - 1][n - 1] == 0
  • +
+
\ No newline at end of file diff --git a/2300-successful-pairs-of-spells-and-potions/2300-successful-pairs-of-spells-and-potions.cpp b/2300-successful-pairs-of-spells-and-potions/2300-successful-pairs-of-spells-and-potions.cpp new file mode 100644 index 00000000..ca644387 --- /dev/null +++ b/2300-successful-pairs-of-spells-and-potions/2300-successful-pairs-of-spells-and-potions.cpp @@ -0,0 +1,37 @@ +#define ll long long int +class Solution { +public: + vector successfulPairs(vector& spells, vector& potions, long long success) { + + + int n = spells.size(); + + sort(potions.begin(),potions.end()); + vector v; + + for(int i = 0; i2300. Successful Pairs of Spells and Potions

Medium


You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.

+ +

You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.

+ +

Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.

+ +

 

+

Example 1:

+ +
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
+Output: [4,0,3]
+Explanation:
+- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
+- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
+- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
+Thus, [4,0,3] is returned.
+
+ +

Example 2:

+ +
Input: spells = [3,1,2], potions = [8,5,8], success = 16
+Output: [2,0,2]
+Explanation:
+- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
+- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. 
+- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. 
+Thus, [2,0,2] is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • n == spells.length
  • +
  • m == potions.length
  • +
  • 1 <= n, m <= 105
  • +
  • 1 <= spells[i], potions[i] <= 105
  • +
  • 1 <= success <= 1010
  • +
+
\ No newline at end of file diff --git a/2305-fair-distribution-of-cookies/NOTES.md b/2305-fair-distribution-of-cookies/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2305-fair-distribution-of-cookies/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2305-fair-distribution-of-cookies/README.md b/2305-fair-distribution-of-cookies/README.md new file mode 100644 index 00000000..f3d14dcf --- /dev/null +++ b/2305-fair-distribution-of-cookies/README.md @@ -0,0 +1,39 @@ +

2305. Fair Distribution of Cookies

Medium


You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.

+ +

The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.

+ +

Return the minimum unfairness of all distributions.

+ +

 

+

Example 1:

+ +
Input: cookies = [8,15,10,20,8], k = 2
+Output: 31
+Explanation: One optimal distribution is [8,15,8] and [10,20]
+- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
+- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
+The unfairness of the distribution is max(31,30) = 31.
+It can be shown that there is no distribution with an unfairness less than 31.
+
+ +

Example 2:

+ +
Input: cookies = [6,1,3,2,2,4,1,2], k = 3
+Output: 7
+Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
+- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
+- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
+- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
+The unfairness of the distribution is max(7,7,7) = 7.
+It can be shown that there is no distribution with an unfairness less than 7.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= cookies.length <= 8
  • +
  • 1 <= cookies[i] <= 105
  • +
  • 2 <= k <= cookies.length
  • +
+
\ No newline at end of file diff --git a/2306-naming-a-company/2306-naming-a-company.cpp b/2306-naming-a-company/2306-naming-a-company.cpp new file mode 100644 index 00000000..058588d5 --- /dev/null +++ b/2306-naming-a-company/2306-naming-a-company.cpp @@ -0,0 +1,26 @@ +#define ll long long int +class Solution { +public: + long long distinctNames(vector& ideas) { + unordered_set count[26]; + + for(auto& itr : ideas) + count[itr[0] - 'a'].insert(itr.substr(1)); + + ll res = 0; + for(int i = 0; i < 26; ++i) + { + for(int j = i+1; j < 26; ++j) + { + ll c1 = 0, c2 = 0; + for(auto& c : count[i]) + if(!count[j].count(c)) ++c1; + for(auto& c : count[j]) + if(!count[i].count(c)) ++c2; + + res += c1 * c2; + } + } + return res * 2; + } +}; diff --git a/2306-naming-a-company/NOTES.md b/2306-naming-a-company/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2306-naming-a-company/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2306-naming-a-company/README.md b/2306-naming-a-company/README.md new file mode 100644 index 00000000..a2d1dbeb --- /dev/null +++ b/2306-naming-a-company/README.md @@ -0,0 +1,48 @@ +

2306. Naming a Company

Hard


You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:

+ +
    +
  1. Choose 2 distinct names from ideas, call them ideaA and ideaB.
  2. +
  3. Swap the first letters of ideaA and ideaB with each other.
  4. +
  5. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
  6. +
  7. Otherwise, it is not a valid name.
  8. +
+ +

Return the number of distinct valid names for the company.

+ +

 

+

Example 1:

+ +
Input: ideas = ["coffee","donuts","time","toffee"]
+Output: 6
+Explanation: The following selections are valid:
+- ("coffee", "donuts"): The company name created is "doffee conuts".
+- ("donuts", "coffee"): The company name created is "conuts doffee".
+- ("donuts", "time"): The company name created is "tonuts dime".
+- ("donuts", "toffee"): The company name created is "tonuts doffee".
+- ("time", "donuts"): The company name created is "dime tonuts".
+- ("toffee", "donuts"): The company name created is "doffee tonuts".
+Therefore, there are a total of 6 distinct company names.
+
+The following are some examples of invalid selections:
+- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
+- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
+- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
+
+ +

Example 2:

+ +
Input: ideas = ["lack","back"]
+Output: 0
+Explanation: There are no valid selections. Therefore, 0 is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= ideas.length <= 5 * 104
  • +
  • 1 <= ideas[i].length <= 10
  • +
  • ideas[i] consists of lowercase English letters.
  • +
  • All the strings in ideas are unique.
  • +
+
\ No newline at end of file diff --git a/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.cpp b/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.cpp new file mode 100644 index 00000000..0d489239 --- /dev/null +++ b/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + + + void dfs(int sv, vector adj[], vector& visited, long long& count) + { + visited[sv] = true; + ++count; + + for(auto itr : adj[sv]) + { + if(!visited[itr]) + { + dfs(itr,adj,visited,count); + } + } + } + + + long long countPairs(int n, vector>& edges) { + + vector adj[n+1]; + + for(auto itr : edges) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + } + + long long total = (long long)n*(n-1)/2; + vector visited(n+1,false); + for(int i = 0; i2316. Count Unreachable Pairs of Nodes in an Undirected Graph

Medium


You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

+ +

Return the number of pairs of different nodes that are unreachable from each other.

+ +

 

+

Example 1:

+ +
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
+Output: 0
+Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
+
+ +

Example 2:

+ +
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
+Output: 14
+Explanation: There are 14 pairs of nodes that are unreachable from each other:
+[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
+Therefore, we return 14.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 0 <= edges.length <= 2 * 105
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • There are no repeated edges.
  • +
+
\ No newline at end of file diff --git a/2327-number-of-people-aware-of-a-secret/2327-number-of-people-aware-of-a-secret.cpp b/2327-number-of-people-aware-of-a-secret/2327-number-of-people-aware-of-a-secret.cpp new file mode 100644 index 00000000..49cc5598 --- /dev/null +++ b/2327-number-of-people-aware-of-a-secret/2327-number-of-people-aware-of-a-secret.cpp @@ -0,0 +1,27 @@ +#define ll long long int +int mod = 1e9+7; + +class Solution { +public: + int peopleAwareOfSecret(int n, int delay, int forget) { + + vector dp(n+1,0); + + dp[1] = 1; + ll ans = 0, spreading = 0; + + for(int i = 2; i<= n; ++i) + { + ll sharing = dp[max(i-delay,0)]; + ll forgetting = dp[max(i-forget,0)]; + spreading += (sharing - forgetting + mod) % mod; + + dp[i] = spreading; + } + + for(int i = n - forget + 1; i <= n; ++i) + ans = (ans + dp[i]) % mod; + + return (int)ans; + } +}; \ No newline at end of file diff --git a/2327-number-of-people-aware-of-a-secret/README.md b/2327-number-of-people-aware-of-a-secret/README.md new file mode 100644 index 00000000..a608eb8d --- /dev/null +++ b/2327-number-of-people-aware-of-a-secret/README.md @@ -0,0 +1,39 @@ +

2327. Number of People Aware of a Secret

Medium


On day 1, one person discovers a secret.

+ +

You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.

+ +

Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: n = 6, delay = 2, forget = 4
+Output: 5
+Explanation:
+Day 1: Suppose the first person is named A. (1 person)
+Day 2: A is the only person who knows the secret. (1 person)
+Day 3: A shares the secret with a new person, B. (2 people)
+Day 4: A shares the secret with a new person, C. (3 people)
+Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)
+Day 6: B shares the secret with E, and C shares the secret with F. (5 people)
+
+ +

Example 2:

+ +
Input: n = 4, delay = 1, forget = 3
+Output: 6
+Explanation:
+Day 1: The first person is named A. (1 person)
+Day 2: A shares the secret with B. (2 people)
+Day 3: A and B share the secret with 2 new people, C and D. (4 people)
+Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 1000
  • +
  • 1 <= delay < forget <= n
  • +
+
\ No newline at end of file diff --git a/2328-number-of-increasing-paths-in-a-grid/2328-number-of-increasing-paths-in-a-grid.cpp b/2328-number-of-increasing-paths-in-a-grid/2328-number-of-increasing-paths-in-a-grid.cpp new file mode 100644 index 00000000..084282cc --- /dev/null +++ b/2328-number-of-increasing-paths-in-a-grid/2328-number-of-increasing-paths-in-a-grid.cpp @@ -0,0 +1,54 @@ +class Solution { + +private: + int mod = 1e9 + 7; + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1, 0}; + + int helper(int i, int j, int n, int m, vector>& grid, vector>& dp) + { + if(dp[i][j] != -1) + return dp[i][j]; + + int ans = 1; + + for(int k = 0; k < 4; ++k) + { + int x = dx[k] + i; + int y = dy[k] + j; + + if(x >= 0 and y >= 0 and x < n and y < m and grid[x][y] > grid[i][j]) + { + ans += helper(x, y, n, m, grid, dp); + ans %= mod; + } + } + + return dp[i][j] = ans; + + } + +public: + int countPaths(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + vector> dp(n+1, vector(m+1, -1)); + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + cnt += helper(i, j, n, m, grid, dp); + cnt %= mod; + } + } + + return cnt % mod; + + } +}; \ No newline at end of file diff --git a/2328-number-of-increasing-paths-in-a-grid/NOTES.md b/2328-number-of-increasing-paths-in-a-grid/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2328-number-of-increasing-paths-in-a-grid/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2328-number-of-increasing-paths-in-a-grid/README.md b/2328-number-of-increasing-paths-in-a-grid/README.md new file mode 100644 index 00000000..39f07a06 --- /dev/null +++ b/2328-number-of-increasing-paths-in-a-grid/README.md @@ -0,0 +1,39 @@ +

2328. Number of Increasing Paths in a Grid

Hard


You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.

+ +

Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.

+ +

Two paths are considered different if they do not have exactly the same sequence of visited cells.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,1],[3,4]]
+Output: 8
+Explanation: The strictly increasing paths are:
+- Paths with length 1: [1], [1], [3], [4].
+- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
+- Paths with length 3: [1 -> 3 -> 4].
+The total number of paths is 4 + 3 + 1 = 8.
+
+ +

Example 2:

+ +
Input: grid = [[1],[2]]
+Output: 3
+Explanation: The strictly increasing paths are:
+- Paths with length 1: [1], [2].
+- Paths with length 2: [1 -> 2].
+The total number of paths is 2 + 1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 1000
  • +
  • 1 <= m * n <= 105
  • +
  • 1 <= grid[i][j] <= 105
  • +
+
\ No newline at end of file diff --git a/2331-evaluate-boolean-binary-tree/2331-evaluate-boolean-binary-tree.cpp b/2331-evaluate-boolean-binary-tree/2331-evaluate-boolean-binary-tree.cpp new file mode 100644 index 00000000..4b1f5932 --- /dev/null +++ b/2331-evaluate-boolean-binary-tree/2331-evaluate-boolean-binary-tree.cpp @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + bool helper(TreeNode* root) + { + if(!root->left and !root->right) + { + return root->val; + } + + bool left = helper(root->left); + bool right = helper(root->right); + + return (root->val == 2 ? left | right : left & right); + } + + bool evaluateTree(TreeNode* root) { + + return helper(root); + } +}; \ No newline at end of file diff --git a/2331-evaluate-boolean-binary-tree/NOTES.md b/2331-evaluate-boolean-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2331-evaluate-boolean-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2331-evaluate-boolean-binary-tree/README.md b/2331-evaluate-boolean-binary-tree/README.md new file mode 100644 index 00000000..d563a4b9 --- /dev/null +++ b/2331-evaluate-boolean-binary-tree/README.md @@ -0,0 +1,48 @@ +

2331. Evaluate Boolean Binary Tree

Easy


You are given the root of a full binary tree with the following properties:

+ +
    +
  • Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.
  • +
  • Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.
  • +
+ +

The evaluation of a node is as follows:

+ +
    +
  • If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
  • +
  • Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.
  • +
+ +

Return the boolean result of evaluating the root node.

+ +

A full binary tree is a binary tree where each node has either 0 or 2 children.

+ +

A leaf node is a node that has zero children.

+ +

 

+

Example 1:

+ +
Input: root = [2,1,3,null,null,0,1]
+Output: true
+Explanation: The above diagram illustrates the evaluation process.
+The AND node evaluates to False AND True = False.
+The OR node evaluates to True OR False = True.
+The root node evaluates to True, so we return true.
+ +

Example 2:

+ +
Input: root = [0]
+Output: false
+Explanation: The root node is a leaf node and it evaluates to false, so we return false.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 3
  • +
  • Every node has either 0 or 2 children.
  • +
  • Leaf nodes have a value of 0 or 1.
  • +
  • Non-leaf nodes have a value of 2 or 3.
  • +
+
\ No newline at end of file diff --git a/2336-smallest-number-in-infinite-set/2336-smallest-number-in-infinite-set.cpp b/2336-smallest-number-in-infinite-set/2336-smallest-number-in-infinite-set.cpp new file mode 100644 index 00000000..2302502f --- /dev/null +++ b/2336-smallest-number-in-infinite-set/2336-smallest-number-in-infinite-set.cpp @@ -0,0 +1,31 @@ +class SmallestInfiniteSet { +public: + + set st; + + SmallestInfiniteSet() { + for(int i = 1 ; i<= 1000; ++i) + st.insert(i); + } + + int popSmallest() { + + int val = *st.begin(); + st.erase(val); + return val; + + } + + void addBack(int num) { + + if(st.find(num) == st.end()) + st.insert(num); + } +}; + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * SmallestInfiniteSet* obj = new SmallestInfiniteSet(); + * int param_1 = obj->popSmallest(); + * obj->addBack(num); + */ \ No newline at end of file diff --git a/2336-smallest-number-in-infinite-set/NOTES.md b/2336-smallest-number-in-infinite-set/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2336-smallest-number-in-infinite-set/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2336-smallest-number-in-infinite-set/README.md b/2336-smallest-number-in-infinite-set/README.md new file mode 100644 index 00000000..7e19ea4f --- /dev/null +++ b/2336-smallest-number-in-infinite-set/README.md @@ -0,0 +1,40 @@ +

2336. Smallest Number in Infinite Set

Medium


You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].

+ +

Implement the SmallestInfiniteSet class:

+ +
    +
  • SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.
  • +
  • int popSmallest() Removes and returns the smallest integer contained in the infinite set.
  • +
  • void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.
  • +
+ +

 

+

Example 1:

+ +
Input
+["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]
+[[], [2], [], [], [], [1], [], [], []]
+Output
+[null, null, 1, 2, 3, null, 1, 4, 5]
+
+Explanation
+SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
+smallestInfiniteSet.addBack(2);    // 2 is already in the set, so no change is made.
+smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.
+smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.
+smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.
+smallestInfiniteSet.addBack(1);    // 1 is added back to the set.
+smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and
+                                   // is the smallest number, and remove it from the set.
+smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.
+smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num <= 1000
  • +
  • At most 1000 calls will be made in total to popSmallest and addBack.
  • +
+
\ No newline at end of file diff --git a/2342-max-sum-of-a-pair-with-equal-sum-of-digits/2342-max-sum-of-a-pair-with-equal-sum-of-digits.cpp b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/2342-max-sum-of-a-pair-with-equal-sum-of-digits.cpp new file mode 100644 index 00000000..63e6b916 --- /dev/null +++ b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/2342-max-sum-of-a-pair-with-equal-sum-of-digits.cpp @@ -0,0 +1,41 @@ +#define ll long long int +class Solution { +public: + + ll sum (int num) + { + ll s = 0; + while(num > 0) + { + s += (num%10); + num /= 10; + } + return s; + } + + int maximumSum(vector& nums) { + + vector> vec; + int n = nums.size(); + + for(auto &n : nums) + { + ll s = sum(n); + vec.push_back({s,n}); + } + + sort(vec.begin(),vec.end()); + + ll ans = -1; + for(int i = 1; i < n; ++i) + { + if(vec[i].first == vec[i-1].first) + { + ll currSum = (ll)vec[i].second + vec[i-1].second; + ans = max(ans,currSum); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/2342-max-sum-of-a-pair-with-equal-sum-of-digits/NOTES.md b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2342-max-sum-of-a-pair-with-equal-sum-of-digits/README.md b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/README.md new file mode 100644 index 00000000..8c107197 --- /dev/null +++ b/2342-max-sum-of-a-pair-with-equal-sum-of-digits/README.md @@ -0,0 +1,30 @@ +

2342. Max Sum of a Pair With Equal Sum of Digits

Medium


You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].

+ +

Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.

+ +

 

+

Example 1:

+ +
Input: nums = [18,43,36,13,7]
+Output: 54
+Explanation: The pairs (i, j) that satisfy the conditions are:
+- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
+- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
+So the maximum sum that we can obtain is 54.
+
+ +

Example 2:

+ +
Input: nums = [10,12,19,14]
+Output: -1
+Explanation: There are no two numbers that satisfy the conditions, so we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2343-query-kth-smallest-trimmed-number/2343-query-kth-smallest-trimmed-number.cpp b/2343-query-kth-smallest-trimmed-number/2343-query-kth-smallest-trimmed-number.cpp new file mode 100644 index 00000000..e86673fa --- /dev/null +++ b/2343-query-kth-smallest-trimmed-number/2343-query-kth-smallest-trimmed-number.cpp @@ -0,0 +1,44 @@ +#define ll long long int +class Solution { +public: + + vector smallestTrimmedNumbers(vector& nums, vector>& queries) { + + int n = nums.size(); + vector ans; + + for(auto q : queries) + { + int k = q[0]; + int trim = q[1]; + + vector> vp; // string, idx + int need = nums[0].size() - trim; + + for(int i = 0; i < n; ++i) + { + if(nums[i].size() < trim) + break; + + vp.push_back({nums[i].substr(need),i}); + } + + // debug + // for(auto itr : vp) + // cout<& a, const pair& b){ + if(a.first == b.first) + return a.second < b.second; + return a.first < b.first; + }); + + ans.push_back(vp[k-1].second); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2343-query-kth-smallest-trimmed-number/NOTES.md b/2343-query-kth-smallest-trimmed-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2343-query-kth-smallest-trimmed-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2352-equal-row-and-column-pairs/2352-equal-row-and-column-pairs.cpp b/2352-equal-row-and-column-pairs/2352-equal-row-and-column-pairs.cpp new file mode 100644 index 00000000..5af26602 --- /dev/null +++ b/2352-equal-row-and-column-pairs/2352-equal-row-and-column-pairs.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int equalPairs(vector>& grid) { + + int n = grid.size(); + int m = grid[0].size(); + + map, int> mp; + + vector> mat = grid; + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(i < j) + swap(grid[i][j], grid[j][i]); + } + ++mp[grid[i]]; + } + + for(int i = 0; i < n; ++i) + { + if(mp[mat[i]] > 0) + ans += mp[mat[i]]; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2352-equal-row-and-column-pairs/NOTES.md b/2352-equal-row-and-column-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2352-equal-row-and-column-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2352-equal-row-and-column-pairs/README.md b/2352-equal-row-and-column-pairs/README.md new file mode 100644 index 00000000..54c26f69 --- /dev/null +++ b/2352-equal-row-and-column-pairs/README.md @@ -0,0 +1,32 @@ +

2352. Equal Row and Column Pairs

Medium


Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.

+ +

A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).

+ +

 

+

Example 1:

+ +
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
+Output: 1
+Explanation: There is 1 equal row and column pair:
+- (Row 2, Column 1): [2,7,7]
+
+ +

Example 2:

+ +
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
+Output: 3
+Explanation: There are 3 equal row and column pairs:
+- (Row 0, Column 0): [3,1,2,2]
+- (Row 2, Column 2): [2,4,2,2]
+- (Row 3, Column 2): [2,4,2,2]
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 1 <= n <= 200
  • +
  • 1 <= grid[i][j] <= 105
  • +
+
\ No newline at end of file diff --git a/2353-design-a-food-rating-system/2353-design-a-food-rating-system.cpp b/2353-design-a-food-rating-system/2353-design-a-food-rating-system.cpp new file mode 100644 index 00000000..f865a9a6 --- /dev/null +++ b/2353-design-a-food-rating-system/2353-design-a-food-rating-system.cpp @@ -0,0 +1,34 @@ +class FoodRatings { +public: + map>> s; + unordered_map cus; + unordered_map rat; + FoodRatings(vector& foods, vector& cuisines, vector& ratings) { + for(int i=0;i p= *(s[cuisine].begin()); + return p.second; + } +}; + +/** + * Your FoodRatings object will be instantiated and called as such: + * FoodRatings* obj = new FoodRatings(foods, cuisines, ratings); + * obj->changeRating(food,newRating); + * string param_2 = obj->highestRated(cuisine); + */ \ No newline at end of file diff --git a/2353-design-a-food-rating-system/NOTES.md b/2353-design-a-food-rating-system/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2353-design-a-food-rating-system/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2353-design-a-food-rating-system/README.md b/2353-design-a-food-rating-system/README.md new file mode 100644 index 00000000..085588a8 --- /dev/null +++ b/2353-design-a-food-rating-system/README.md @@ -0,0 +1,63 @@ +

2353. Design a Food Rating System

Medium


Design a food rating system that can do the following:

+ +
    +
  • Modify the rating of a food item listed in the system.
  • +
  • Return the highest-rated food item for a type of cuisine in the system.
  • +
+ +

Implement the FoodRatings class:

+ +
    +
  • FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. + +
      +
    • foods[i] is the name of the ith food,
    • +
    • cuisines[i] is the type of cuisine of the ith food, and
    • +
    • ratings[i] is the initial rating of the ith food.
    • +
    +
  • +
  • void changeRating(String food, int newRating) Changes the rating of the food item with the name food.
  • +
  • String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.
  • +
+ +

Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.

+ +

 

+

Example 1:

+ +
Input
+["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
+[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]
+Output
+[null, "kimchi", "ramen", null, "sushi", null, "ramen"]
+
+Explanation
+FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
+foodRatings.highestRated("korean"); // return "kimchi"
+                                    // "kimchi" is the highest rated korean food with a rating of 9.
+foodRatings.highestRated("japanese"); // return "ramen"
+                                      // "ramen" is the highest rated japanese food with a rating of 14.
+foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "sushi"
+                                      // "sushi" is the highest rated japanese food with a rating of 16.
+foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16.
+foodRatings.highestRated("japanese"); // return "ramen"
+                                      // Both "sushi" and "ramen" have a rating of 16.
+                                      // However, "ramen" is lexicographically smaller than "sushi".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 104
  • +
  • n == foods.length == cuisines.length == ratings.length
  • +
  • 1 <= foods[i].length, cuisines[i].length <= 10
  • +
  • foods[i], cuisines[i] consist of lowercase English letters.
  • +
  • 1 <= ratings[i] <= 108
  • +
  • All the strings in foods are distinct.
  • +
  • food will be the name of a food item in the system across all calls to changeRating.
  • +
  • cuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.
  • +
  • At most 2 * 104 calls in total will be made to changeRating and highestRated.
  • +
+
\ No newline at end of file diff --git a/2357. Make Array Zero by Subtracting Equal Amounts.cpp b/2357. Make Array Zero by Subtracting Equal Amounts.cpp new file mode 100644 index 00000000..0ffa5c9b --- /dev/null +++ b/2357. Make Array Zero by Subtracting Equal Amounts.cpp @@ -0,0 +1,38 @@ +// 2357. Make Array Zero by Subtracting Equal Amounts + +class Solution +{ +public: + int minimumOperations(vector &nums) + { + + int count = 0; + sort(nums.begin(), nums.end()); + + for (int i = 0; i < nums.size(); ++i) + { + if (nums[i] == 0) + continue; + else + { + int a = nums[i]; + for (int j = i; j < nums.size(); ++j) + { + // nums[j] -= nums[i]; + nums[j] -= a; + } + + cout << endl; + + for (auto itr : nums) + cout << itr << " "; + + ++count; + + cout << endl; + cout << count; + } + } + return count; + } +}; \ No newline at end of file diff --git a/2358-maximum-number-of-groups-entering-a-competition/2358-maximum-number-of-groups-entering-a-competition.cpp b/2358-maximum-number-of-groups-entering-a-competition/2358-maximum-number-of-groups-entering-a-competition.cpp new file mode 100644 index 00000000..4c14b4cf --- /dev/null +++ b/2358-maximum-number-of-groups-entering-a-competition/2358-maximum-number-of-groups-entering-a-competition.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maximumGroups(vector& grades) { + + int n = grades.size(); + sort(grades.begin(),grades.end()); + + int curr = 0, prev = 0, currSum = 0, prevSum = 0, res = 0; + + for(auto itr : grades) + { + currSum += itr; + ++curr; + + if(currSum > prevSum and curr > prev) + { + ++res; + prevSum = currSum, prev = curr; + currSum = 0, curr = 0; + } + } + + return res; + } +}; \ No newline at end of file diff --git a/2358-maximum-number-of-groups-entering-a-competition/NOTES.md b/2358-maximum-number-of-groups-entering-a-competition/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2358-maximum-number-of-groups-entering-a-competition/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2358-maximum-number-of-groups-entering-a-competition/README.md b/2358-maximum-number-of-groups-entering-a-competition/README.md new file mode 100644 index 00000000..1c1cacc0 --- /dev/null +++ b/2358-maximum-number-of-groups-entering-a-competition/README.md @@ -0,0 +1,36 @@ +

2358. Maximum Number of Groups Entering a Competition

Medium


You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:

+ +
    +
  • The sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last).
  • +
  • The total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last).
  • +
+ +

Return the maximum number of groups that can be formed.

+ +

 

+

Example 1:

+ +
Input: grades = [10,6,12,7,3,5]
+Output: 3
+Explanation: The following is a possible way to form 3 groups of students:
+- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1
+- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2
+- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3
+It can be shown that it is not possible to form more than 3 groups.
+
+ +

Example 2:

+ +
Input: grades = [8,8]
+Output: 1
+Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= grades.length <= 105
  • +
  • 1 <= grades[i] <= 105
  • +
+
\ No newline at end of file diff --git a/2358. Maximum Number of Groups Entering a Competition.cpp b/2358. Maximum Number of Groups Entering a Competition.cpp new file mode 100644 index 00000000..b39b012b --- /dev/null +++ b/2358. Maximum Number of Groups Entering a Competition.cpp @@ -0,0 +1,21 @@ +// 2358.✅ Maximum Number of Groups Entering a Competition + +class Solution +{ +public: + int maximumGroups(vector &grades) + { + + int n = grades.size(); + int count = 0; + + int i = 1; + while (n > 0) + { + n -= i++; + ++count; + } + + return n == 0 ? count : count - 1; + } +}; \ No newline at end of file diff --git a/2359-find-closest-node-to-given-two-nodes/2359-find-closest-node-to-given-two-nodes.cpp b/2359-find-closest-node-to-given-two-nodes/2359-find-closest-node-to-given-two-nodes.cpp new file mode 100644 index 00000000..c96350af --- /dev/null +++ b/2359-find-closest-node-to-given-two-nodes/2359-find-closest-node-to-given-two-nodes.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + + void dfs(int node, vector& edges, vector& dist , vector& visited, int distance) + { + if(node != -1 and !visited[node]) { + visited[node] = 1; + dist[node] = distance; + dfs(edges[node], edges, dist, visited, distance + 1); + } + } + + int closestMeetingNode(vector& edges, int node1, int node2) { + + int n = edges.size(); + + vector visited1(n,0), visited2(n,0), dist1(n,-1), dist2(n,-1); + + dfs(node1, edges, dist1, visited1, 0); + dfs(node2 , edges, dist2, visited2, 0); + + int ans = edges.size(); + int res = -1; + for(int i = 0; i &ed , vector &pvis , vector &vis , int i , int j){ + if(pvis[i]){ + mx = max(mx , j - pvis[i]); + return; + } + if(!vis[i]){ + pvis[i] =j; j++; vis[i]=1; + if(ed[i]!=-1) dfs(ed , pvis , vis , ed[i],j); + } + pvis[i] = 0; + return; + } + + int longestCycle(vector& ed) { + vector vis(ed.size(),0) , pvis(ed.size(),0); + mx = -1; + for(int i=0;i2360. Longest Cycle in a Graph

Hard


You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

+ +

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

+ +

Return the length of the longest cycle in the graph. If no cycle exists, return -1.

+ +

A cycle is a path that starts and ends at the same node.

+ +

 

+

Example 1:

+ +
Input: edges = [3,3,4,2,3]
+Output: 3
+Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
+The length of this cycle is 3, so 3 is returned.
+
+ +

Example 2:

+ +
Input: edges = [2,-1,3,1]
+Output: -1
+Explanation: There are no cycles in this graph.
+
+ +

 

+

Constraints:

+ +
    +
  • n == edges.length
  • +
  • 2 <= n <= 105
  • +
  • -1 <= edges[i] < n
  • +
  • edges[i] != i
  • +
+
\ No newline at end of file diff --git a/2363. Merge Similar Items.cpp b/2363. Merge Similar Items.cpp new file mode 100644 index 00000000..58306501 --- /dev/null +++ b/2363. Merge Similar Items.cpp @@ -0,0 +1,34 @@ +// 2363.✅ Merge Similar Items + +class Solution +{ +public: + vector> mergeSimilarItems(vector> &items1, vector> &items2) + { + + map mp; + + for (int i = 0; i < items1.size(); ++i) + { + mp.insert({items1[i][0], items1[i][1]}); + } + + for (int i = 0; i < items2.size(); ++i) + { + if (mp[items2[i][0]] >= 0) + { + mp[items2[i][0]] += items2[i][1]; + } + else + mp.insert({items2[i][0], items2[1][1]}); + } + + vector> ans; + for (auto it = mp.cbegin(); it != mp.cend(); ++it) + { + ans.push_back({it->first, it->second}); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2365. Task Scheduler II.cpp b/2365. Task Scheduler II.cpp new file mode 100644 index 00000000..8e92ef0d --- /dev/null +++ b/2365. Task Scheduler II.cpp @@ -0,0 +1,28 @@ +// 2365.✅ Task Scheduler II + +class Solution +{ +public: + long long taskSchedulerII(vector &tasks, int space) + { + map mp; + long long day = 0; + + for (int i = 0; i < tasks.size(); ++i) + { + if (mp.find(tasks[i]) == mp.end()) + { + ++day; + mp[tasks[i]] = day; + continue; + } + + long long last_day = mp[tasks[i]]; + + day = max(day + 1, last_day + space + 1); + + mp[tasks[i]] = day; + } + return day; + } +}; \ No newline at end of file diff --git a/2366-minimum-replacements-to-sort-the-array/2366-minimum-replacements-to-sort-the-array.cpp b/2366-minimum-replacements-to-sort-the-array/2366-minimum-replacements-to-sort-the-array.cpp new file mode 100644 index 00000000..138b8834 --- /dev/null +++ b/2366-minimum-replacements-to-sort-the-array/2366-minimum-replacements-to-sort-the-array.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + long long minimumReplacement(vector& nums) { + + int n = nums.size(); + + long long numberOfOperations = 0; + + for(int i = n-2; i >= 0; --i) + { + if(nums[i] <= nums[i+1]) + continue; + + long long parts = nums[i] / nums[i+1]; + + if(nums[i] % nums[i+1] != 0) + ++parts; + + numberOfOperations += (parts-1); + + nums[i] = (nums[i] / parts); + } + + return numberOfOperations; + + } +}; \ No newline at end of file diff --git a/2366-minimum-replacements-to-sort-the-array/NOTES.md b/2366-minimum-replacements-to-sort-the-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2366-minimum-replacements-to-sort-the-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2366-minimum-replacements-to-sort-the-array/README.md b/2366-minimum-replacements-to-sort-the-array/README.md new file mode 100644 index 00000000..19164773 --- /dev/null +++ b/2366-minimum-replacements-to-sort-the-array/README.md @@ -0,0 +1,35 @@ +

2366. Minimum Replacements to Sort the Array

Hard


You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.

+ +
    +
  • For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].
  • +
+ +

Return the minimum number of operations to make an array that is sorted in non-decreasing order.

+ +

 

+

Example 1:

+ +
Input: nums = [3,9,3]
+Output: 2
+Explanation: Here are the steps to sort the array in non-decreasing order:
+- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
+- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
+There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.
+
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5]
+Output: 0
+Explanation: The array is already in non-decreasing order. Therefore, we return 0. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2367. Number of Arithmetic Triplets.cpp b/2367. Number of Arithmetic Triplets.cpp new file mode 100644 index 00000000..425a4dd7 --- /dev/null +++ b/2367. Number of Arithmetic Triplets.cpp @@ -0,0 +1,22 @@ +// 2367.✅ Number of Arithmetic Triplets + +class Solution +{ +public: + int arithmeticTriplets(vector &nums, int diff) + { + int count = 0; + for (int i = 0; i < nums.size(); ++i) + { + for (int j = i + 1; j < nums.size(); ++j) + { + for (int k = j + 1; k < nums.size(); ++k) + { + if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff) + ++count; + } + } + } + return count; + } +}; \ No newline at end of file diff --git a/2368. Reachable Nodes With Restrictions.cpp b/2368. Reachable Nodes With Restrictions.cpp new file mode 100644 index 00000000..478338d5 --- /dev/null +++ b/2368. Reachable Nodes With Restrictions.cpp @@ -0,0 +1,65 @@ +// 2368.✅ Reachable Nodes With Restrictions + +class Solution +{ +public: + void adjacencylist(vector adj[], int V) + { + for (int i = 0; i < V; i++) + { + cout << i << "->"; + for (int &x : adj[i]) + { + cout << x << " "; + } + cout << endl; + } + } + + void dfsOfGraph(int sv, vector &visited, vector adj[]) + { + visited[sv] = true; + + for (auto itr : adj[sv]) + { + if (!visited[itr]) + dfsOfGraph(itr, visited, adj); + } + } + + int reachableNodes(int n, vector> &edges, vector &restricted) + { + + vector graph[n + 1]; + for (int i = 0; i < edges.size(); ++i) + { + graph[edges[i][0]].push_back(edges[i][1]); + graph[edges[i][1]].push_back(edges[i][0]); + } + + vector visited(n + 1, 0); + int count = 0; + for (int i = 0; i < restricted.size(); ++i) + { + visited[restricted[i]] = true; + } + + // for(auto itr : visited) + // cout<& nums, vector& dp) + { + if(idx == n) + return true; + + if(dp[idx] != -1) + return dp[idx]; + + if(idx + 1 < n and nums[idx] == nums[idx+1]) + { + if(helper(idx+2, n, nums, dp)) + return true; + + if(idx + 2 < n and nums[idx] == nums[idx+2]) + { + if(helper(idx+3, n, nums , dp)) + return true; + } + } + + if(idx + 2 < n and nums[idx] == nums[idx+1] - 1 and nums[idx] == nums[idx+2] - 2) + { + if(helper(idx + 3, n, nums, dp)) + return true; + } + + return dp[idx] = false; + } + +public: + bool validPartition(vector& nums) { + + int n = nums.size(); + + vector dp(n+1, -1); + + return helper(0, n, nums, dp); + + } +}; \ No newline at end of file diff --git a/2369-check-if-there-is-a-valid-partition-for-the-array/NOTES.md b/2369-check-if-there-is-a-valid-partition-for-the-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2369-check-if-there-is-a-valid-partition-for-the-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2369-check-if-there-is-a-valid-partition-for-the-array/README.md b/2369-check-if-there-is-a-valid-partition-for-the-array/README.md new file mode 100644 index 00000000..9f45a5c9 --- /dev/null +++ b/2369-check-if-there-is-a-valid-partition-for-the-array/README.md @@ -0,0 +1,36 @@ +

2369. Check if There is a Valid Partition For The Array

Medium


You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.

+ +

We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:

+ +
    +
  1. The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.
  2. +
  3. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.
  4. +
  5. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.
  6. +
+ +

Return true if the array has at least one valid partition. Otherwise, return false.

+ +

 

+

Example 1:

+ +
Input: nums = [4,4,4,5,6]
+Output: true
+Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
+This partition is valid, so we return true.
+
+ +

Example 2:

+ +
Input: nums = [1,1,1,2]
+Output: false
+Explanation: There is no valid partition for this array.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 106
  • +
+
\ No newline at end of file diff --git a/2369. Check if There is a Valid Partition For The Array.cpp b/2369. Check if There is a Valid Partition For The Array.cpp new file mode 100644 index 00000000..dc783b5e --- /dev/null +++ b/2369. Check if There is a Valid Partition For The Array.cpp @@ -0,0 +1,27 @@ +class Solution +{ + // 2369.✅ Check if There is a Valid Partition For The Array + +public: + bool validPartition(vector &nums) + { + int n = nums.size(); + vector dp(n + 1); + + dp[0] = 1; + + for (int i = 0; i < n; ++i) + { + if (dp[i]) + { + if (i + 1 < n && nums[i] == nums[i + 1]) + dp[i + 2] = true; + if (i + 2 < n && nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) + dp[i + 3] = true; + if (i + 2 < n && nums[i] == nums[i + 1] - 1 && nums[i] == nums[i + 2] - 2) + dp[i + 3] = true; + } + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/2370-longest-ideal-subsequence/2370-longest-ideal-subsequence.cpp b/2370-longest-ideal-subsequence/2370-longest-ideal-subsequence.cpp new file mode 100644 index 00000000..d54a17f5 --- /dev/null +++ b/2370-longest-ideal-subsequence/2370-longest-ideal-subsequence.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + int helper(int idx, int prev, int k, int n, string& s, vector>& dp) + { + if(idx == n) + return 0; + + if(dp[idx][prev+1] != -1) + return dp[idx][prev+1]; + + int notTake = helper(idx+1, prev, k, n, s, dp); + + int take = 0; + int curr = s[idx]; + if(prev == -1 or abs(prev - curr) <= k) + take = max(1 + helper(idx+1, curr, k, n, s, dp), notTake); + + return dp[idx][prev+1] = max(take, notTake); + } + + int longestIdealString(string s, int k) { + + int n = s.size(); + + vector> dp(n+1, vector(150, -1)); + + return helper(0, -1, k, n, s, dp); + + } +}; \ No newline at end of file diff --git a/2370-longest-ideal-subsequence/README.md b/2370-longest-ideal-subsequence/README.md new file mode 100644 index 00000000..17c7257e --- /dev/null +++ b/2370-longest-ideal-subsequence/README.md @@ -0,0 +1,37 @@ +

2370. Longest Ideal Subsequence

Medium


You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:

+ +
    +
  • t is a subsequence of the string s.
  • +
  • The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.
  • +
+ +

Return the length of the longest ideal string.

+ +

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

+ +

Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.

+ +

 

+

Example 1:

+ +
Input: s = "acfgbd", k = 2
+Output: 4
+Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned.
+Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.
+ +

Example 2:

+ +
Input: s = "abcd", k = 3
+Output: 4
+Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • 0 <= k <= 25
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2373-largest-local-values-in-a-matrix/2373-largest-local-values-in-a-matrix.cpp b/2373-largest-local-values-in-a-matrix/2373-largest-local-values-in-a-matrix.cpp new file mode 100644 index 00000000..1620dba7 --- /dev/null +++ b/2373-largest-local-values-in-a-matrix/2373-largest-local-values-in-a-matrix.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector> largestLocal(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector> ans; + + for(int i = 0; i < n-2; ++i) + { + vector curr; + for(int j = 0; j < n-2; ++j) + { + int maxi = -1; + for(int row = i; row < i+3; ++row) + { + for(int col = j; col < j+3; ++col) + { + maxi = max(maxi, grid[row][col]); + } + } + curr.push_back(maxi); + } + ans.push_back(curr); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2373-largest-local-values-in-a-matrix/README.md b/2373-largest-local-values-in-a-matrix/README.md new file mode 100644 index 00000000..b70175ae --- /dev/null +++ b/2373-largest-local-values-in-a-matrix/README.md @@ -0,0 +1,36 @@ +

2373. Largest Local Values in a Matrix

Easy


You are given an n x n integer matrix grid.

+ +

Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:

+ +
    +
  • maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.
  • +
+ +

In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.

+ +

Return the generated matrix.

+ +

 

+

Example 1:

+ +
Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
+Output: [[9,9],[8,6]]
+Explanation: The diagram above shows the original matrix and the generated matrix.
+Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.
+ +

Example 2:

+ +
Input: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
+Output: [[2,2,2],[2,2,2],[2,2,2]]
+Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 3 <= n <= 100
  • +
  • 1 <= grid[i][j] <= 100
  • +
+
\ No newline at end of file diff --git a/2385-amount-of-time-for-binary-tree-to-be-infected/2385-amount-of-time-for-binary-tree-to-be-infected.cpp b/2385-amount-of-time-for-binary-tree-to-be-infected/2385-amount-of-time-for-binary-tree-to-be-infected.cpp new file mode 100644 index 00000000..c9bdd38b --- /dev/null +++ b/2385-amount-of-time-for-binary-tree-to-be-infected/2385-amount-of-time-for-binary-tree-to-be-infected.cpp @@ -0,0 +1,86 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + map> graph; + + int amountOfTime(TreeNode* root, int start) { + + queue q; + + q.push(root); + + while(!q.empty()) + { + int size = q.size(); + + for(int i = 0; i < size; ++i) + { + TreeNode* parent = q.front(); + q.pop(); + + if(parent->left) + { + q.push(parent->left); + graph[parent->val].push_back(parent->left->val); + graph[parent->left->val].push_back(parent->val); + } + + if(parent->right) + { + q.push(parent->right); + graph[parent->val].push_back(parent->right->val); + graph[parent->right->val].push_back(parent->val); + } + } + } + + int n = graph.size(); + + queue q2; + + set visited; + + visited.insert(start); + + for(auto& itr : graph[start]) + { + q2.push(itr); + visited.insert(itr); + } + + int cnt = 0; + + while(!q2.empty()) + { + int size = q2.size(); + for(int i = 0; i < size; ++i) + { + int curr = q2.front(); + q2.pop(); + + for(auto& itr : graph[curr]) + { + if(!visited.count(itr)) + { + q2.push(itr); + visited.insert(itr); + } + } + } + ++cnt; + } + + return cnt; + } +}; \ No newline at end of file diff --git a/2385-amount-of-time-for-binary-tree-to-be-infected/README.md b/2385-amount-of-time-for-binary-tree-to-be-infected/README.md new file mode 100644 index 00000000..4c9f31b3 --- /dev/null +++ b/2385-amount-of-time-for-binary-tree-to-be-infected/README.md @@ -0,0 +1,42 @@ +

2385. Amount of Time for Binary Tree to Be Infected

Medium


You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.

+ +

Each minute, a node becomes infected if:

+ +
    +
  • The node is currently uninfected.
  • +
  • The node is adjacent to an infected node.
  • +
+ +

Return the number of minutes needed for the entire tree to be infected.

+ +

 

+

Example 1:

+ +
Input: root = [1,5,3,null,4,10,6,9,2], start = 3
+Output: 4
+Explanation: The following nodes are infected during:
+- Minute 0: Node 3
+- Minute 1: Nodes 1, 10 and 6
+- Minute 2: Node 5
+- Minute 3: Node 4
+- Minute 4: Nodes 9 and 2
+It takes 4 minutes for the whole tree to be infected so we return 4.
+
+ +

Example 2:

+ +
Input: root = [1], start = 1
+Output: 0
+Explanation: At minute 0, the only node in the tree is infected so we return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 105].
  • +
  • 1 <= Node.val <= 105
  • +
  • Each node has a unique value.
  • +
  • A node with a value of start exists in the tree.
  • +
+
\ No newline at end of file diff --git a/2389-longest-subsequence-with-limited-sum/2389-longest-subsequence-with-limited-sum.cpp b/2389-longest-subsequence-with-limited-sum/2389-longest-subsequence-with-limited-sum.cpp new file mode 100644 index 00000000..a9377a4a --- /dev/null +++ b/2389-longest-subsequence-with-limited-sum/2389-longest-subsequence-with-limited-sum.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + + int n = nums.size(); + sort(nums.begin(),nums.end()); + + vector ans; + + for(int i = 1; i2389. Longest Subsequence With Limited Sum

Easy


You are given an integer array nums of length n, and an integer array queries of length m.

+ +

Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [4,5,2,1], queries = [3,10,21]
+Output: [2,3,4]
+Explanation: We answer the queries as follows:
+- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
+- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
+- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
+
+ +

Example 2:

+ +
Input: nums = [2,3,4,5], queries = [1]
+Output: [0]
+Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • m == queries.length
  • +
  • 1 <= n, m <= 1000
  • +
  • 1 <= nums[i], queries[i] <= 106
  • +
+
\ No newline at end of file diff --git a/2390-removing-stars-from-a-string/2390-removing-stars-from-a-string.cpp b/2390-removing-stars-from-a-string/2390-removing-stars-from-a-string.cpp new file mode 100644 index 00000000..453c3e9f --- /dev/null +++ b/2390-removing-stars-from-a-string/2390-removing-stars-from-a-string.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string removeStars(string s) { + + stack st; + string ans; + + for(auto itr : s) + { + if(!st.empty() and itr == '*') + st.pop(); + else + st.push(itr); + } + + while(!st.empty()) + { + ans += st.top(); + st.pop(); + } + + reverse(ans.begin(),ans.end()); + + return ans; + } +}; \ No newline at end of file diff --git a/2390-removing-stars-from-a-string/NOTES.md b/2390-removing-stars-from-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2390-removing-stars-from-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2390-removing-stars-from-a-string/README.md b/2390-removing-stars-from-a-string/README.md new file mode 100644 index 00000000..341e4236 --- /dev/null +++ b/2390-removing-stars-from-a-string/README.md @@ -0,0 +1,45 @@ +

2390. Removing Stars From a String

Medium


You are given a string s, which contains stars *.

+ +

In one operation, you can:

+ +
    +
  • Choose a star in s.
  • +
  • Remove the closest non-star character to its left, as well as remove the star itself.
  • +
+ +

Return the string after all stars have been removed.

+ +

Note:

+ +
    +
  • The input will be generated such that the operation is always possible.
  • +
  • It can be shown that the resulting string will always be unique.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "leet**cod*e"
+Output: "lecoe"
+Explanation: Performing the removals from left to right:
+- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
+- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
+- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
+There are no more stars, so we return "lecoe".
+ +

Example 2:

+ +
Input: s = "erase*****"
+Output: ""
+Explanation: The entire string is removed, so we return an empty string.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase English letters and stars *.
  • +
  • The operation above can be performed on s.
  • +
+
\ No newline at end of file diff --git a/2391-minimum-amount-of-time-to-collect-garbage/2391-minimum-amount-of-time-to-collect-garbage.cpp b/2391-minimum-amount-of-time-to-collect-garbage/2391-minimum-amount-of-time-to-collect-garbage.cpp new file mode 100644 index 00000000..80607765 --- /dev/null +++ b/2391-minimum-amount-of-time-to-collect-garbage/2391-minimum-amount-of-time-to-collect-garbage.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + + int n = garbage.size(); + + int totalTime = 0; + + unordered_map mp; + + for(int i = 0; i < n; ++i) + { + for(auto& gar : garbage[i]) + ++mp[gar]; + } + + for(int i = 0; i < n; ++i) + { + int p = 0, g = 0, m = 0; + + for(auto& gar : garbage[i]) + { + if(gar == 'P') + ++p; + else if(gar == 'G') + ++g; + else + ++m; + } + + totalTime += (p+g+m); + + if(i-1 >= 0) + { + if(mp['P']) totalTime += travel[i-1]; + if(mp['G']) totalTime += travel[i-1]; + if(mp['M']) totalTime += travel[i-1]; + } + + mp['P'] -= p; + mp['M'] -= m; + mp['G'] -= g; + + if(mp['P'] == 0) + mp.erase('P'); + if(mp['G'] == 0) + mp.erase('G'); + if(mp['M'] == 0) + mp.erase('M'); + + } + + return totalTime; + + } +}; \ No newline at end of file diff --git a/2391-minimum-amount-of-time-to-collect-garbage/NOTES.md b/2391-minimum-amount-of-time-to-collect-garbage/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2391-minimum-amount-of-time-to-collect-garbage/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2391-minimum-amount-of-time-to-collect-garbage/README.md b/2391-minimum-amount-of-time-to-collect-garbage/README.md new file mode 100644 index 00000000..8a44ad8c --- /dev/null +++ b/2391-minimum-amount-of-time-to-collect-garbage/README.md @@ -0,0 +1,56 @@ +

2391. Minimum Amount of Time to Collect Garbage

Medium


You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.

+ +

You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.

+ +

There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.

+ +

Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.

+ +

Return the minimum number of minutes needed to pick up all the garbage.

+ +

 

+

Example 1:

+ +
Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
+Output: 21
+Explanation:
+The paper garbage truck:
+1. Travels from house 0 to house 1
+2. Collects the paper garbage at house 1
+3. Travels from house 1 to house 2
+4. Collects the paper garbage at house 2
+Altogether, it takes 8 minutes to pick up all the paper garbage.
+The glass garbage truck:
+1. Collects the glass garbage at house 0
+2. Travels from house 0 to house 1
+3. Travels from house 1 to house 2
+4. Collects the glass garbage at house 2
+5. Travels from house 2 to house 3
+6. Collects the glass garbage at house 3
+Altogether, it takes 13 minutes to pick up all the glass garbage.
+Since there is no metal garbage, we do not need to consider the metal garbage truck.
+Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.
+
+ +

Example 2:

+ +
Input: garbage = ["MMM","PGM","GP"], travel = [3,10]
+Output: 37
+Explanation:
+The metal garbage truck takes 7 minutes to pick up all the metal garbage.
+The paper garbage truck takes 15 minutes to pick up all the paper garbage.
+The glass garbage truck takes 15 minutes to pick up all the glass garbage.
+It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= garbage.length <= 105
  • +
  • garbage[i] consists of only the letters 'M', 'P', and 'G'.
  • +
  • 1 <= garbage[i].length <= 10
  • +
  • travel.length == garbage.length - 1
  • +
  • 1 <= travel[i] <= 100
  • +
+
\ No newline at end of file diff --git a/2392-build-a-matrix-with-conditions/2392-build-a-matrix-with-conditions.cpp b/2392-build-a-matrix-with-conditions/2392-build-a-matrix-with-conditions.cpp new file mode 100644 index 00000000..356083ec --- /dev/null +++ b/2392-build-a-matrix-with-conditions/2392-build-a-matrix-with-conditions.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + vector findOrder(int k, vector>& dependencies) { + + vector> adj(k + 1); + vector indegree(k + 1); + for(auto dependency: dependencies) { + adj[dependency[0]].push_back(dependency[1]); + indegree[dependency[1]]++; + } + + queue q; + for(int i = 1; i <= k; i++) { + if(indegree[i] == 0) { + q.push(i); + } + } + + int cnt = 0; + vector order; + while(!q.empty()) { + + int cur = q.front(); + q.pop(); + + cnt++; + order.push_back(cur); + + for(int nbr: adj[cur]) { + indegree[nbr]--; + + if(indegree[nbr] == 0) { + q.push(nbr); + } + } + } + + if(cnt == k) return order; + return {}; + } + + vector> buildMatrix(int k, vector>& rowConditions, vector>& colConditions) { + vector rowArray = findOrder(k, rowConditions); + vector colArray = findOrder(k, colConditions); + + + if(rowArray.size() == 0 || colArray.size() == 0) { + return {}; + } + + vector> ind(k); + + for(int i = 0; i < k; i++) { + ind[rowArray[i] - 1].first = i; + ind[colArray[i] - 1].second = i; + } + + vector> result(k, vector(k, 0)); + + for(int i = 0; i < k; i++) { + result[ind[i].first][ind[i].second] = i + 1; + } + return result; + } +}; \ No newline at end of file diff --git a/2392-build-a-matrix-with-conditions/README.md b/2392-build-a-matrix-with-conditions/README.md new file mode 100644 index 00000000..83a8ca6c --- /dev/null +++ b/2392-build-a-matrix-with-conditions/README.md @@ -0,0 +1,55 @@ +

2392. Build a Matrix With Conditions

Hard


You are given a positive integer k. You are also given:

+ +
    +
  • a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
  • +
  • a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
  • +
+ +

The two arrays contain integers from 1 to k.

+ +

You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.

+ +

The matrix should also satisfy the following conditions:

+ +
    +
  • The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.
  • +
  • The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.
  • +
+ +

Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.

+ +

 

+

Example 1:

+ +
Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]
+Output: [[3,0,0],[0,0,1],[0,2,0]]
+Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.
+The row conditions are the following:
+- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.
+- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.
+The column conditions are the following:
+- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.
+- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.
+Note that there may be multiple correct answers.
+
+ +

Example 2:

+ +
Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]
+Output: []
+Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.
+No matrix can satisfy all the conditions, so we return the empty matrix.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= k <= 400
  • +
  • 1 <= rowConditions.length, colConditions.length <= 104
  • +
  • rowConditions[i].length == colConditions[i].length == 2
  • +
  • 1 <= abovei, belowi, lefti, righti <= k
  • +
  • abovei != belowi
  • +
  • lefti != righti
  • +
+
\ No newline at end of file diff --git a/2402-meeting-rooms-iii/2402-meeting-rooms-iii.cpp b/2402-meeting-rooms-iii/2402-meeting-rooms-iii.cpp new file mode 100644 index 00000000..bc237167 --- /dev/null +++ b/2402-meeting-rooms-iii/2402-meeting-rooms-iii.cpp @@ -0,0 +1,66 @@ + +class Solution { +public: + int mostBooked(int n, vector>& meetings) { + + int m = meetings.size(); + + int roomOccupied = 0; + + sort(meetings.begin(), meetings.end()); + + vector roomCount(n, 0); + + priority_queue, vector>, greater>> meetingRooms; // EndTime, RoomNumber + + priority_queue, greater> availableRooms; + + for(int room = 0; room < n; ++room) + availableRooms.push(room); + + for(auto& meet : meetings) + { + long long start = meet[0]; + long long end = meet[1]; + long long duration = end - start; + + while(!meetingRooms.empty() and meetingRooms.top().first <= start) + { + int room = meetingRooms.top().second; + availableRooms.push(room); + meetingRooms.pop(); + } + + if(!availableRooms.empty()) + { + int room = availableRooms.top(); + availableRooms.pop(); + meetingRooms.push({end, room}); + ++roomCount[room]; + } + else + { + int room = meetingRooms.top().second; + long long endTime = meetingRooms.top().first; + meetingRooms.pop(); + endTime += duration; + meetingRooms.push({endTime, room}); + ++roomCount[room]; + } + } + + int resultRoom = -1; + int maxUse = 0; + + for(int i = 0; i < n; ++i) + { + if(roomCount[i] > maxUse) + { + resultRoom = i; + maxUse = roomCount[i]; + } + } + + return resultRoom; + } +}; \ No newline at end of file diff --git a/2402-meeting-rooms-iii/NOTES.md b/2402-meeting-rooms-iii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2402-meeting-rooms-iii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2402-meeting-rooms-iii/README.md b/2402-meeting-rooms-iii/README.md new file mode 100644 index 00000000..fffc9ee8 --- /dev/null +++ b/2402-meeting-rooms-iii/README.md @@ -0,0 +1,57 @@ +

2402. Meeting Rooms III

Hard


You are given an integer n. There are n rooms numbered from 0 to n - 1.

+ +

You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.

+ +

Meetings are allocated to rooms in the following manner:

+ +
    +
  1. Each meeting will take place in the unused room with the lowest number.
  2. +
  3. If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
  4. +
  5. When a room becomes unused, meetings that have an earlier original start time should be given the room.
  6. +
+ +

Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.

+ +

A half-closed interval [a, b) is the interval between a and b including a and not including b.

+ +

 

+

Example 1:

+ +
Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
+Output: 0
+Explanation:
+- At time 0, both rooms are not being used. The first meeting starts in room 0.
+- At time 1, only room 1 is not being used. The second meeting starts in room 1.
+- At time 2, both rooms are being used. The third meeting is delayed.
+- At time 3, both rooms are being used. The fourth meeting is delayed.
+- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).
+- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).
+Both rooms 0 and 1 held 2 meetings, so we return 0. 
+
+ +

Example 2:

+ +
Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
+Output: 1
+Explanation:
+- At time 1, all three rooms are not being used. The first meeting starts in room 0.
+- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.
+- At time 3, only room 2 is not being used. The third meeting starts in room 2.
+- At time 4, all three rooms are being used. The fourth meeting is delayed.
+- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).
+- At time 6, all three rooms are being used. The fifth meeting is delayed.
+- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).
+Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 1 <= meetings.length <= 105
  • +
  • meetings[i].length == 2
  • +
  • 0 <= starti < endi <= 5 * 105
  • +
  • All the values of starti are unique.
  • +
+
\ No newline at end of file diff --git a/2405-optimal-partition-of-string/2405-optimal-partition-of-string.cpp b/2405-optimal-partition-of-string/2405-optimal-partition-of-string.cpp new file mode 100644 index 00000000..7566a6f8 --- /dev/null +++ b/2405-optimal-partition-of-string/2405-optimal-partition-of-string.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int partitionString(string s) { + + int i = 0, j = s.size(); + + int part = 1; + map mp; + + while(i < j) + { + if(mp.find(s[i]) != mp.end()) + { + ++part; + mp.clear(); + } + ++mp[s[i]]; + ++i; + } + + return part; + + } +}; \ No newline at end of file diff --git a/2405-optimal-partition-of-string/NOTES.md b/2405-optimal-partition-of-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2405-optimal-partition-of-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2405-optimal-partition-of-string/README.md b/2405-optimal-partition-of-string/README.md new file mode 100644 index 00000000..bb11394a --- /dev/null +++ b/2405-optimal-partition-of-string/README.md @@ -0,0 +1,32 @@ +

2405. Optimal Partition of String

Medium


Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.

+ +

Return the minimum number of substrings in such a partition.

+ +

Note that each character should belong to exactly one substring in a partition.

+ +

 

+

Example 1:

+ +
Input: s = "abacaba"
+Output: 4
+Explanation:
+Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
+It can be shown that 4 is the minimum number of substrings needed.
+
+ +

Example 2:

+ +
Input: s = "ssssss"
+Output: 6
+Explanation:
+The only valid partition is ("s","s","s","s","s","s").
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only English lowercase letters.
  • +
+
\ No newline at end of file diff --git a/2418-sort-the-people/2418-sort-the-people.cpp b/2418-sort-the-people/2418-sort-the-people.cpp new file mode 100644 index 00000000..eb04256d --- /dev/null +++ b/2418-sort-the-people/2418-sort-the-people.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + + vector> here; + + for(int i = 0; i < heights.size(); ++i) + here.push_back({heights[i], i}); + + sort(here.rbegin(), here.rend()); + + vector ans; + + for(int i = 0; i < names.size(); ++i) + ans.push_back(names[here[i].second]); + + return ans; + + } +}; \ No newline at end of file diff --git a/2418-sort-the-people/NOTES.md b/2418-sort-the-people/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2418-sort-the-people/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2418-sort-the-people/README.md b/2418-sort-the-people/README.md new file mode 100644 index 00000000..2f291942 --- /dev/null +++ b/2418-sort-the-people/README.md @@ -0,0 +1,33 @@ +

2418. Sort the People

Easy


You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.

+ +

For each index i, names[i] and heights[i] denote the name and height of the ith person.

+ +

Return names sorted in descending order by the people's heights.

+ +

 

+

Example 1:

+ +
Input: names = ["Mary","John","Emma"], heights = [180,165,170]
+Output: ["Mary","Emma","John"]
+Explanation: Mary is the tallest, followed by Emma and John.
+
+ +

Example 2:

+ +
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
+Output: ["Bob","Alice","Bob"]
+Explanation: The first Bob is the tallest, followed by Alice and the second Bob.
+
+ +

 

+

Constraints:

+ +
    +
  • n == names.length == heights.length
  • +
  • 1 <= n <= 103
  • +
  • 1 <= names[i].length <= 20
  • +
  • 1 <= heights[i] <= 105
  • +
  • names[i] consists of lower and upper case English letters.
  • +
  • All the values of heights are distinct.
  • +
+
\ No newline at end of file diff --git a/2421-number-of-good-paths/2421-number-of-good-paths.cpp b/2421-number-of-good-paths/2421-number-of-good-paths.cpp new file mode 100644 index 00000000..b7ea45ef --- /dev/null +++ b/2421-number-of-good-paths/2421-number-of-good-paths.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int find(vector& y,int i) { + if(i==y[i]) return i; + y[i]=find(y,y[i]); + return y[i]; + } + int numberOfGoodPaths(vector& vals, vector>& edges) { + int n = vals.size(),m=edges.size(),ans=0; + vector> x(n); + vector y(n); + for(int i=0;i& a,vector& b){ + return max(vals[a[0]],vals[a[1]])x[b][0]) y[b]=a; + else y[a]=b; + } + else{ + y[a]=b; + ans+=x[a][1]*x[b][1]; + x[b][1]+=x[a][1]; + } + } + return ans+n; + } +}; \ No newline at end of file diff --git a/2421-number-of-good-paths/README.md b/2421-number-of-good-paths/README.md new file mode 100644 index 00000000..2c710218 --- /dev/null +++ b/2421-number-of-good-paths/README.md @@ -0,0 +1,55 @@ +

2421. Number of Good Paths

Hard


There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.

+ +

You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

+ +

A good path is a simple path that satisfies the following conditions:

+ +
    +
  1. The starting node and the ending node have the same value.
  2. +
  3. All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
  4. +
+ +

Return the number of distinct good paths.

+ +

Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.

+ +

 

+

Example 1:

+ +
Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
+Output: 6
+Explanation: There are 5 good paths consisting of a single node.
+There is 1 additional good path: 1 -> 0 -> 2 -> 4.
+(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)
+Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].
+
+ +

Example 2:

+ +
Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]
+Output: 7
+Explanation: There are 5 good paths consisting of a single node.
+There are 2 additional good paths: 0 -> 1 and 2 -> 3.
+
+ +

Example 3:

+ +
Input: vals = [1], edges = []
+Output: 1
+Explanation: The tree consists of only one node, so there is one good path.
+
+ +

 

+

Constraints:

+ +
    +
  • n == vals.length
  • +
  • 1 <= n <= 3 * 104
  • +
  • 0 <= vals[i] <= 105
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • edges represents a valid tree.
  • +
+
\ No newline at end of file diff --git a/2433-find-the-original-array-of-prefix-xor/2433-find-the-original-array-of-prefix-xor.cpp b/2433-find-the-original-array-of-prefix-xor/2433-find-the-original-array-of-prefix-xor.cpp new file mode 100644 index 00000000..d6984685 --- /dev/null +++ b/2433-find-the-original-array-of-prefix-xor/2433-find-the-original-array-of-prefix-xor.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector findArray(vector& pref) { + + int n = pref.size(); + + vector ans(n); + + ans[0] = pref[0]; + + int currXor = pref[0]; + + for(int i = 1; i < n; ++i) + { + int mask = 0; + int newXor = pref[i]; + + for(int i = 0; i < 32; ++i) + { + if(!(currXor & (1 << i)) and (newXor & (1 << i))) + mask |= (1<2433. Find The Original Array of Prefix Xor

Medium


You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:

+ +
    +
  • pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
  • +
+ +

Note that ^ denotes the bitwise-xor operation.

+ +

It can be proven that the answer is unique.

+ +

 

+

Example 1:

+ +
Input: pref = [5,2,0,3,1]
+Output: [5,7,2,3,2]
+Explanation: From the array [5,7,2,3,2] we have the following:
+- pref[0] = 5.
+- pref[1] = 5 ^ 7 = 2.
+- pref[2] = 5 ^ 7 ^ 2 = 0.
+- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
+- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
+
+ +

Example 2:

+ +
Input: pref = [13]
+Output: [13]
+Explanation: We have pref[0] = arr[0] = 13.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pref.length <= 105
  • +
  • 0 <= pref[i] <= 106
  • +
+
\ No newline at end of file diff --git a/2439-minimize-maximum-of-array/2439-minimize-maximum-of-array.cpp b/2439-minimize-maximum-of-array/2439-minimize-maximum-of-array.cpp new file mode 100644 index 00000000..06122c95 --- /dev/null +++ b/2439-minimize-maximum-of-array/2439-minimize-maximum-of-array.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minimizeArrayValue(vector& nums) { + + int n = nums.size(); + long long sum = nums[0]; + long long mini = nums[0]; + + for(int i = 1; i mini) + { + long long avg = sum/(i+1); + if(avg >= mini) + { + if(sum % (i+1)) + mini = avg + 1; + else + mini = avg; + } + } + } + + return mini; + } +}; \ No newline at end of file diff --git a/2439-minimize-maximum-of-array/NOTES.md b/2439-minimize-maximum-of-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2439-minimize-maximum-of-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2441-largest-positive-integer-that-exists-with-its-negative/2441-largest-positive-integer-that-exists-with-its-negative.cpp b/2441-largest-positive-integer-that-exists-with-its-negative/2441-largest-positive-integer-that-exists-with-its-negative.cpp new file mode 100644 index 00000000..03f004a3 --- /dev/null +++ b/2441-largest-positive-integer-that-exists-with-its-negative/2441-largest-positive-integer-that-exists-with-its-negative.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int findMaxK(vector& nums) { + + set st(nums.begin(), nums.end()); + int ans = -1; + + for(auto& ele : nums) + { + if(ele > 0) + { + if(st.count(-ele)) + ans = max(ans, ele); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/2441-largest-positive-integer-that-exists-with-its-negative/NOTES.md b/2441-largest-positive-integer-that-exists-with-its-negative/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2441-largest-positive-integer-that-exists-with-its-negative/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2441-largest-positive-integer-that-exists-with-its-negative/README.md b/2441-largest-positive-integer-that-exists-with-its-negative/README.md new file mode 100644 index 00000000..6a824672 --- /dev/null +++ b/2441-largest-positive-integer-that-exists-with-its-negative/README.md @@ -0,0 +1,35 @@ +

2441. Largest Positive Integer That Exists With Its Negative

Easy


Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.

+ +

Return the positive integer k. If there is no such integer, return -1.

+ +

 

+

Example 1:

+ +
Input: nums = [-1,2,-3,3]
+Output: 3
+Explanation: 3 is the only valid k we can find in the array.
+
+ +

Example 2:

+ +
Input: nums = [-1,10,6,7,-7,1]
+Output: 7
+Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
+
+ +

Example 3:

+ +
Input: nums = [-10,8,6,7,-2,-3]
+Output: -1
+Explanation: There is no a single valid k, we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -1000 <= nums[i] <= 1000
  • +
  • nums[i] != 0
  • +
+
\ No newline at end of file diff --git a/2444-count-subarrays-with-fixed-bounds/2444-count-subarrays-with-fixed-bounds.cpp b/2444-count-subarrays-with-fixed-bounds/2444-count-subarrays-with-fixed-bounds.cpp new file mode 100644 index 00000000..8b7a11da --- /dev/null +++ b/2444-count-subarrays-with-fixed-bounds/2444-count-subarrays-with-fixed-bounds.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long countSubarrays(vector& nums, int minK, int maxK) { + + int n = nums.size(); + long long res = 0; + + long long maxiIdx = -1, miniIdx = -1, badIdx = -1; + for(int i = 0; i maxK or nums[i] < minK) + badIdx = i; + if(nums[i] == maxK) maxiIdx = i; + if(nums[i] == minK) miniIdx = i; + res += max(0LL, (min(maxiIdx,miniIdx) - badIdx)); + } + + return res; + + } +}; \ No newline at end of file diff --git a/2444-count-subarrays-with-fixed-bounds/NOTES.md b/2444-count-subarrays-with-fixed-bounds/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2444-count-subarrays-with-fixed-bounds/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2444-count-subarrays-with-fixed-bounds/README.md b/2444-count-subarrays-with-fixed-bounds/README.md new file mode 100644 index 00000000..ab1ef885 --- /dev/null +++ b/2444-count-subarrays-with-fixed-bounds/README.md @@ -0,0 +1,36 @@ +

2444. Count Subarrays With Fixed Bounds

Hard


You are given an integer array nums and two integers minK and maxK.

+ +

A fixed-bound subarray of nums is a subarray that satisfies the following conditions:

+ +
    +
  • The minimum value in the subarray is equal to minK.
  • +
  • The maximum value in the subarray is equal to maxK.
  • +
+ +

Return the number of fixed-bound subarrays.

+ +

A subarray is a contiguous part of an array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
+Output: 2
+Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
+
+ +

Example 2:

+ +
Input: nums = [1,1,1,1], minK = 1, maxK = 1
+Output: 10
+Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • 1 <= nums[i], minK, maxK <= 106
  • +
+
\ No newline at end of file diff --git a/2448-minimum-cost-to-make-array-equal/2448-minimum-cost-to-make-array-equal.cpp b/2448-minimum-cost-to-make-array-equal/2448-minimum-cost-to-make-array-equal.cpp new file mode 100644 index 00000000..a6f7c0c5 --- /dev/null +++ b/2448-minimum-cost-to-make-array-equal/2448-minimum-cost-to-make-array-equal.cpp @@ -0,0 +1,42 @@ +#define ll long long int + +class Solution { +public: + long long minCost(vector& nums, vector& cost) { + + int n = nums.size(); + + vector> vp; + + for(int i = 0; i < n; ++i) + { + vp.push_back({nums[i], cost[i]}); + } + + sort(vp.begin(), vp.end()); + + ll median, sum = 0, tot = 0; + + for(auto itr : vp) + { + sum += itr.second; + } + + ll here = 0, ans = 0; + + ll i = 0; + + while(i < n and here < (sum + 1) / 2) + { + here += vp[i].second; + median = vp[i++].first; + } + + for(int i = 0; i < n; ++i) + { + ans += (abs(nums[i] - median) * cost[i]); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2448-minimum-cost-to-make-array-equal/README.md b/2448-minimum-cost-to-make-array-equal/README.md new file mode 100644 index 00000000..053f9dce --- /dev/null +++ b/2448-minimum-cost-to-make-array-equal/README.md @@ -0,0 +1,41 @@ +

2448. Minimum Cost to Make Array Equal

Hard


You are given two 0-indexed arrays nums and cost consisting each of n positive integers.

+ +

You can do the following operation any number of times:

+ +
    +
  • Increase or decrease any element of the array nums by 1.
  • +
+ +

The cost of doing one operation on the ith element is cost[i].

+ +

Return the minimum total cost such that all the elements of the array nums become equal.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,5,2], cost = [2,3,1,14]
+Output: 8
+Explanation: We can make all the elements equal to 2 in the following way:
+- Increase the 0th element one time. The cost is 2.
+- Decrease the 1st element one time. The cost is 3.
+- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
+The total cost is 2 + 3 + 3 = 8.
+It can be shown that we cannot make the array equal with a smaller cost.
+
+ +

Example 2:

+ +
Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]
+Output: 0
+Explanation: All the elements are already equal, so no operations are needed.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length == cost.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i], cost[i] <= 106
  • +
+
\ No newline at end of file diff --git a/2462-total-cost-to-hire-k-workers/2462-total-cost-to-hire-k-workers.cpp b/2462-total-cost-to-hire-k-workers/2462-total-cost-to-hire-k-workers.cpp new file mode 100644 index 00000000..b494c152 --- /dev/null +++ b/2462-total-cost-to-hire-k-workers/2462-total-cost-to-hire-k-workers.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + long long totalCost(vector& costs, int k, int candidates) { + + long long ans=0; + priority_queue,greater> pq1,pq2; + + int cnt = 0; + int i=0; + int j=costs.size()-1; + + while(cnt=i) pq2.push(costs[j--]); + + int cost1 = pq1.size()>0?pq1.top():INT_MAX; + int cost2 = pq2.size()>0?pq2.top():INT_MAX; + + if(cost1<=cost2){ + + ans += cost1; + pq1.pop(); + } + else{ + + ans += cost2; + pq2.pop(); + } + + cnt++; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2462-total-cost-to-hire-k-workers/NOTES.md b/2462-total-cost-to-hire-k-workers/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2462-total-cost-to-hire-k-workers/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2462-total-cost-to-hire-k-workers/README.md b/2462-total-cost-to-hire-k-workers/README.md new file mode 100644 index 00000000..91a9d501 --- /dev/null +++ b/2462-total-cost-to-hire-k-workers/README.md @@ -0,0 +1,50 @@ +

2462. Total Cost to Hire K Workers

Medium


You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.

+ +

You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:

+ +
    +
  • You will run k sessions and hire exactly one worker in each session.
  • +
  • In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index. +
      +
    • For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].
    • +
    • In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.
    • +
    +
  • +
  • If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
  • +
  • A worker can only be chosen once.
  • +
+ +

Return the total cost to hire exactly k workers.

+ +

 

+

Example 1:

+ +
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
+Output: 11
+Explanation: We hire 3 workers in total. The total cost is initially 0.
+- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
+- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
+- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
+The total hiring cost is 11.
+
+ +

Example 2:

+ +
Input: costs = [1,2,4,1], k = 3, candidates = 3
+Output: 4
+Explanation: We hire 3 workers in total. The total cost is initially 0.
+- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
+- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
+- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
+The total hiring cost is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= costs.length <= 105
  • +
  • 1 <= costs[i] <= 105
  • +
  • 1 <= k, candidates <= costs.length
  • +
+
\ No newline at end of file diff --git a/2466-count-ways-to-build-good-strings/2466-count-ways-to-build-good-strings.cpp b/2466-count-ways-to-build-good-strings/2466-count-ways-to-build-good-strings.cpp new file mode 100644 index 00000000..09515186 --- /dev/null +++ b/2466-count-ways-to-build-good-strings/2466-count-ways-to-build-good-strings.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + + int mod = 1e9 + 7; + + int helper(int i, int low, int high, int zero, int one, vector& dp) + { + if( i > high) + return 0; + + if(dp[i] != -1) + return dp[i]; + + int ans = 0; + + if( i >= low and i <= high) + ++ans; + + return dp[i] = (ans + helper(i + zero,low, high, zero , one, dp) + helper(i + one, low, high, zero, one, dp)) % mod; + } + + int countGoodStrings(int low, int high, int zero, int one) { + + vector dp(high+1, -1); + + return helper(0, low, high, zero, one, dp) % mod; + + } +}; + + + diff --git a/2466-count-ways-to-build-good-strings/README.md b/2466-count-ways-to-build-good-strings/README.md new file mode 100644 index 00000000..91b10e79 --- /dev/null +++ b/2466-count-ways-to-build-good-strings/README.md @@ -0,0 +1,39 @@ +

2466. Count Ways To Build Good Strings

Medium


Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:

+ +
    +
  • Append the character '0' zero times.
  • +
  • Append the character '1' one times.
  • +
+ +

This can be performed any number of times.

+ +

A good string is a string constructed by the above process having a length between low and high (inclusive).

+ +

Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: low = 3, high = 3, zero = 1, one = 1
+Output: 8
+Explanation: 
+One possible valid good string is "011". 
+It can be constructed as follows: "" -> "0" -> "01" -> "011". 
+All binary strings from "000" to "111" are good strings in this example.
+
+ +

Example 2:

+ +
Input: low = 2, high = 3, zero = 1, one = 2
+Output: 5
+Explanation: The good strings are "00", "11", "000", "110", and "011".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= low <= high <= 105
  • +
  • 1 <= zero, one <= low
  • +
+
\ No newline at end of file diff --git a/2477-minimum-fuel-cost-to-report-to-the-capital/2477-minimum-fuel-cost-to-report-to-the-capital.cpp b/2477-minimum-fuel-cost-to-report-to-the-capital/2477-minimum-fuel-cost-to-report-to-the-capital.cpp new file mode 100644 index 00000000..12c28b39 --- /dev/null +++ b/2477-minimum-fuel-cost-to-report-to-the-capital/2477-minimum-fuel-cost-to-report-to-the-capital.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + long long ans = 0; + + int dfs(int curr, int prev, vector adj[], int seats) + { + int people = 1; + + for(auto itr : adj[curr]) + { + if(itr == prev) + continue; + people += dfs(itr, curr, adj, seats); + } + + if(curr != 0) + ans += (long)(ceil((double)people/seats)); + + return people; + } + + long long minimumFuelCost(vector>& roads, int seats) { + + int n = roads.size(); + vector adj[n+1]; + + for(auto itr : roads) + { + adj[itr[0]].push_back(itr[1]); + adj[itr[1]].push_back(itr[0]); + } + + dfs(0,-1,adj,seats); + + return ans; + + } +}; \ No newline at end of file diff --git a/2477-minimum-fuel-cost-to-report-to-the-capital/NOTES.md b/2477-minimum-fuel-cost-to-report-to-the-capital/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2477-minimum-fuel-cost-to-report-to-the-capital/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2482-difference-between-ones-and-zeros-in-row-and-column/2482-difference-between-ones-and-zeros-in-row-and-column.cpp b/2482-difference-between-ones-and-zeros-in-row-and-column/2482-difference-between-ones-and-zeros-in-row-and-column.cpp new file mode 100644 index 00000000..97f982b3 --- /dev/null +++ b/2482-difference-between-ones-and-zeros-in-row-and-column/2482-difference-between-ones-and-zeros-in-row-and-column.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector> onesMinusZeros(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector row(n, 0), col(m, 0); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1) + ++row[i], ++col[j]; + } + } + + vector> diff(n, vector(m)); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + diff[i][j] = (row[i] + col[j] - (m - row[i]) - (n - col[j])); + } + + return diff; + } +}; \ No newline at end of file diff --git a/2482-difference-between-ones-and-zeros-in-row-and-column/NOTES.md b/2482-difference-between-ones-and-zeros-in-row-and-column/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2482-difference-between-ones-and-zeros-in-row-and-column/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2482-difference-between-ones-and-zeros-in-row-and-column/README.md b/2482-difference-between-ones-and-zeros-in-row-and-column/README.md new file mode 100644 index 00000000..3353ff56 --- /dev/null +++ b/2482-difference-between-ones-and-zeros-in-row-and-column/README.md @@ -0,0 +1,55 @@ +

2482. Difference Between Ones and Zeros in Row and Column

Medium


You are given a 0-indexed m x n binary matrix grid.

+ +

A 0-indexed m x n difference matrix diff is created with the following procedure:

+ +
    +
  • Let the number of ones in the ith row be onesRowi.
  • +
  • Let the number of ones in the jth column be onesColj.
  • +
  • Let the number of zeros in the ith row be zerosRowi.
  • +
  • Let the number of zeros in the jth column be zerosColj.
  • +
  • diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
  • +
+ +

Return the difference matrix diff.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,1,1],[1,0,1],[0,0,1]]
+Output: [[0,0,4],[0,0,4],[-2,-2,2]]
+Explanation:
+- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0 
+- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0 
+- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4 
+- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0 
+- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0 
+- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4 
+- diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2
+- diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2
+- diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2
+
+ +

Example 2:

+ +
Input: grid = [[1,1,1],[1,1,1]]
+Output: [[5,5,5],[5,5,5]]
+Explanation:
+- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5
+- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5
+- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5
+- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5
+- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5
+- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 105
  • +
  • 1 <= m * n <= 105
  • +
  • grid[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/2483-minimum-penalty-for-a-shop/2483-minimum-penalty-for-a-shop.cpp b/2483-minimum-penalty-for-a-shop/2483-minimum-penalty-for-a-shop.cpp new file mode 100644 index 00000000..573c4245 --- /dev/null +++ b/2483-minimum-penalty-for-a-shop/2483-minimum-penalty-for-a-shop.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int bestClosingTime(string customers) { + + int n = customers.size(); + + int totPenalty = n; + int shopClosed = -1; + + vector> records; + + int customerCome = 0, customerNotCome = 0; + + for(int i = 0; i < n; ++i) + { + if(customers[i] == 'Y') + ++customerCome; + else + ++customerNotCome; + + records.push_back({customerCome, customerNotCome}); + } + + for(int i = 0; i <= n; ++i) + { + int notCameAndOpen = (i > 0 ? records[i-1].second : 0); + int cameAndClosed = (i == 0 ? records[n-1].first : records[n-1].first - records[i-1].first); + + if(notCameAndOpen + cameAndClosed < totPenalty) + { + totPenalty = notCameAndOpen + cameAndClosed; + shopClosed = i; + } + } + + return shopClosed; + + } +}; \ No newline at end of file diff --git a/2483-minimum-penalty-for-a-shop/NOTES.md b/2483-minimum-penalty-for-a-shop/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2483-minimum-penalty-for-a-shop/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2483-minimum-penalty-for-a-shop/README.md b/2483-minimum-penalty-for-a-shop/README.md new file mode 100644 index 00000000..eb9e9cc7 --- /dev/null +++ b/2483-minimum-penalty-for-a-shop/README.md @@ -0,0 +1,53 @@ +

2483. Minimum Penalty for a Shop

Medium


You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':

+ +
    +
  • if the ith character is 'Y', it means that customers come at the ith hour
  • +
  • whereas 'N' indicates that no customers come at the ith hour.
  • +
+ +

If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:

+ +
    +
  • For every hour when the shop is open and no customers come, the penalty increases by 1.
  • +
  • For every hour when the shop is closed and customers come, the penalty increases by 1.
  • +
+ +

Return the earliest hour at which the shop must be closed to incur a minimum penalty.

+ +

Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.

+ +

 

+

Example 1:

+ +
Input: customers = "YYNY"
+Output: 2
+Explanation: 
+- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
+- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
+- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
+- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
+- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
+Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
+
+ +

Example 2:

+ +
Input: customers = "NNNNN"
+Output: 0
+Explanation: It is best to close the shop at the 0th hour as no customers arrive.
+ +

Example 3:

+ +
Input: customers = "YYYY"
+Output: 4
+Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= customers.length <= 105
  • +
  • customers consists only of characters 'Y' and 'N'.
  • +
+
\ No newline at end of file diff --git a/2485-find-the-pivot-integer/2485-find-the-pivot-integer.cpp b/2485-find-the-pivot-integer/2485-find-the-pivot-integer.cpp new file mode 100644 index 00000000..2c01acd0 --- /dev/null +++ b/2485-find-the-pivot-integer/2485-find-the-pivot-integer.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int pivotInteger(int n) { + + int tot = (n*(n+1))/2; + + for(int i = 1; i <= n; ++i) + { + int left = (i*(i+1))/2; + int right = tot - left + i; + + if(left == right) + return i; + } + + return -1; + } +}; \ No newline at end of file diff --git a/2485-find-the-pivot-integer/NOTES.md b/2485-find-the-pivot-integer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2485-find-the-pivot-integer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2485-find-the-pivot-integer/README.md b/2485-find-the-pivot-integer/README.md new file mode 100644 index 00000000..12c9294c --- /dev/null +++ b/2485-find-the-pivot-integer/README.md @@ -0,0 +1,37 @@ +

2485. Find the Pivot Integer

Easy


Given a positive integer n, find the pivot integer x such that:

+ +
    +
  • The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.
  • +
+ +

Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.

+ +

 

+

Example 1:

+ +
Input: n = 8
+Output: 6
+Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.
+
+ +

Example 2:

+ +
Input: n = 1
+Output: 1
+Explanation: 1 is the pivot integer since: 1 = 1.
+
+ +

Example 3:

+ +
Input: n = 4
+Output: -1
+Explanation: It can be proved that no such integer exist.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/2486-append-characters-to-string-to-make-subsequence/2486-append-characters-to-string-to-make-subsequence.cpp b/2486-append-characters-to-string-to-make-subsequence/2486-append-characters-to-string-to-make-subsequence.cpp new file mode 100644 index 00000000..36e9a014 --- /dev/null +++ b/2486-append-characters-to-string-to-make-subsequence/2486-append-characters-to-string-to-make-subsequence.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int appendCharacters(string s, string t) { + + int idx = 0; + + for(int i = 0; i < s.size(); ++i) + { + if(t[idx] == s[i]) + ++idx; + if(idx == t.size()) + return 0; + } + + return t.size() - idx; + + } +}; \ No newline at end of file diff --git a/2486-append-characters-to-string-to-make-subsequence/README.md b/2486-append-characters-to-string-to-make-subsequence/README.md new file mode 100644 index 00000000..3029053c --- /dev/null +++ b/2486-append-characters-to-string-to-make-subsequence/README.md @@ -0,0 +1,40 @@ +

2486. Append Characters to String to Make Subsequence

Medium


You are given two strings s and t consisting of only lowercase English letters.

+ +

Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s.

+ +

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

+ +

 

+

Example 1:

+ +
Input: s = "coaching", t = "coding"
+Output: 4
+Explanation: Append the characters "ding" to the end of s so that s = "coachingding".
+Now, t is a subsequence of s ("coachingding").
+It can be shown that appending any 3 characters to the end of s will never make t a subsequence.
+
+ +

Example 2:

+ +
Input: s = "abcde", t = "a"
+Output: 0
+Explanation: t is already a subsequence of s ("abcde").
+
+ +

Example 3:

+ +
Input: s = "z", t = "abcde"
+Output: 5
+Explanation: Append the characters "abcde" to the end of s so that s = "zabcde".
+Now, t is a subsequence of s ("zabcde").
+It can be shown that appending any 4 characters to the end of s will never make t a subsequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 105
  • +
  • s and t consist only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2487-remove-nodes-from-linked-list/2487-remove-nodes-from-linked-list.cpp b/2487-remove-nodes-from-linked-list/2487-remove-nodes-from-linked-list.cpp new file mode 100644 index 00000000..6a24a27a --- /dev/null +++ b/2487-remove-nodes-from-linked-list/2487-remove-nodes-from-linked-list.cpp @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + if(!head or !head->next) + return head; + ListNode* newNode = removeNodes(head->next); + if(newNode->val > head->val) + return newNode; + head->next = newNode; + return head; + } +}; \ No newline at end of file diff --git a/2487-remove-nodes-from-linked-list/NOTES.md b/2487-remove-nodes-from-linked-list/NOTES.md new file mode 100644 index 00000000..4ebb8157 --- /dev/null +++ b/2487-remove-nodes-from-linked-list/NOTES.md @@ -0,0 +1,25 @@ +void delete_Node(ListNode* head) +{ +ListNode *maxNode = head, *curr = head; +while(curr && curr->next) +{ +if(curr->next->val < maxNode->val) +{ +ListNode* temp = curr->next; +curr->next = temp->next; +delete(temp); +} +else +{ +curr = curr->next; +maxNode = curr; +} +} +} +ListNode* removeNodes(ListNode* head) { +head = reverseList(head); +delete_Node(head); +head = reverseList(head); +return head; +} +}; \ No newline at end of file diff --git a/2487-remove-nodes-from-linked-list/README.md b/2487-remove-nodes-from-linked-list/README.md new file mode 100644 index 00000000..85da83fc --- /dev/null +++ b/2487-remove-nodes-from-linked-list/README.md @@ -0,0 +1,32 @@ +

2487. Remove Nodes From Linked List

Medium


You are given the head of a linked list.

+ +

Remove every node which has a node with a strictly greater value anywhere to the right side of it.

+ +

Return the head of the modified linked list.

+ +

 

+

Example 1:

+ +
Input: head = [5,2,13,3,8]
+Output: [13,8]
+Explanation: The nodes that should be removed are 5, 2 and 3.
+- Node 13 is to the right of node 5.
+- Node 13 is to the right of node 2.
+- Node 8 is to the right of node 3.
+
+ +

Example 2:

+ +
Input: head = [1,1,1,1]
+Output: [1,1,1,1]
+Explanation: Every node has value 1, so no nodes are removed.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [1, 105].
  • +
  • 1 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/2492-minimum-score-of-a-path-between-two-cities/2492-minimum-score-of-a-path-between-two-cities.cpp b/2492-minimum-score-of-a-path-between-two-cities/2492-minimum-score-of-a-path-between-two-cities.cpp new file mode 100644 index 00000000..e110cd1f --- /dev/null +++ b/2492-minimum-score-of-a-path-between-two-cities/2492-minimum-score-of-a-path-between-two-cities.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + + void dfs(int sv, vector> adj[], vector& visited) + { + visited[sv] = true; + for(auto itr : adj[sv]) + { + if(!visited[itr.first]) + dfs(itr.first,adj,visited); + } + } + + int minScore(int n, vector>& roads) { + + vector> adj[n+1]; + + for(auto itr : roads) + { + adj[itr[0]].push_back({itr[1],itr[2]}); + adj[itr[1]].push_back({itr[0],itr[2]}); + } + + vector visited(n+1,false); + + dfs(1,adj,visited); + int ans = INT_MAX; + + for(auto itr : roads) + { + if(visited[itr[0]] and visited[itr[1]]) + ans = min(ans,itr[2]); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2492-minimum-score-of-a-path-between-two-cities/NOTES.md b/2492-minimum-score-of-a-path-between-two-cities/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2492-minimum-score-of-a-path-between-two-cities/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2492-minimum-score-of-a-path-between-two-cities/README.md b/2492-minimum-score-of-a-path-between-two-cities/README.md new file mode 100644 index 00000000..e7bd11d5 --- /dev/null +++ b/2492-minimum-score-of-a-path-between-two-cities/README.md @@ -0,0 +1,44 @@ +

2492. Minimum Score of a Path Between Two Cities

Medium


You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected.

+ +

The score of a path between two cities is defined as the minimum distance of a road in this path.

+ +

Return the minimum possible score of a path between cities 1 and n.

+ +

Note:

+ +
    +
  • A path is a sequence of roads between two cities.
  • +
  • It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path.
  • +
  • The test cases are generated such that there is at least one path between 1 and n.
  • +
+ +

 

+

Example 1:

+ +
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
+Output: 5
+Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
+It can be shown that no other path has less score.
+
+ +

Example 2:

+ +
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
+Output: 2
+Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 105
  • +
  • 1 <= roads.length <= 105
  • +
  • roads[i].length == 3
  • +
  • 1 <= ai, bi <= n
  • +
  • ai != bi
  • +
  • 1 <= distancei <= 104
  • +
  • There are no repeated edges.
  • +
  • There is at least one path between 1 and n.
  • +
+
\ No newline at end of file diff --git a/2501-longest-square-streak-in-an-array/2501-longest-square-streak-in-an-array.cpp b/2501-longest-square-streak-in-an-array/2501-longest-square-streak-in-an-array.cpp new file mode 100644 index 00000000..902dbddb --- /dev/null +++ b/2501-longest-square-streak-in-an-array/2501-longest-square-streak-in-an-array.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int longestSquareStreak(vector& nums) { + + int n = nums.size(); + unordered_map mp; + + for(auto itr : nums) + ++mp[itr]; + + sort(nums.begin(),nums.end()); + + int ans = 1; + + for(int i = 0; i2501. Longest Square Streak in an Array

Medium


You are given an integer array nums. A subsequence of nums is called a square streak if:

+ +
    +
  • The length of the subsequence is at least 2, and
  • +
  • after sorting the subsequence, each element (except the first element) is the square of the previous number.
  • +
+ +

Return the length of the longest square streak in nums, or return -1 if there is no square streak.

+ +

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

+ +

 

+

Example 1:

+ +
Input: nums = [4,3,6,16,8,2]
+Output: 3
+Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].
+- 4 = 2 * 2.
+- 16 = 4 * 4.
+Therefore, [4,16,2] is a square streak.
+It can be shown that every subsequence of length 4 is not a square streak.
+
+ +

Example 2:

+ +
Input: nums = [2,3,5,6,7]
+Output: -1
+Explanation: There is no square streak in nums so return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • 2 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/2508-add-edges-to-make-degrees-of-all-nodes-even/2508-add-edges-to-make-degrees-of-all-nodes-even.cpp b/2508-add-edges-to-make-degrees-of-all-nodes-even/2508-add-edges-to-make-degrees-of-all-nodes-even.cpp new file mode 100644 index 00000000..8aaa12ca --- /dev/null +++ b/2508-add-edges-to-make-degrees-of-all-nodes-even/2508-add-edges-to-make-degrees-of-all-nodes-even.cpp @@ -0,0 +1,66 @@ +class Solution { +public: + + pair removeTwo(vector& odd, int one , int two) + { + vector res; + for(int i = 0; i<4; ++i) + { + if(i == one or i == two) continue; + res.push_back(odd[i]); + } + return {res[0],res[1]}; + } + + + bool isPossible(int n, vector>& edges) { + + vector degree(n+1,0); + set> allEdge; + vector odd; + + for(auto itr : edges) + { + ++degree[itr[0]]; + ++degree[itr[1]]; + + allEdge.insert({itr[0],itr[1]}); + allEdge.insert({itr[1],itr[0]}); + } + + for(int i = 0 ; i 4) return false; + + if(odd.size() == 2) + { + for(int i = 1; i<=n; ++i) + { + pair edge1 = {odd[0],i}; + pair edge2 = {odd[1],i}; + + if(allEdge.count(edge1) == 0 and allEdge.count(edge2) == 0) return true; + } + return false; + } + + if(odd.size() == 4) + { + for(int i = 1; i<4; ++i){ + pair edge1 = {odd[0],odd[i]}; + pair edge2 = removeTwo(odd,0,i); + + if(allEdge.count(edge1) == 0 and allEdge.count(edge2) == 0) return true; + } + return false; + } + + return false; + } +}; \ No newline at end of file diff --git a/2508-add-edges-to-make-degrees-of-all-nodes-even/NOTES.md b/2508-add-edges-to-make-degrees-of-all-nodes-even/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2508-add-edges-to-make-degrees-of-all-nodes-even/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2508-add-edges-to-make-degrees-of-all-nodes-even/README.md b/2508-add-edges-to-make-degrees-of-all-nodes-even/README.md new file mode 100644 index 00000000..55f111f4 --- /dev/null +++ b/2508-add-edges-to-make-degrees-of-all-nodes-even/README.md @@ -0,0 +1,41 @@ +

2508. Add Edges to Make Degrees of All Nodes Even

Hard


There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected.

+ +

You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.

+ +

Return true if it is possible to make the degree of each node in the graph even, otherwise return false.

+ +

The degree of a node is the number of edges connected to it.

+ +

 

+

Example 1:

+ +
Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]]
+Output: true
+Explanation: The above diagram shows a valid way of adding an edge.
+Every node in the resulting graph is connected to an even number of edges.
+
+ +

Example 2:

+ +
Input: n = 4, edges = [[1,2],[3,4]]
+Output: true
+Explanation: The above diagram shows a valid way of adding two edges.
+ +

Example 3:

+ +
Input: n = 4, edges = [[1,2],[1,3],[1,4]]
+Output: false
+Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n <= 105
  • +
  • 2 <= edges.length <= 105
  • +
  • edges[i].length == 2
  • +
  • 1 <= ai, bi <= n
  • +
  • ai != bi
  • +
  • There are no repeated edges.
  • +
+
\ No newline at end of file diff --git a/2512-reward-top-k-students/2512-reward-top-k-students.cpp b/2512-reward-top-k-students/2512-reward-top-k-students.cpp new file mode 100644 index 00000000..5bd540fb --- /dev/null +++ b/2512-reward-top-k-students/2512-reward-top-k-students.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + vector topStudents(vector& positive_feedback, vector& negative_feedback, vector& report, vector& student_id, int k) { + + map pos, neg; + int n = student_id.size(); + + for(auto itr : positive_feedback) + ++pos[itr]; + for(auto itr : negative_feedback) + ++neg[itr]; + + vector topK; + vector> vp; + + for(int i = 0; i current; + int score = 0; + int j = 0; + while(str[j] != '\0') + { + if(str[j] == ' ') + { + current.push_back(curr); + curr.clear(); + ++j; + } + else + { + curr += str[j]; + ++j; + } + } + if(!curr.empty()) + current.push_back(curr); + + for(auto itr : current) + { + if(pos[itr]) + score += 3; + if(neg[itr]) + score -= 1; + } + + vp.push_back({score,student_id[i]}); + } + + sort(vp.begin(),vp.end(),[&](const auto &a, const auto &b){ + if(a.first == b.first) + return a.second < b.second; + return a.first > b.first; + }); + + for(int i =0 ; i2512. Reward Top K Students

Medium


You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative.

+ +

Initially every student has 0 points. Each positive word in a feedback report increases the points of a student by 3, whereas each negative word decreases the points by 1.

+ +

You are given n feedback reports, represented by a 0-indexed string array report and a 0-indexed integer array student_id, where student_id[i] represents the ID of the student who has received the feedback report report[i]. The ID of each student is unique.

+ +

Given an integer k, return the top k students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.

+ +

 

+

Example 1:

+ +
Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2
+Output: [1,2]
+Explanation: 
+Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher.
+
+ +

Example 2:

+ +
Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is not studious","the student is smart"], student_id = [1,2], k = 2
+Output: [2,1]
+Explanation: 
+- The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points. 
+- The student with ID 2 has 1 positive feedback, so he has 3 points. 
+Since student 2 has more points, [2,1] is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= positive_feedback.length, negative_feedback.length <= 104
  • +
  • 1 <= positive_feedback[i].length, negative_feedback[j].length <= 100
  • +
  • Both positive_feedback[i] and negative_feedback[j] consists of lowercase English letters.
  • +
  • No word is present in both positive_feedback and negative_feedback.
  • +
  • n == report.length == student_id.length
  • +
  • 1 <= n <= 104
  • +
  • report[i] consists of lowercase English letters and spaces ' '.
  • +
  • There is a single space between consecutive words of report[i].
  • +
  • 1 <= report[i].length <= 100
  • +
  • 1 <= student_id[i] <= 109
  • +
  • All the values of student_id[i] are unique.
  • +
  • 1 <= k <= n
  • +
+
\ No newline at end of file diff --git a/2513-minimize-the-maximum-of-two-arrays/2513-minimize-the-maximum-of-two-arrays.cpp b/2513-minimize-the-maximum-of-two-arrays/2513-minimize-the-maximum-of-two-arrays.cpp new file mode 100644 index 00000000..d8e412bb --- /dev/null +++ b/2513-minimize-the-maximum-of-two-arrays/2513-minimize-the-maximum-of-two-arrays.cpp @@ -0,0 +1,31 @@ +#define ll long long int +class Solution { +public: + int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { + + ll start = 1, end = INT_MAX, mid; + ll lcm = divisor1; + lcm*= divisor2; + + lcm /= __gcd(divisor1,divisor2); + + ll ans = end; + while(start <= end) + { + mid = start + (end - start)/2; + + ll first = mid - (mid/divisor1); + ll second = mid - (mid/divisor2); + ll both = mid - (mid/divisor1) - (mid/divisor2) + mid/lcm; + + if(first >= uniqueCnt1 and second >= uniqueCnt2 and first + second - both >= uniqueCnt1 + uniqueCnt2) + { + ans = mid; + end = mid-1; + } + else + start = mid + 1; + } + return (int)ans; + } +}; \ No newline at end of file diff --git a/2513-minimize-the-maximum-of-two-arrays/README.md b/2513-minimize-the-maximum-of-two-arrays/README.md new file mode 100644 index 00000000..d2dbb416 --- /dev/null +++ b/2513-minimize-the-maximum-of-two-arrays/README.md @@ -0,0 +1,48 @@ +

2513. Minimize the Maximum of Two Arrays

Medium


We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:

+ +
    +
  • arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1.
  • +
  • arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2.
  • +
  • No integer is present in both arr1 and arr2.
  • +
+ +

Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.

+ +

 

+

Example 1:

+ +
Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3
+Output: 4
+Explanation: 
+We can distribute the first 4 natural numbers into arr1 and arr2.
+arr1 = [1] and arr2 = [2,3,4].
+We can see that both arrays satisfy all the conditions.
+Since the maximum value is 4, we return it.
+
+ +

Example 2:

+ +
Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1
+Output: 3
+Explanation: 
+Here arr1 = [1,2], and arr2 = [3] satisfy all conditions.
+Since the maximum value is 3, we return it.
+ +

Example 3:

+ +
Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2
+Output: 15
+Explanation: 
+Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6].
+It can be shown that it is not possible to obtain a lower maximum satisfying all conditions. 
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= divisor1, divisor2 <= 105
  • +
  • 1 <= uniqueCnt1, uniqueCnt2 < 109
  • +
  • 2 <= uniqueCnt1 + uniqueCnt2 <= 109
  • +
+
\ No newline at end of file diff --git a/2515-shortest-distance-to-target-string-in-a-circular-array/2515-shortest-distance-to-target-string-in-a-circular-array.cpp b/2515-shortest-distance-to-target-string-in-a-circular-array/2515-shortest-distance-to-target-string-in-a-circular-array.cpp new file mode 100644 index 00000000..0b11c2f8 --- /dev/null +++ b/2515-shortest-distance-to-target-string-in-a-circular-array/2515-shortest-distance-to-target-string-in-a-circular-array.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int closetTarget(vector& words, string target, int startIndex) { + + int n = words.size(); + int ans = INT_MAX; + for(int i = 0; i < words.size(); ++i) + { + if(words[i] == target) + { + ans = min(ans,abs(startIndex - i)); + ans = min({ans,n - i + startIndex, n - startIndex + i}); + } + } + + return (ans == INT_MAX) ? -1 : ans; + } +}; \ No newline at end of file diff --git a/2515-shortest-distance-to-target-string-in-a-circular-array/README.md b/2515-shortest-distance-to-target-string-in-a-circular-array/README.md new file mode 100644 index 00000000..baa658f1 --- /dev/null +++ b/2515-shortest-distance-to-target-string-in-a-circular-array/README.md @@ -0,0 +1,49 @@ +

2515. Shortest Distance to Target String in a Circular Array

Easy


You are given a 0-indexed circular string array words and a string target. A circular array means that the array's end connects to the array's beginning.

+ +
    +
  • Formally, the next element of words[i] is words[(i + 1) % n] and the previous element of words[i] is words[(i - 1 + n) % n], where n is the length of words.
  • +
+ +

Starting from startIndex, you can move to either the next word or the previous word with 1 step at a time.

+ +

Return the shortest distance needed to reach the string target. If the string target does not exist in words, return -1.

+ +

 

+

Example 1:

+ +
Input: words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1
+Output: 1
+Explanation: We start from index 1 and can reach "hello" by
+- moving 3 units to the right to reach index 4.
+- moving 2 units to the left to reach index 4.
+- moving 4 units to the right to reach index 0.
+- moving 1 unit to the left to reach index 0.
+The shortest distance to reach "hello" is 1.
+
+ +

Example 2:

+ +
Input: words = ["a","b","leetcode"], target = "leetcode", startIndex = 0
+Output: 1
+Explanation: We start from index 0 and can reach "leetcode" by
+- moving 2 units to the right to reach index 3.
+- moving 1 unit to the left to reach index 3.
+The shortest distance to reach "leetcode" is 1.
+ +

Example 3:

+ +
Input: words = ["i","eat","leetcode"], target = "ate", startIndex = 0
+Output: -1
+Explanation: Since "ate" does not exist in words, we return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] and target consist of only lowercase English letters.
  • +
  • 0 <= startIndex < words.length
  • +
+
\ No newline at end of file diff --git a/2516-take-k-of-each-character-from-left-and-right/2516-take-k-of-each-character-from-left-and-right.cpp b/2516-take-k-of-each-character-from-left-and-right/2516-take-k-of-each-character-from-left-and-right.cpp new file mode 100644 index 00000000..7259f5ed --- /dev/null +++ b/2516-take-k-of-each-character-from-left-and-right/2516-take-k-of-each-character-from-left-and-right.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + int takeCharacters(string s, int k) { + + int ca,cb, cc; + ca = cb = cc = 0; + int n = s.size(); + unordered_map mpa, mpb, mpc; + int ans = -1; + + mpa[0] = mpb[0] = mpc[0] = n; + + for(int i = n-1 ; i >= 0; --i) + { + if(s[i] == 'a') + { + ++ca; + mpa[ca] = i; + } + if(s[i] == 'b') + { + ++cb; + mpb[cb] = i; + } + if(s[i] == 'c') + { + ++cc; + mpc[cc] = i; + } + } + + ca = cb = cc = 0; + + if(k == 0) + return 0; + + if(mpa.find(k) == mpa.end() or mpb.find(k) == mpb.end() or mpc.find(k) == mpc.end()) + return -1; + + ans = n - min({mpa[k],mpb[k] , mpc[k]}); + + for(int i = 0; i2516. Take K of Each Character From Left and Right

Medium


You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.

+ +

Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.

+ +

 

+

Example 1:

+ +
Input: s = "aabaaaacaabc", k = 2
+Output: 8
+Explanation: 
+Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.
+Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.
+A total of 3 + 5 = 8 minutes is needed.
+It can be proven that 8 is the minimum number of minutes needed.
+
+ +

Example 2:

+ +
Input: s = "a", k = 1
+Output: -1
+Explanation: It is not possible to take one 'b' or 'c' so return -1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only the letters 'a', 'b', and 'c'.
  • +
  • 0 <= k <= s.length
  • +
+
\ No newline at end of file diff --git a/2540-minimum-common-value/2540-minimum-common-value.cpp b/2540-minimum-common-value/2540-minimum-common-value.cpp new file mode 100644 index 00000000..116f4f9c --- /dev/null +++ b/2540-minimum-common-value/2540-minimum-common-value.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int getCommon(vector& nums1, vector& nums2) { + + int i = nums1.size() - 1, j = nums2.size() - 1; + + int cnt = 0, ans = -1; + + while(i >= 0 and j >= 0) + { + if(nums1[i] == nums2[j]) + { + ans = nums1[i]; + --i, --j; + } + else if(nums1[i] > nums2[j]) + --i; + else + --j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2540-minimum-common-value/README.md b/2540-minimum-common-value/README.md new file mode 100644 index 00000000..acdefbbf --- /dev/null +++ b/2540-minimum-common-value/README.md @@ -0,0 +1,28 @@ +

2540. Minimum Common Value

Easy


Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.

+ +

Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,3], nums2 = [2,4]
+Output: 2
+Explanation: The smallest element common to both arrays is 2, so we return 2.
+
+ +

Example 2:

+ +
Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
+Output: 2
+Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 105
  • +
  • 1 <= nums1[i], nums2[j] <= 109
  • +
  • Both nums1 and nums2 are sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/2542-maximum-subsequence-score/2542-maximum-subsequence-score.cpp b/2542-maximum-subsequence-score/2542-maximum-subsequence-score.cpp new file mode 100644 index 00000000..ab2bc228 --- /dev/null +++ b/2542-maximum-subsequence-score/2542-maximum-subsequence-score.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + long long maxScore(vector& nums1, vector& nums2, int k) { + + + vector> v; + + for(int i=0;i,greater> pq; + + for(int i=0;i2551. Put Marbles in Bags

Hard


You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k.

+ +

Divide the marbles into the k bags according to the following rules:

+ +
    +
  • No bag is empty.
  • +
  • If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag.
  • +
  • If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j].
  • +
+ +

The score after distributing the marbles is the sum of the costs of all the k bags.

+ +

Return the difference between the maximum and minimum scores among marble distributions.

+ +

 

+

Example 1:

+ +
Input: weights = [1,3,5,1], k = 2
+Output: 4
+Explanation: 
+The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. 
+The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. 
+Thus, we return their difference 10 - 6 = 4.
+
+ +

Example 2:

+ +
Input: weights = [1, 3], k = 2
+Output: 0
+Explanation: The only distribution possible is [1],[3]. 
+Since both the maximal and minimal score are the same, we return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= weights.length <= 105
  • +
  • 1 <= weights[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip.cpp b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip.cpp new file mode 100644 index 00000000..1a0deb48 --- /dev/null +++ b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + + vector dx = {1,0}; + vector dy = {0,1}; + + bool dfs(int i, int j, int n, int m, vector>& grid) + { + if(i == n-1 and j == m-1) + return true; + + grid[i][j] = 0; + + for(int k = 0; k < 2; ++k) + { + int newx = i + dx[k]; + int newy = j + dy[k]; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and grid[newx][newy] == 1) + { + if(dfs(newx,newy, n,m,grid)) + return true; + } + } + return false; + } + + bool isPossibleToCutPath(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + if(dfs(0,0,n,m,grid) == false) + return true; + + if(dfs(0,0,n,m,grid) == false) + return true; + + return false; + } +}; \ No newline at end of file diff --git a/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/NOTES.md b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/README.md b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/README.md new file mode 100644 index 00000000..cf02414f --- /dev/null +++ b/2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip/README.md @@ -0,0 +1,35 @@ +

2556. Disconnect Path in a Binary Matrix by at Most One Flip

Medium


You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1).

+ +

You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1).

+ +

Return true if it is possible to make the matrix disconnect or false otherwise.

+ +

Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,1,1],[1,0,0],[1,1,1]]
+Output: true
+Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid.
+
+ +

Example 2:

+ +
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
+Output: false
+Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 1000
  • +
  • 1 <= m * n <= 105
  • +
  • grid[i][j] is either 0 or 1.
  • +
  • grid[0][0] == grid[m - 1][n - 1] == 1
  • +
+
\ No newline at end of file diff --git a/2567-minimum-score-by-changing-two-elements/2567-minimum-score-by-changing-two-elements.cpp b/2567-minimum-score-by-changing-two-elements/2567-minimum-score-by-changing-two-elements.cpp new file mode 100644 index 00000000..feb15c9c --- /dev/null +++ b/2567-minimum-score-by-changing-two-elements/2567-minimum-score-by-changing-two-elements.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int minimizeSum(vector& nums) { + + int n = nums.size(); + sort(nums.begin(),nums.end()); + + // both last and secondLast same to 3rd last which is now max + int a = nums[n-3] - nums[0]; + + // both first and second to 3rd which is now min + int b = nums[n-1] - nums[2]; + + // last equals second last and first equals second , now min is second and max is secondLast + int c = nums[n-2] - nums[1]; + + return min({a,b,c}); + + } +}; \ No newline at end of file diff --git a/2567-minimum-score-by-changing-two-elements/NOTES.md b/2567-minimum-score-by-changing-two-elements/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2567-minimum-score-by-changing-two-elements/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2582-pass-the-pillow/2582-pass-the-pillow.cpp b/2582-pass-the-pillow/2582-pass-the-pillow.cpp new file mode 100644 index 00000000..52a89766 --- /dev/null +++ b/2582-pass-the-pillow/2582-pass-the-pillow.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int passThePillow(int n, int time) { + + int fullChunks = time / (n-1); + int extTime = time % (n-1); + + return (fullChunks & 1 ? n - extTime : extTime + 1); + + } +}; \ No newline at end of file diff --git a/2582-pass-the-pillow/NOTES.md b/2582-pass-the-pillow/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2582-pass-the-pillow/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2582-pass-the-pillow/README.md b/2582-pass-the-pillow/README.md new file mode 100644 index 00000000..fcea9416 --- /dev/null +++ b/2582-pass-the-pillow/README.md @@ -0,0 +1,32 @@ +

2582. Pass the Pillow

Easy


There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.

+ +
    +
  • For example, once the pillow reaches the nth person they pass it to the n - 1th person, then to the n - 2th person and so on.
  • +
+ +

Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.

+

 

+

Example 1:

+ +
Input: n = 4, time = 5
+Output: 2
+Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
+After five seconds, the 2nd person is holding the pillow.
+
+ +

Example 2:

+ +
Input: n = 3, time = 2
+Output: 3
+Explanation: People pass the pillow in the following way: 1 -> 2 -> 3.
+After two seconds, the 3rd person is holding the pillow.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 1000
  • +
  • 1 <= time <= 1000
  • +
+
\ No newline at end of file diff --git a/2591-distribute-money-to-maximum-children/2591-distribute-money-to-maximum-children.cpp b/2591-distribute-money-to-maximum-children/2591-distribute-money-to-maximum-children.cpp new file mode 100644 index 00000000..04e0cb7e --- /dev/null +++ b/2591-distribute-money-to-maximum-children/2591-distribute-money-to-maximum-children.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int distMoney(int money, int children) { + + + if(money < children) + return -1; + + money -= children; + + if(money / 7 == children) + { + if(money % 7 == 0) + return children; + } + else if(money/7 == children-1) + { + if(money % 7 == 3) + return children-2; + } + + return min(children-1, money/7); + } +}; diff --git a/2591-distribute-money-to-maximum-children/NOTES.md b/2591-distribute-money-to-maximum-children/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2591-distribute-money-to-maximum-children/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2591-distribute-money-to-maximum-children/README.md b/2591-distribute-money-to-maximum-children/README.md new file mode 100644 index 00000000..df923f03 --- /dev/null +++ b/2591-distribute-money-to-maximum-children/README.md @@ -0,0 +1,40 @@ +

2591. Distribute Money to Maximum Children

Easy


You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to.

+ +

You have to distribute the money according to the following rules:

+ +
    +
  • All money must be distributed.
  • +
  • Everyone must receive at least 1 dollar.
  • +
  • Nobody receives 4 dollars.
  • +
+ +

Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1.

+ +

 

+

Example 1:

+ +
Input: money = 20, children = 3
+Output: 1
+Explanation: 
+The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
+- 8 dollars to the first child.
+- 9 dollars to the second child. 
+- 3 dollars to the third child.
+It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
+
+ +

Example 2:

+ +
Input: money = 16, children = 2
+Output: 2
+Explanation: Each child can be given 8 dollars.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= money <= 200
  • +
  • 2 <= children <= 30
  • +
+
\ No newline at end of file diff --git a/2596-check-knight-tour-configuration/2596-check-knight-tour-configuration.cpp b/2596-check-knight-tour-configuration/2596-check-knight-tour-configuration.cpp new file mode 100644 index 00000000..d1c03e34 --- /dev/null +++ b/2596-check-knight-tour-configuration/2596-check-knight-tour-configuration.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + + bool isValid(int x, int y, int n) + { + return (x >= 0 and y >= 0 and x < n and y < n); + } + + bool checkValidGrid(vector>& grid) { + + int n = grid.size(); + + int start = 0; int end = (n * n) - 1 ; + + int currx = 0, curry = 0; + + vector dx = {-1,-2,-1,-2,1,2,1,2}; + vector dy = {-2,-1,+2,+1,-2,-1,2,1}; + + if(grid[0][0] != start) + return false; + + while(start < end) + { + bool ok = false; + ++start; + for(int i = 0; i < 8; ++i) + { + int newx = currx + dx[i]; + int newy = curry + dy[i]; + + if(isValid(newx,newy,n) and grid[newx][newy] == start) + { + currx = newx; + curry = newy; + ok = true; + break; + } + } + if(!ok) + return false; + } + return true; + } +}; \ No newline at end of file diff --git a/2596-check-knight-tour-configuration/README.md b/2596-check-knight-tour-configuration/README.md new file mode 100644 index 00000000..875f7d98 --- /dev/null +++ b/2596-check-knight-tour-configuration/README.md @@ -0,0 +1,33 @@ +

2596. Check Knight Tour Configuration

Medium


There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once.

+ +

You are given an n x n integer matrix grid consisting of distinct integers from the range [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]th cell that the knight visited. The moves are 0-indexed.

+ +

Return true if grid represents a valid configuration of the knight's movements or false otherwise.

+ +

Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.

+ +

 

+

Example 1:

+ +
Input: grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
+Output: true
+Explanation: The above diagram represents the grid. It can be shown that it is a valid configuration.
+
+ +

Example 2:

+ +
Input: grid = [[0,3,6],[5,8,1],[2,7,4]]
+Output: false
+Explanation: The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move.
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • 3 <= n <= 7
  • +
  • 0 <= grid[row][col] < n * n
  • +
  • All integers in grid are unique.
  • +
+
\ No newline at end of file diff --git a/2597-the-number-of-beautiful-subsets/2597-the-number-of-beautiful-subsets.cpp b/2597-the-number-of-beautiful-subsets/2597-the-number-of-beautiful-subsets.cpp new file mode 100644 index 00000000..41dc5896 --- /dev/null +++ b/2597-the-number-of-beautiful-subsets/2597-the-number-of-beautiful-subsets.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + void helper(int idx, vector& nums, unordered_map& mp, int k, int& ans) + { + if(idx == nums.size()) + { + ++ans; + } + else + { + if(!mp[nums[idx] - k] and !mp[nums[idx] + k]) + { + ++mp[nums[idx]]; + helper(idx+1, nums,mp, k, ans); + --mp[nums[idx]]; + } + helper(idx+1,nums,mp,k,ans); + } + } + + int beautifulSubsets(vector& nums, int k) { + + int ans = 0; + unordered_map mp; + + helper(0,nums,mp,k,ans); + + return ans-1; + } +}; \ No newline at end of file diff --git a/2597-the-number-of-beautiful-subsets/NOTES.md b/2597-the-number-of-beautiful-subsets/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2597-the-number-of-beautiful-subsets/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2597-the-number-of-beautiful-subsets/README.md b/2597-the-number-of-beautiful-subsets/README.md new file mode 100644 index 00000000..1c16e7be --- /dev/null +++ b/2597-the-number-of-beautiful-subsets/README.md @@ -0,0 +1,33 @@ +

2597. The Number of Beautiful Subsets

Medium


You are given an array nums of positive integers and a positive integer k.

+ +

A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.

+ +

Return the number of non-empty beautiful subsets of the array nums.

+ +

A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.

+ +

 

+

Example 1:

+ +
Input: nums = [2,4,6], k = 2
+Output: 4
+Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
+It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
+
+ +

Example 2:

+ +
Input: nums = [1], k = 1
+Output: 1
+Explanation: The beautiful subset of the array nums is [1].
+It can be proved that there is only 1 beautiful subset in the array [1].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 20
  • +
  • 1 <= nums[i], k <= 1000
  • +
+
\ No newline at end of file diff --git a/2598-smallest-missing-non-negative-integer-after-operations/2598-smallest-missing-non-negative-integer-after-operations.cpp b/2598-smallest-missing-non-negative-integer-after-operations/2598-smallest-missing-non-negative-integer-after-operations.cpp new file mode 100644 index 00000000..43b61a9e --- /dev/null +++ b/2598-smallest-missing-non-negative-integer-after-operations/2598-smallest-missing-non-negative-integer-after-operations.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int findSmallestInteger(vector& nums, int value) { + + int n = nums.size(); + + map mp; + + for(auto itr : nums) + { + int val = itr%value; + if(val < 0) + ++mp[val + value]; + else + ++mp[val]; + } + + for(int i = 0; i<=n; ++i) + { + if(mp[i % value] > 0) + { + --mp[i%value]; + continue; + } + else + return i; + } + return n; + } +}; \ No newline at end of file diff --git a/2598-smallest-missing-non-negative-integer-after-operations/README.md b/2598-smallest-missing-non-negative-integer-after-operations/README.md new file mode 100644 index 00000000..6075d8f1 --- /dev/null +++ b/2598-smallest-missing-non-negative-integer-after-operations/README.md @@ -0,0 +1,45 @@ +

2598. Smallest Missing Non-negative Integer After Operations

Medium


You are given a 0-indexed integer array nums and an integer value.

+ +

In one operation, you can add or subtract value from any element of nums.

+ +
    +
  • For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3].
  • +
+ +

The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.

+ +
    +
  • For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2.
  • +
+ +

Return the maximum MEX of nums after applying the mentioned operation any number of times.

+ +

 

+

Example 1:

+ +
Input: nums = [1,-10,7,13,6,8], value = 5
+Output: 4
+Explanation: One can achieve this result by applying the following operations:
+- Add value to nums[1] twice to make nums = [1,0,7,13,6,8]
+- Subtract value from nums[2] once to make nums = [1,0,2,13,6,8]
+- Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8]
+The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
+
+ +

Example 2:

+ +
Input: nums = [1,-10,7,13,6,8], value = 7
+Output: 2
+Explanation: One can achieve this result by applying the following operation:
+- subtract value from nums[2] once to make nums = [1,-10,0,13,6,8]
+The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length, value <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2607-make-k-subarray-sums-equal/2607-make-k-subarray-sums-equal.cpp b/2607-make-k-subarray-sums-equal/2607-make-k-subarray-sums-equal.cpp new file mode 100644 index 00000000..66abb41e --- /dev/null +++ b/2607-make-k-subarray-sums-equal/2607-make-k-subarray-sums-equal.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) { + + long long n = arr.size(), ans = 0; + + for(int i = 0; i < n; ++i) + { + vector cycles; + + for(int j = i; arr[j] != 0 ; j = (j+k)%n) + { + cycles.push_back(arr[j]); + arr[j] = 0; + } + + nth_element(cycles.begin(),cycles.begin()+cycles.size()/2,cycles.end()); + + for(int i = 0; i < cycles.size(); ++i) + { + ans += abs(cycles[i] - cycles[cycles.size()/2]); + } + + } + + return ans; + } +}; \ No newline at end of file diff --git a/2607-make-k-subarray-sums-equal/NOTES.md b/2607-make-k-subarray-sums-equal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2607-make-k-subarray-sums-equal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2607-make-k-subarray-sums-equal/README.md b/2607-make-k-subarray-sums-equal/README.md new file mode 100644 index 00000000..6794e757 --- /dev/null +++ b/2607-make-k-subarray-sums-equal/README.md @@ -0,0 +1,45 @@ +

2607. Make K-Subarray Sums Equal

Medium


You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.

+ +

You can do the following operation any number of times:

+ +
    +
  • Pick any element from arr and increase or decrease it by 1.
  • +
+ +

Return the minimum number of operations such that the sum of each subarray of length k is equal.

+ +

A subarray is a contiguous part of the array.

+ +

 

+

Example 1:

+ +
Input: arr = [1,4,1,3], k = 2
+Output: 1
+Explanation: we can do one operation on index 1 to make its value equal to 3.
+The array after the operation is [1,3,1,3]
+- Subarray starts at index 0 is [1, 3], and its sum is 4 
+- Subarray starts at index 1 is [3, 1], and its sum is 4 
+- Subarray starts at index 2 is [1, 3], and its sum is 4 
+- Subarray starts at index 3 is [3, 1], and its sum is 4 
+
+ +

Example 2:

+ +
Input: arr = [2,5,5,7], k = 3
+Output: 5
+Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5.
+The array after the operations is [5,5,5,5]
+- Subarray starts at index 0 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 1 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 2 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 3 is [5, 5, 5], and its sum is 15 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= arr.length <= 105
  • +
  • 1 <= arr[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2610-convert-an-array-into-a-2d-array-with-conditions/2610-convert-an-array-into-a-2d-array-with-conditions.cpp b/2610-convert-an-array-into-a-2d-array-with-conditions/2610-convert-an-array-into-a-2d-array-with-conditions.cpp new file mode 100644 index 00000000..5dd5bc13 --- /dev/null +++ b/2610-convert-an-array-into-a-2d-array-with-conditions/2610-convert-an-array-into-a-2d-array-with-conditions.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector> findMatrix(vector& nums) { + + map mp; + + for(auto& itr : nums) + ++mp[itr]; + + vector> ans; + + bool ok = true; + + while(ok) + { + vector currRow; + ok = false; + for(auto& [f, e] : mp) + { + if(mp[f] > 0) + currRow.push_back(f); + --e; + if(e > 0) + ok = true; + } + ans.push_back(currRow); + } + + return ans; + } +}; \ No newline at end of file diff --git a/2610-convert-an-array-into-a-2d-array-with-conditions/NOTES.md b/2610-convert-an-array-into-a-2d-array-with-conditions/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2610-convert-an-array-into-a-2d-array-with-conditions/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2610-convert-an-array-into-a-2d-array-with-conditions/README.md b/2610-convert-an-array-into-a-2d-array-with-conditions/README.md new file mode 100644 index 00000000..58b3233b --- /dev/null +++ b/2610-convert-an-array-into-a-2d-array-with-conditions/README.md @@ -0,0 +1,39 @@ +

2610. Convert an Array Into a 2D Array With Conditions

Medium


You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:

+ +
    +
  • The 2D array should contain only the elements of the array nums.
  • +
  • Each row in the 2D array contains distinct integers.
  • +
  • The number of rows in the 2D array should be minimal.
  • +
+ +

Return the resulting array. If there are multiple answers, return any of them.

+ +

Note that the 2D array can have a different number of elements on each row.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,1,2,3,1]
+Output: [[1,3,4,2],[1,3],[1]]
+Explanation: We can create a 2D array that contains the following rows:
+- 1,3,4,2
+- 1,3
+- 1
+All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
+It can be shown that we cannot have less than 3 rows in a valid array.
+ +

Example 2:

+ +
Input: nums = [1,2,3,4]
+Output: [[4,3,2,1]]
+Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= nums.length
  • +
+
\ No newline at end of file diff --git a/2616-minimize-the-maximum-difference-of-pairs/2616-minimize-the-maximum-difference-of-pairs.cpp b/2616-minimize-the-maximum-difference-of-pairs/2616-minimize-the-maximum-difference-of-pairs.cpp new file mode 100644 index 00000000..8bc7ca57 --- /dev/null +++ b/2616-minimize-the-maximum-difference-of-pairs/2616-minimize-the-maximum-difference-of-pairs.cpp @@ -0,0 +1,51 @@ +class Solution { + +private: + int isPossibleToDivideInpPairs(int mid, int n, vector& nums, int p) + { + int cnt = 0; + int i = 1; + + while(i < n and cnt < p) + { + if(nums[i] - nums[i-1] <= mid) + { + i += 2; + ++cnt; + } + else + ++i; + } + + return cnt >= p; + } + +public: + int minimizeMax(vector& nums, int p) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + int right = nums[n-1] - nums[0]; + int left = 0; + int ans = right; + + + while(left <= right) + { + int mid = (left + right) >> 1; + + if(isPossibleToDivideInpPairs(mid, n, nums, p)) + { + ans = mid; + right = mid-1; + } + else + left = mid+1; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2616-minimize-the-maximum-difference-of-pairs/README.md b/2616-minimize-the-maximum-difference-of-pairs/README.md new file mode 100644 index 00000000..3b3b0943 --- /dev/null +++ b/2616-minimize-the-maximum-difference-of-pairs/README.md @@ -0,0 +1,31 @@ +

2616. Minimize the Maximum Difference of Pairs

Medium


You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.

+ +

Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.

+ +

Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero.

+ +

 

+

Example 1:

+ +
Input: nums = [10,1,2,7,1,3], p = 2
+Output: 1
+Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. 
+The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
+
+ +

Example 2:

+ +
Input: nums = [4,2,1,2], p = 1
+Output: 0
+Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
  • 0 <= p <= (nums.length)/2
  • +
+
\ No newline at end of file diff --git a/2618-check-if-object-instance-of-class/2618-check-if-object-instance-of-class.js b/2618-check-if-object-instance-of-class/2618-check-if-object-instance-of-class.js new file mode 100644 index 00000000..8969213f --- /dev/null +++ b/2618-check-if-object-instance-of-class/2618-check-if-object-instance-of-class.js @@ -0,0 +1,28 @@ +/** + * @param {any} obj + * @param {any} classFunction + * @return {boolean} + */ +var checkIfInstanceOf = function(obj, classFunction) { + + if(obj == null || obj == undefined || typeof classFunction !== 'function') + { + return false; + } + + let currPrototype = Object.getPrototypeOf(obj); + + while(currPrototype !== null) + { + if(currPrototype === classFunction.prototype) + { + return true; + } + currPrototype = Object.getPrototypeOf(currPrototype); + } + return false; +}; + +/** + * checkIfInstanceOf(new Date(), Date); // true + */ \ No newline at end of file diff --git a/2618-check-if-object-instance-of-class/NOTES.md b/2618-check-if-object-instance-of-class/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2618-check-if-object-instance-of-class/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2618-check-if-object-instance-of-class/README.md b/2618-check-if-object-instance-of-class/README.md new file mode 100644 index 00000000..a32bda5c --- /dev/null +++ b/2618-check-if-object-instance-of-class/README.md @@ -0,0 +1,37 @@ +

2618. Check if Object Instance of Class

Medium


Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.

+ +

There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.

+ +

 

+

Example 1:

+ +
Input: func = () => checkIfInstanceOf(new Date(), Date)
+Output: true
+Explanation: The object returned by the Date constructor is, by definition, an instance of Date.
+
+ +

Example 2:

+ +
Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
+Output: true
+Explanation:
+class Animal {};
+class Dog extends Animal {};
+checkIfInstance(new Dog(), Animal); // true
+
+Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.
+ +

Example 3:

+ +
Input: func = () => checkIfInstanceOf(Date, Date)
+Output: false
+Explanation: A date constructor cannot logically be an instance of itself.
+
+ +

Example 4:

+ +
Input: func = () => checkIfInstanceOf(5, Number)
+Output: true
+Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".
+
+
\ No newline at end of file diff --git a/2619-array-prototype-last/2619-array-prototype-last.js b/2619-array-prototype-last/2619-array-prototype-last.js new file mode 100644 index 00000000..4e556a1c --- /dev/null +++ b/2619-array-prototype-last/2619-array-prototype-last.js @@ -0,0 +1,12 @@ +Array.prototype.last = function() { + if (this.length === 0) { + return -1; + } else { + return this[this.length - 1]; + } +}; + +/** + * const arr = [1, 2, 3]; + * arr.last(); // 3 + */ \ No newline at end of file diff --git a/2619-array-prototype-last/NOTES.md b/2619-array-prototype-last/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2619-array-prototype-last/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2620-counter/2620-counter.js b/2620-counter/2620-counter.js new file mode 100644 index 00000000..25d6e6b4 --- /dev/null +++ b/2620-counter/2620-counter.js @@ -0,0 +1,17 @@ +/** + * @param {number} n + * @return {Function} counter + */ +var createCounter = function(n) { + return function() { + ++n; + return n-1; + }; +}; + +/** + * const counter = createCounter(10) + * counter() // 10 + * counter() // 11 + * counter() // 12 + */ \ No newline at end of file diff --git a/2620-counter/NOTES.md b/2620-counter/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2620-counter/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2620-counter/README.md b/2620-counter/README.md new file mode 100644 index 00000000..26ee6dd6 --- /dev/null +++ b/2620-counter/README.md @@ -0,0 +1,32 @@ +

2620. Counter

Easy


Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

+ +

 

+

Example 1:

+ +
Input: 
+n = 10 
+["call","call","call"]
+Output: [10,11,12]
+Explanation: 
+counter() = 10 // The first time counter() is called, it returns n.
+counter() = 11 // Returns 1 more than the previous time.
+counter() = 12 // Returns 1 more than the previous time.
+
+ +

Example 2:

+ +
Input: 
+n = -2
+["call","call","call","call","call"]
+Output: [-2,-1,0,1,2]
+Explanation: counter() initially returns -2. Then increases after each sebsequent call.
+
+ +

 

+

Constraints:

+ +
    +
  • -1000 <= n <= 1000
  • +
  • At most 1000 calls to counter() will be made
  • +
+
\ No newline at end of file diff --git a/2621-sleep/2621-sleep.js b/2621-sleep/2621-sleep.js new file mode 100644 index 00000000..03f0e2a7 --- /dev/null +++ b/2621-sleep/2621-sleep.js @@ -0,0 +1,11 @@ +/** + * @param {number} millis + */ +async function sleep(millis) { + await new Promise(resolve => setTimeout(resolve, millis)); +} + +/** + * let t = Date.now() + * sleep(100).then(() => console.log(Date.now() - t)) // 100 + */ \ No newline at end of file diff --git a/2621-sleep/NOTES.md b/2621-sleep/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2621-sleep/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2621-sleep/README.md b/2621-sleep/README.md new file mode 100644 index 00000000..3366c206 --- /dev/null +++ b/2621-sleep/README.md @@ -0,0 +1,28 @@ +

2621. Sleep

Easy


Given a positive integer millis, write an asyncronous function that sleeps for millis milliseconds. It can resolve any value.

+ +

 

+

Example 1:

+ +
Input: millis = 100
+Output: 100
+Explanation: It should return a promise that resolves after 100ms.
+let t = Date.now();
+sleep(100).then(() => {
+  console.log(Date.now() - t); // 100
+});
+
+ +

Example 2:

+ +
Input: millis = 200
+Output: 200
+Explanation: It should return a promise that resolves after 200ms.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= millis <= 1000
  • +
+
\ No newline at end of file diff --git a/2622-cache-with-time-limit/2622-cache-with-time-limit.js b/2622-cache-with-time-limit/2622-cache-with-time-limit.js new file mode 100644 index 00000000..75c890b8 --- /dev/null +++ b/2622-cache-with-time-limit/2622-cache-with-time-limit.js @@ -0,0 +1,30 @@ + +const TimeLimitedCache = function() { + this.cache = new Map(); // Using Map so we don't need a size variable +}; + +TimeLimitedCache.prototype.set = function(key, value, duration) { + let found = this.cache.has(key); + if (found) clearTimeout(this.cache.get(key).ref); // Cancel previous timeout + this.cache.set(key, { + value, // Equivalent to `value: value` + ref: setTimeout(() => this.cache.delete(key), duration) + }); + return found; +}; + +TimeLimitedCache.prototype.get = function(key) { + return this.cache.has(key) ? this.cache.get(key).value : -1; +}; + +TimeLimitedCache.prototype.count = function() { + return this.cache.size; +}; + +/** + * Your TimeLimitedCache object will be instantiated and called as such: + * var obj = new TimeLimitedCache() + * obj.set(1, 42, 1000); // false + * obj.get(1) // 42 + * obj.count() // 1 + */ \ No newline at end of file diff --git a/2622-cache-with-time-limit/NOTES.md b/2622-cache-with-time-limit/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2622-cache-with-time-limit/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2622-cache-with-time-limit/README.md b/2622-cache-with-time-limit/README.md new file mode 100644 index 00000000..c5a91d65 --- /dev/null +++ b/2622-cache-with-time-limit/README.md @@ -0,0 +1,55 @@ +

2622. Cache With Time Limit

Medium


Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.

+ +

The class has three public methods:

+ +

set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists.

+ +

get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1.

+ +

count(): returns the count of un-expired keys.

+ +

 

+

Example 1:

+ +
Input: 
+["TimeLimitedCache", "set", "get", "count", "get"]
+[[], [1, 42, 100], [1], [], [1]]
+[0, 0, 50, 50, 150]
+Output: [null, false, 42, 1, -1]
+Explanation:
+At t=0, the cache is constructed.
+At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned.
+At t=50, key=1 is requested and the value of 42 is returned.
+At t=50, count() is called and there is one active key in the cache.
+At t=100, key=1 expires.
+At t=150, get(1) is called but -1 is returned because the cache is empty.
+
+ +

Example 2:

+ +
Input: 
+["TimeLimitedCache", "set", "set", "get", "get", "get", "count"]
+[[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []]
+[0, 0, 40, 50, 120, 200, 250]
+Output: [null, false, true, 50, 50, -1]
+Explanation:
+At t=0, the cache is constructed.
+At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned.
+At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten.
+At t=50, get(1) is called which returned 50.
+At t=120, get(1) is called which returned 50.
+At t=140, key=1 expires.
+At t=200, get(1) is called but the cache is empty so -1 is returned.
+At t=250, count() returns 0 because the cache is empty.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= key <= 109
  • +
  • 0 <= value <= 109
  • +
  • 0 <= duration <= 1000
  • +
  • total method calls will not exceed 100
  • +
+
\ No newline at end of file diff --git a/2623-memoize/2623-memoize.js b/2623-memoize/2623-memoize.js new file mode 100644 index 00000000..f35a333b --- /dev/null +++ b/2623-memoize/2623-memoize.js @@ -0,0 +1,23 @@ +/** + * @param {Function} fn + */ +function memoize(fn) { + const mem = {}; + return function(...args) { + if (mem[args] !== undefined) return mem[args]; + mem[args] = fn(...args); + return mem[args] + } +} + + +/** + * let callCount = 0; + * const memoizedFn = memoize(function (a, b) { + * callCount += 1; + * return a + b; + * }) + * memoizedFn(2, 3) // 5 + * memoizedFn(2, 3) // 5 + * console.log(callCount) // 1 + */ \ No newline at end of file diff --git a/2623-memoize/NOTES.md b/2623-memoize/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2623-memoize/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2623-memoize/README.md b/2623-memoize/README.md new file mode 100644 index 00000000..2f1ce95f --- /dev/null +++ b/2623-memoize/README.md @@ -0,0 +1,78 @@ +

2623. Memoize

Medium


Given a function fn, return a memoized version of that function.

+ +

memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.

+ +

You can assume there are possible input functions: sum, fiband factorial.

+ +
    +
  • sum accepts two integers a and b and returns a + b.
  • +
  • fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise.
  • +
  • factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise.
  • +
+ +

 

+

Example 1:

+ +
Input
+"sum"
+["call","call","getCallCount","call","getCallCount"]
+[[2,2],[2,2],[],[1,2],[]]
+Output
+[4,4,1,3,2]
+
+Explanation
+const sum = (a, b) => a + b;
+const memoizedSum = memoize(sum);
+memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.
+memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.
+// Total call count: 1
+memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.
+// Total call count: 2
+
+ +

Example 2:

+ +
Input
+"factorial"
+["call","call","call","getCallCount","call","getCallCount"]
+[[2],[3],[2],[],[3],[]]
+Output
+[2,6,2,2,6,2]
+
+Explanation
+const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));
+const memoFactorial = memoize(factorial);
+memoFactorial(2); // Returns 2.
+memoFactorial(3); // Returns 6.
+memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before.
+// Total call count: 2
+memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before.
+// Total call count: 2
+
+ +

Example 3:

+ +
Input
+"fib"
+["call","getCallCount"]
+[[5],[]]
+Output
+[8,1]
+
+Explanation
+fib(5) = 8
+// Total call count: 1
+
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= a, b <= 105
  • +
  • 1 <= n <= 10
  • +
  • at most 105 function calls
  • +
  • at most 105 attempts to access callCount
  • +
  • input function is sum, fib, or factorial
  • +
+
\ No newline at end of file diff --git a/2625-flatten-deeply-nested-array/2625-flatten-deeply-nested-array.js b/2625-flatten-deeply-nested-array/2625-flatten-deeply-nested-array.js new file mode 100644 index 00000000..3fad1af4 --- /dev/null +++ b/2625-flatten-deeply-nested-array/2625-flatten-deeply-nested-array.js @@ -0,0 +1,17 @@ +/** + * @param {any[]} arr + * @param {number} depth + * @return {any[]} + */ +var flat = function (arr, n) { + + if(n == 0 || arr.every((item) => !Array.isArray(item))) return arr; + const result = []; + for(let i=0;i2625. Flatten Deeply Nested Array

Medium


Given a multi-dimensional array arr and a depth n, return a flattened version of that array.

+ +

A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.

+ +

flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0.

+ +

Please solve it without the built-in Array.flat method.

+ +

 

+

Example 1:

+ +
Input
+arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
+n = 0
+Output
+[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
+
+Explanation
+Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened. 
+ +

Example 2:

+ +
Input
+arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
+n = 1
+Output
+[1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]
+
+Explanation
+The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1.
+ +

Example 3:

+ +
Input
+arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
+n = 2
+Output
+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
+
+Explanation
+The maximum depth of any subarray is 1. Thus, all of them are flattened.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= count of numbers in arr <= 105
  • +
  • 0 <= count of subarrays in arr <= 105
  • +
  • maxDepth <= 1000
  • +
  • -1000 <= each number <= 1000
  • +
  • 0 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/2627-debounce/2627-debounce.js b/2627-debounce/2627-debounce.js new file mode 100644 index 00000000..6b7a70ba --- /dev/null +++ b/2627-debounce/2627-debounce.js @@ -0,0 +1,20 @@ +/** + * @param {Function} fn + * @param {number} t milliseconds + * @return {Function} + */ + +var debounce = function(fn, t) { + let timeout = null + return (...args) => { + clearTimeout(timeout) + timeout = setTimeout(fn, t, ...args) + } +}; + +/** + * const log = debounce(console.log, 100); + * log('Hello'); // cancelled + * log('Hello'); // cancelled + * log('Hello'); // Logged at t=100ms + */ \ No newline at end of file diff --git a/2627-debounce/README.md b/2627-debounce/README.md new file mode 100644 index 00000000..3d3a68c0 --- /dev/null +++ b/2627-debounce/README.md @@ -0,0 +1,75 @@ +

2627. Debounce

Medium


Given a function fn and a time in milliseconds t, return a debounced version of that function.

+ +

debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also recieve the passed parameters.

+ +

For example, let's say t = 50ms, and the function was called at 30ms60ms, and 100ms. The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms.

+ +

Debounce Schematic

+ +

The above diagram shows how debounce will transform events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs.

+ +

Please solve it without using lodash's _.debounce() function.

+ +

 

+

Example 1:

+ +
Input: 
+t = 50
+calls = [
+  {"t": 50, inputs: [1]},
+  {"t": 75, inputs: [2]}
+]
+Output: [{"t": 125, inputs: [2]}]
+Explanation:
+let start = Date.now();
+function log(...inputs) { 
+  console.log([Date.now() - start, inputs ])
+}
+const dlog = debounce(log, 50);
+setTimeout(() => dlog(1), 50);
+setTimeout(() => dlog(2), 75);
+
+The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms
+The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2).
+
+ +

Example 2:

+ +
Input: 
+t = 20
+calls = [
+  {"t": 50, inputs: [1]},
+  {"t": 100, inputs: [2]}
+]
+Output: [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}]
+Explanation:
+The 1st call is delayed until 70ms. The inputs were (1).
+The 2nd call is delayed until 120ms. The inputs were (2).
+
+ +

Example 3:

+ +
Input: 
+t = 150
+calls = [
+  {"t": 50, inputs: [1, 2]},
+  {"t": 300, inputs: [3, 4]},
+  {"t": 300, inputs: [5, 6]}
+]
+Output: [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}]
+Explanation:
+The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2).
+The 2nd call is cancelled by the 3rd call
+The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6).
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= t <= 1000
  • +
  • 1 <= calls.length <= 10
  • +
  • 0 <= calls[i].t <= 1000
  • +
  • 0 <= calls[i].inputs.length <= 10
  • +
+
\ No newline at end of file diff --git a/2628-json-deep-equal/2628-json-deep-equal.js b/2628-json-deep-equal/2628-json-deep-equal.js new file mode 100644 index 00000000..3c7cf269 --- /dev/null +++ b/2628-json-deep-equal/2628-json-deep-equal.js @@ -0,0 +1,10 @@ +/** + * @param {any} o1 + * @param {any} o2 + * @return {boolean} + */ +var areDeeplyEqual = function(o1, o2) { + + + return _.isEqual(o1,o2); +}; \ No newline at end of file diff --git a/2628-json-deep-equal/NOTES.md b/2628-json-deep-equal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2628-json-deep-equal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2628-json-deep-equal/README.md b/2628-json-deep-equal/README.md new file mode 100644 index 00000000..10f6565c --- /dev/null +++ b/2628-json-deep-equal/README.md @@ -0,0 +1,45 @@ +

2628. JSON Deep Equal

Medium


Given two objects o1 and o2, check if they are deeply equal.

+ +

For two objects to be deeply equal, they must contain the same keys, and the associated values must also be deeply equal. Two objects are also considered deeply equal if they pass the === equality check.

+ +

You may assume both objects are the output of JSON.parse. In other words, they are valid JSON.

+ +

Please solve it without using lodash's _.isEqual() function.

+ +

 

+

Example 1:

+ +
Input: o1 = {"x":1,"y":2}, o2 = {"x":1,"y":2}
+Output: true
+Explanation: The keys and values match exactly.
+
+ +

Example 2:

+ +
Input: o1 = {"y":2,"x":1}, o2 = {"x":1,"y":2}
+Output: true
+Explanation: Although the keys are in a different order, they still match exactly.
+
+ +

Example 3:

+ +
Input: o1 = {"x":null,"L":[1,2,3]}, o2 = {"x":null,"L":["1","2","3"]}
+Output: false
+Explanation: The array of numbers is different from the array of strings.
+
+ +

Example 4:

+ +
Input: o1 = true, o2 = false
+Output: false
+Explanation: true !== false
+ +

 

+

Constraints:

+ +
    +
  • 1 <= JSON.stringify(o1).length <= 105
  • +
  • 1 <= JSON.stringify(o2).length <= 105
  • +
  • maxNestingDepth <= 1000
  • +
+
\ No newline at end of file diff --git a/2631-group-by/NOTES.md b/2631-group-by/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2631-group-by/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2631-group-by/README.md b/2631-group-by/README.md new file mode 100644 index 00000000..04f5d874 --- /dev/null +++ b/2631-group-by/README.md @@ -0,0 +1,81 @@ +

2631. Group By

Medium


Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array.

+ +

grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array with that key.

+ +

The provided callback fn will accept an item in the array and return a string key.

+ +

The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.

+ +

Please solve it without lodash's _.groupBy function.

+ +

 

+

Example 1:

+ +
Input: 
+array = [
+  {"id":"1"},
+  {"id":"1"},
+  {"id":"2"}
+], 
+fn = function (item) { 
+  return item.id; 
+}
+Output: 
+{ 
+  "1": [{"id": "1"}, {"id": "1"}],   
+  "2": [{"id": "2"}] 
+}
+Explanation:
+Output is from array.groupBy(fn).
+The selector function gets the "id" out of each item in the array.
+There are two objects with an "id" of 1. Both of those objects are put in the first array.
+There is one object with an "id" of 2. That object is put in the second array.
+
+ +

Example 2:

+ +
Input: 
+array = [
+  [1, 2, 3],
+  [1, 3, 5],
+  [1, 5, 9]
+]
+fn = function (list) { 
+  return String(list[0]); 
+}
+Output: 
+{ 
+  "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] 
+}
+Explanation:
+The array can be of any type. In this case, the selector function defines the key as being the first element in the array. 
+All the arrays have 1 as their first element so they are grouped together.
+{
+  "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]
+}
+
+ +

Example 3:

+ +
Input: 
+array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+fn = function (n) { 
+  return String(n > 5);
+}
+Output:
+{
+  "true": [6, 7, 8, 9, 10],
+  "false": [1, 2, 3, 4, 5]
+}
+Explanation:
+The selector function splits the array by whether each number is greater than 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= array.length <= 105
  • +
  • fn returns a string
  • +
+
\ No newline at end of file diff --git a/2632-curry/2632-curry.js b/2632-curry/2632-curry.js new file mode 100644 index 00000000..3975dc73 --- /dev/null +++ b/2632-curry/2632-curry.js @@ -0,0 +1,21 @@ +/** + * @param {Function} fn + * @return {Function} + */ +var curry = function(fn) { + return function curried(...args) { + if (fn.length === args.length) { + return fn(...args); + } else { + return function(...newArgs) { + return curried(...args, ...newArgs) + } + } + }; +}; + +/** + * function sum(a, b) { return a + b; } + * const csum = curry(sum); + * csum(1)(2) // 3 + */ diff --git a/2632-curry/NOTES.md b/2632-curry/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2632-curry/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2633-convert-object-to-json-string/2633-convert-object-to-json-string.js b/2633-convert-object-to-json-string/2633-convert-object-to-json-string.js new file mode 100644 index 00000000..439d8256 --- /dev/null +++ b/2633-convert-object-to-json-string/2633-convert-object-to-json-string.js @@ -0,0 +1,10 @@ +/** + * @param {any} object + * @return {string} + */ +var jsonStringify = function(object) { + + var ans = JSON.stringify(object); + + return ans; +}; \ No newline at end of file diff --git a/2633-convert-object-to-json-string/NOTES.md b/2633-convert-object-to-json-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2633-convert-object-to-json-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2633-convert-object-to-json-string/README.md b/2633-convert-object-to-json-string/README.md new file mode 100644 index 00000000..59ecac38 --- /dev/null +++ b/2633-convert-object-to-json-string/README.md @@ -0,0 +1,46 @@ +

2633. Convert Object to JSON String

Medium


Given an object, return a valid JSON string of that object. You may assume the object only inludes strings, integers, arrays, objects, booleans, and null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys().

+ +

Please solve it without using the built-in JSON.stringify method.

+ +

 

+

Example 1:

+ +
Input: object = {"y":1,"x":2}
+Output: {"y":1,"x":2}
+Explanation: 
+Return the JSON representation.
+Note that the order of keys should be the same as the order returned by Object.keys().
+ +

Example 2:

+ +
Input: object = {"a":"str","b":-12,"c":true,"d":null}
+Output: {"a":"str","b":-12,"c":true,"d":null}
+Explanation:
+The primitives of JSON are strings, numbers, booleans, and null.
+
+ +

Example 3:

+ +
Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
+Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
+Explanation:
+Objects and arrays can include other objects and arrays.
+
+ +

Example 4:

+ +
Input: object = true
+Output: true
+Explanation:
+Primitive types are valid inputs.
+ +

 

+

Constraints:

+ +
    +
  • object includes strings, integers, booleans, arrays, objects, and null
  • +
  • 1 <= JSON.stringify(object).length <= 105
  • +
  • maxNestingLevel <= 1000
  • +
  • all strings will only contain alphanumeric characters
  • +
+
\ No newline at end of file diff --git a/2634-filter-elements-from-array/2634-filter-elements-from-array.js b/2634-filter-elements-from-array/2634-filter-elements-from-array.js new file mode 100644 index 00000000..09e068af --- /dev/null +++ b/2634-filter-elements-from-array/2634-filter-elements-from-array.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var filter = function(arr, fn) { + + var ans = []; + + for(var i = 0; i < arr.length; ++i) + { + if(fn(arr[i], i)) + ans.push(arr[i]); + } + + return ans; + +}; + diff --git a/2634-filter-elements-from-array/2634-filter-elements-from-array.ts b/2634-filter-elements-from-array/2634-filter-elements-from-array.ts new file mode 100644 index 00000000..b321d81e --- /dev/null +++ b/2634-filter-elements-from-array/2634-filter-elements-from-array.ts @@ -0,0 +1,12 @@ +function filter(arr: number[], fn: (n: number, i: number) => any): number[] { + + const ans : number[] = []; + + for(var i = 0; i < arr.length; ++i) + { + if(fn(arr[i],i)) + ans.push(arr[i]); + } + + return ans; +}; diff --git a/2634-filter-elements-from-array/NOTES.md b/2634-filter-elements-from-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2634-filter-elements-from-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2634-filter-elements-from-array/README.md b/2634-filter-elements-from-array/README.md new file mode 100644 index 00000000..e168964e --- /dev/null +++ b/2634-filter-elements-from-array/README.md @@ -0,0 +1,40 @@ +

2634. Filter Elements from Array

Easy


Given an integer array arr and a filtering function fn, return a new array with a fewer or equal number of elements.

+ +

The returned array should only contain elements where fn(arr[i], i) evaluated to a truthy value.

+ +

Please solve it without the built-in Array.filter method.

+ +

 

+

Example 1:

+ +
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
+Output: [20,30]
+Explanation:
+const newArray = filter(arr, fn); // [20, 30]
+The function filters out values that are not greater than 10
+ +

Example 2:

+ +
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
+Output: [1]
+Explanation:
+fn can also accept the index of each element
+In this case, the function removes elements not at index 0
+
+ +

Example 3:

+ +
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
+Output: [-2,0,1,2]
+Explanation:
+Falsey values such as 0 should be filtered out
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= arr.length <= 1000
  • +
  • -109 <= arr[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.js b/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.js new file mode 100644 index 00000000..dafe7e12 --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.js @@ -0,0 +1,13 @@ +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var map = function(arr, fn) { + var mp = []; + + for(var i = 0; i < arr.length; ++i) + mp.push(fn(arr[i],i)); + + return mp; +}; diff --git a/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.ts b/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.ts new file mode 100644 index 00000000..0ff19d6d --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array/2635-apply-transform-over-each-element-in-array.ts @@ -0,0 +1,9 @@ +function map(arr: number[], fn: (n: number, i: number) => number): number[] { + + const mp : number[] = []; + + for(var i = 0; i < arr.length; ++i) + mp.push(fn(arr[i],i)); + + return mp; +}; \ No newline at end of file diff --git a/2635-apply-transform-over-each-element-in-array/NOTES.md b/2635-apply-transform-over-each-element-in-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2635-apply-transform-over-each-element-in-array/README.md b/2635-apply-transform-over-each-element-in-array/README.md new file mode 100644 index 00000000..eea14ea6 --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array/README.md @@ -0,0 +1,39 @@ +

2635. Apply Transform Over Each Element in Array

Easy


Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

+ +

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

+ +

Please solve it without the built-in Array.map method.

+ +

 

+

Example 1:

+ +
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
+Output: [2,3,4]
+Explanation:
+const newArray = map(arr, plusone); // [2,3,4]
+The function increases each value in the array by one. 
+
+ +

Example 2:

+ +
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
+Output: [1,3,5]
+Explanation: The function increases each value by the index it resides in.
+
+ +

Example 3:

+ +
Input: arr = [10,20,30], fn = function constant() { return 42; }
+Output: [42,42,42]
+Explanation: The function always returns 42.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= arr.length <= 1000
  • +
  • -109 <= arr[i] <= 109
  • +
  • fn returns a number
  • +
+
\ No newline at end of file diff --git a/2636-promise-pool/README.md b/2636-promise-pool/README.md new file mode 100644 index 00000000..69f5907c --- /dev/null +++ b/2636-promise-pool/README.md @@ -0,0 +1,74 @@ +

2636. Promise Pool

Medium


Given an array of asyncronous functions functions and a pool limit n, return an asyncronous function promisePool. It should return a promise that resolves when all the input functions resolve.

+ +

Pool limit is defined as the maximum number promises that can be pending at once. promisePool should begin execution of as many functions as possible and continue executing new functions when old promises resolve. promisePool should execute functions[i] then functions[i + 1] then functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.

+ +

For example, if n = 1, promisePool will execute one function at a time in series. However, if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.

+ +

You can assume all functions never reject. It is acceptable for promisePool to return a promise that resolves any value.

+ +

 

+

Example 1:

+ +
Input: 
+functions = [
+  () => new Promise(res => setTimeout(res, 300)),
+  () => new Promise(res => setTimeout(res, 400)),
+  () => new Promise(res => setTimeout(res, 200))
+]
+n = 2
+Output: [[300,400,500],500]
+Explanation:
+Three functions are passed in. They sleep for 300ms, 400ms, and 200ms respectively.
+They resolve at 300ms, 400ms, and 500ms respectively. The returned promise resolves at 500ms.
+At t=0, the first 2 functions are executed. The pool size limit of 2 is reached.
+At t=300, the 1st function resolves, and the 3rd function is executed. Pool size is 2.
+At t=400, the 2nd function resolves. There is nothing left to execute. Pool size is 1.
+At t=500, the 3rd function resolves. Pool size is zero so the returned promise also resolves.
+
+ +

Example 2:

+ +
Input:
+functions = [
+  () => new Promise(res => setTimeout(res, 300)),
+  () => new Promise(res => setTimeout(res, 400)),
+  () => new Promise(res => setTimeout(res, 200))
+]
+n = 5
+Output: [[300,400,200],400]
+Explanation:
+The three input promises resolve at 300ms, 400ms, and 200ms respectively.
+The returned promise resolves at 400ms.
+At t=0, all 3 functions are executed. The pool limit of 5 is never met.
+At t=200, the 3rd function resolves. Pool size is 2.
+At t=300, the 1st function resolved. Pool size is 1.
+At t=400, the 2nd function resolves. Pool size is 0, so the returned promise also resolves.
+
+ +

Example 3:

+ +
Input:
+functions = [
+  () => new Promise(res => setTimeout(res, 300)),
+  () => new Promise(res => setTimeout(res, 400)),
+  () => new Promise(res => setTimeout(res, 200))
+]
+n = 1
+Output: [[300,700,900],900]
+Explanation:
+The three input promises resolve at 300ms, 700ms, and 900ms respectively.
+The returned promise resolves at 900ms.
+At t=0, the 1st function is executed. Pool size is 1.
+At t=300, the 1st function resolves and the 2nd function is executed. Pool size is 1.
+At t=700, the 2nd function resolves and the 3rd function is executed. Pool size is 1.
+At t=900, the 3rd function resolves. Pool size is 0 so the returned promise resolves.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= functions.length <= 10
  • +
  • 1 <= n <= 10
  • +
+
\ No newline at end of file diff --git a/2637-promise-time-limit/2637-promise-time-limit.js b/2637-promise-time-limit/2637-promise-time-limit.js new file mode 100644 index 00000000..6301c08e --- /dev/null +++ b/2637-promise-time-limit/2637-promise-time-limit.js @@ -0,0 +1,23 @@ +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ +var timeLimit = function(fn, t) { + return async function(...args) { + + return new Promise((resolve, reject) =>{ + const id = setTimeout(() => reject("Time Limit Exceeded"), t); + + fn(...args) + .then((res) => resolve(res)) + .catch((err) => reject(err)) + .finally(() => clearTimeout(id)); + }); + } +}; + +/** + * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100); + * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms + */ \ No newline at end of file diff --git a/2637-promise-time-limit/NOTES.md b/2637-promise-time-limit/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2637-promise-time-limit/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2637-promise-time-limit/README.md b/2637-promise-time-limit/README.md new file mode 100644 index 00000000..bcd8a36d --- /dev/null +++ b/2637-promise-time-limit/README.md @@ -0,0 +1,68 @@ +

2637. Promise Time Limit

Easy


Given an asyncronous function fn and a time t in milliseconds, return a new time limited version of the input function.

+ +

time limited function is a function that is identical to the original unless it takes longer than t milliseconds to fullfill. In that case, it will reject with "Time Limit Exceeded".  Note that it should reject with a string, not an Error.

+ +

 

+

Example 1:

+ +
Input: 
+fn = async (n) => { 
+  await new Promise(res => setTimeout(res, 100)); 
+  return n * n; 
+}
+inputs = [5]
+t = 50
+Output: {"rejected":"Time Limit Exceeded","time":50}
+Explanation:
+The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.
+
+ +

Example 2:

+ +
Input: 
+fn = async (n) => { 
+  await new Promise(res => setTimeout(res, 100)); 
+  return n * n; 
+}
+inputs = [5]
+t = 150
+Output: {"resolved":25,"time":100}
+Explanation:
+The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.
+
+ +

Example 3:

+ +
Input: 
+fn = async (a, b) => { 
+  await new Promise(res => setTimeout(res, 120)); 
+  return a + b; 
+}
+inputs = [5,10]
+t = 150
+Output: {"resolved":15,"time":120}
+Explanation:
+The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.
+
+ +

Example 4:

+ +
Input: 
+fn = async () => { 
+  throw "Error";
+}
+inputs = []
+t = 1000
+Output: {"rejected":"Error","time":0}
+Explanation:
+The function immediately throws an error.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= inputs.length <= 10
  • +
  • 0 <= t <= 1000
  • +
  • fn returns a promise
  • +
+
\ No newline at end of file diff --git a/2642-design-graph-with-shortest-path-calculator/2642-design-graph-with-shortest-path-calculator.cpp b/2642-design-graph-with-shortest-path-calculator/2642-design-graph-with-shortest-path-calculator.cpp new file mode 100644 index 00000000..b46998f3 --- /dev/null +++ b/2642-design-graph-with-shortest-path-calculator/2642-design-graph-with-shortest-path-calculator.cpp @@ -0,0 +1,76 @@ +class Graph { +public: + + vector > adj[105]; + + int dijistras(int src, int dest) + { + vector dist(105, INT_MAX); + + priority_queue, vector>, greater> > pq; + + dist[src] = 0; + + pq.push({dist[src], src}); + + while(!pq.empty()) + { + pair curr = pq.top(); + pq.pop(); + + int distance = curr.first; + int node = curr.second; + + if(node == dest) + { + return distance; + } + + for(auto& child : adj[node]) + { + if(distance + child.second < dist[child.first]) + { + dist[child.first] = distance + child.second; + + pq.push({dist[child.first], child.first}); + } + } + } + return -1; + } + + Graph(int n, vector>& edges) { + + for(auto& edge : edges) + { + int u = edge[0]; + int v = edge[1]; + int wt = edge[2]; + + adj[u].push_back({v, wt}); + } + } + + void addEdge(vector edge) { + + int u = edge[0]; + int v = edge[1]; + int wt = edge[2]; + + adj[u].push_back({v, wt}); + + } + + int shortestPath(int node1, int node2) { + + return dijistras(node1, node2); + + } +}; + +/** + * Your Graph object will be instantiated and called as such: + * Graph* obj = new Graph(n, edges); + * obj->addEdge(edge); + * int param_2 = obj->shortestPath(node1,node2); + */ \ No newline at end of file diff --git a/2642-design-graph-with-shortest-path-calculator/NOTES.md b/2642-design-graph-with-shortest-path-calculator/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2642-design-graph-with-shortest-path-calculator/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2642-design-graph-with-shortest-path-calculator/README.md b/2642-design-graph-with-shortest-path-calculator/README.md new file mode 100644 index 00000000..151185c6 --- /dev/null +++ b/2642-design-graph-with-shortest-path-calculator/README.md @@ -0,0 +1,41 @@ +

2642. Design Graph With Shortest Path Calculator

Hard


There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti.

+ +

Implement the Graph class:

+ +
    +
  • Graph(int n, int[][] edges) initializes the object with n nodes and the given edges.
  • +
  • addEdge(int[] edge) adds an edge to the list of edges where edge = [from, to, edgeCost]. It is guaranteed that there is no edge between the two nodes before adding this one.
  • +
  • int shortestPath(int node1, int node2) returns the minimum cost of a path from node1 to node2. If no path exists, return -1. The cost of a path is the sum of the costs of the edges in the path.
  • +
+ +

 

+

Example 1:

+ +
Input
+["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"]
+[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]]
+Output
+[null, 6, -1, null, 6]
+
+Explanation
+Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);
+g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6.
+g.shortestPath(0, 3); // return -1. There is no path from 0 to 3.
+g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above.
+g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 0 <= edges.length <= n * (n - 1)
  • +
  • edges[i].length == edge.length == 3
  • +
  • 0 <= fromi, toi, from, to, node1, node2 <= n - 1
  • +
  • 1 <= edgeCosti, edgeCost <= 106
  • +
  • There are no repeated edges and no self-loops in the graph at any point.
  • +
  • At most 100 calls will be made for addEdge.
  • +
  • At most 100 calls will be made for shortestPath.
  • +
+
\ No newline at end of file diff --git a/2648-generate-fibonacci-sequence/2648-generate-fibonacci-sequence.js b/2648-generate-fibonacci-sequence/2648-generate-fibonacci-sequence.js new file mode 100644 index 00000000..9522c83c --- /dev/null +++ b/2648-generate-fibonacci-sequence/2648-generate-fibonacci-sequence.js @@ -0,0 +1,19 @@ +/** + * @return {Generator} + */ +var fibGenerator = function*() { + let a = 0; + let b = 1; + + while (true){ + yield a; + [a,b] = [b,a+b]; + } + +}; + +/** + * const gen = fibGenerator(); + * gen.next().value; // 0 + * gen.next().value; // 1 + */ \ No newline at end of file diff --git a/2648-generate-fibonacci-sequence/README.md b/2648-generate-fibonacci-sequence/README.md new file mode 100644 index 00000000..b2ad9203 --- /dev/null +++ b/2648-generate-fibonacci-sequence/README.md @@ -0,0 +1,34 @@ +

2648. Generate Fibonacci Sequence

Easy


Write a generator function that returns a generator object which yields the fibonacci sequence.

+ +

The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2.

+ +

The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.

+ +

 

+

Example 1:

+ +
Input: callCount = 5
+Output: [0,1,1,2,3]
+Explanation:
+const gen = fibGenerator();
+gen.next().value; // 0
+gen.next().value; // 1
+gen.next().value; // 1
+gen.next().value; // 2
+gen.next().value; // 3
+
+ +

Example 2:

+ +
Input: callCount = 0
+Output: []
+Explanation: gen.next() is never called so nothing is outputted
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= callCount <= 50
  • +
+
\ No newline at end of file diff --git a/2649-nested-array-generator/2649-nested-array-generator.js b/2649-nested-array-generator/2649-nested-array-generator.js new file mode 100644 index 00000000..ee262017 --- /dev/null +++ b/2649-nested-array-generator/2649-nested-array-generator.js @@ -0,0 +1,20 @@ +/** + * @param {Array} arr + * @return {Generator} + */ +var inorderTraversal = function*(arr) { + + for (let i = 0; i < arr.length; i++){ + + if (Array.isArray(arr[i]))yield* inorderTraversal(arr[i]) + + else yield arr[i] + + } +}; +/** + * const gen = inorderTraversal([1, [2, 3]]); + * gen.next().value; // 1 + * gen.next().value; // 2 + * gen.next().value; // 3 + */ \ No newline at end of file diff --git a/2649-nested-array-generator/NOTES.md b/2649-nested-array-generator/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2649-nested-array-generator/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2649-nested-array-generator/README.md b/2649-nested-array-generator/README.md new file mode 100644 index 00000000..73c2baee --- /dev/null +++ b/2649-nested-array-generator/README.md @@ -0,0 +1,37 @@ +

2649. Nested Array Generator

Medium


Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.

+ +

multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.

+ +

inorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.

+ +

 

+

Example 1:

+ +
Input: arr = [[[6]],[1,3],[]]
+Output: [6,1,3]
+Explanation:
+const generator = inorderTraversal(arr);
+generator.next().value; // 6
+generator.next().value; // 1
+generator.next().value; // 3
+generator.next().done; // true
+
+ +

Example 2:

+ +
Input: arr = []
+Output: []
+Explanation: There are no integers so the generator doesn't yield anything.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= arr.flat().length <= 105
  • +
  • 0 <= arr.flat()[i] <= 105
  • +
  • maxNestingDepth <= 105
  • +
+ +

 

+Can you solve this without creating a new flattened version of the array?
\ No newline at end of file diff --git a/2661-first-completely-painted-row-or-column/2661-first-completely-painted-row-or-column.cpp b/2661-first-completely-painted-row-or-column/2661-first-completely-painted-row-or-column.cpp new file mode 100644 index 00000000..3f1b41c3 --- /dev/null +++ b/2661-first-completely-painted-row-or-column/2661-first-completely-painted-row-or-column.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int firstCompleteIndex(vector& arr, vector>& mat) { + + int n = mat.size(), m = mat[0].size(); + + vector row(n), col(m); + + map> mp; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + mp[mat[i][j]] = {i,j}; + } + } + + for(int i = 0; i < arr.size(); ++i) + { + int r= mp[arr[i]].first; + int c = mp[arr[i]].second; + + ++row[r], ++col[c]; + + if(row[r] == m or col[c] == n) + return i; + } + + return -1; + + } +}; \ No newline at end of file diff --git a/2661-first-completely-painted-row-or-column/NOTES.md b/2661-first-completely-painted-row-or-column/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2661-first-completely-painted-row-or-column/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2661-first-completely-painted-row-or-column/README.md b/2661-first-completely-painted-row-or-column/README.md new file mode 100644 index 00000000..2c71aa53 --- /dev/null +++ b/2661-first-completely-painted-row-or-column/README.md @@ -0,0 +1,35 @@ +

2661. First Completely Painted Row or Column

Medium


You are given a 0-indexed integer array arr, and an m x n integer matrix mat. arr and mat both contain all the integers in the range [1, m * n].

+ +

Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i].

+ +

Return the smallest index i at which either a row or a column will be completely painted in mat.

+ +

 

+

Example 1:

+image explanation for example 1 +
Input: arr = [1,3,4,2], mat = [[1,4],[2,3]]
+Output: 2
+Explanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].
+
+ +

Example 2:

+image explanation for example 2 +
Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
+Output: 3
+Explanation: The second column becomes fully painted at arr[3].
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n = mat[i].length
  • +
  • arr.length == m * n
  • +
  • 1 <= m, n <= 105
  • +
  • 1 <= m * n <= 105
  • +
  • 1 <= arr[i], mat[r][c] <= m * n
  • +
  • All the integers of arr are unique.
  • +
  • All the integers of mat are unique.
  • +
+
\ No newline at end of file diff --git a/2665-counter-ii/2665-counter-ii.js b/2665-counter-ii/2665-counter-ii.js new file mode 100644 index 00000000..0c55439c --- /dev/null +++ b/2665-counter-ii/2665-counter-ii.js @@ -0,0 +1,18 @@ +/** + * @param {integer} init + * @return { increment: Function, decrement: Function, reset: Function } + */ +var createCounter = function(init) { + let cnt = init; + return{ + increment: () => cnt+=1, decrement: () => cnt-=1, reset: () => (cnt=init), + } +}; + +/** + * const counter = createCounter(5) + * counter.increment(); // 6 + * counter.reset(); // 5 + * counter.decrement(); // 4 + */ + diff --git a/2665-counter-ii/README.md b/2665-counter-ii/README.md new file mode 100644 index 00000000..83e4bfe1 --- /dev/null +++ b/2665-counter-ii/README.md @@ -0,0 +1,43 @@ +

2665. Counter II

Easy


Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.

+ +

The three functions are:

+ +
    +
  • increment() increases the current value by 1 and then returns it.
  • +
  • decrement() reduces the current value by 1 and then returns it.
  • +
  • reset() sets the current value to init and then returns it.
  • +
+ +

 

+

Example 1:

+ +
Input: init = 5, calls = ["increment","reset","decrement"]
+Output: [6,5,4]
+Explanation:
+const counter = createCounter(5);
+counter.increment(); // 6
+counter.reset(); // 5
+counter.decrement(); // 4
+
+ +

Example 2:

+ +
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
+Output: [1,2,1,0,0]
+Explanation:
+const counter = createCounter(0);
+counter.increment(); // 1
+counter.increment(); // 2
+counter.decrement(); // 1
+counter.reset(); // 0
+counter.reset(); // 0
+
+ +

 

+

Constraints:

+ +
    +
  • -1000 <= init <= 1000
  • +
  • total calls not to exceed 1000
  • +
+
\ No newline at end of file diff --git a/2666-allow-one-function-call/2666-allow-one-function-call.js b/2666-allow-one-function-call/2666-allow-one-function-call.js new file mode 100644 index 00000000..d78e0aac --- /dev/null +++ b/2666-allow-one-function-call/2666-allow-one-function-call.js @@ -0,0 +1,23 @@ +/** + * @param {Function} fn + * @return {Function} + */ +var once = function(fn) { + + var ok = false; + + return function(...args){ + if(ok) + return undefined; + ok = true; + return fn(...args); + } +}; + +/** + * let fn = (a,b,c) => (a + b + c) + * let onceFn = once(fn) + * + * onceFn(1,2,3); // 6 + * onceFn(2,3,6); // returns undefined without calling fn + */ diff --git a/2666-allow-one-function-call/2666-allow-one-function-call.ts b/2666-allow-one-function-call/2666-allow-one-function-call.ts new file mode 100644 index 00000000..efeb5ee3 --- /dev/null +++ b/2666-allow-one-function-call/2666-allow-one-function-call.ts @@ -0,0 +1,19 @@ +function once any>(fn: T): + ((...args: Parameters) => ReturnType | undefined) { + + var ok = false; + return function (...args) { + if(ok) + return undefined; + ok = true; + return fn(...args); + }; +} + +/** + * let fn = (a,b,c) => (a + b + c) + * let onceFn = once(fn) + * + * onceFn(1,2,3); // 6 + * onceFn(2,3,6); // returns undefined without calling fn + */ \ No newline at end of file diff --git a/2666-allow-one-function-call/NOTES.md b/2666-allow-one-function-call/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2666-allow-one-function-call/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2666-allow-one-function-call/README.md b/2666-allow-one-function-call/README.md new file mode 100644 index 00000000..0e0e4d60 --- /dev/null +++ b/2666-allow-one-function-call/README.md @@ -0,0 +1,38 @@ +

2666. Allow One Function Call

Easy


Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.

+ +
    +
  • The first time the returned function is called, it should return the same result as fn.
  • +
  • Every subsequent time it is called, it should return undefined.
  • +
+ +

 

+

Example 1:

+ +
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
+Output: [{"calls":1,"value":6}]
+Explanation:
+const onceFn = once(fn);
+onceFn(1, 2, 3); // 6
+onceFn(2, 3, 6); // undefined, fn was not called
+
+ +

Example 2:

+ +
Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
+Output: [{"calls":1,"value":140}]
+Explanation:
+const onceFn = once(fn);
+onceFn(5, 7, 4); // 140
+onceFn(2, 3, 6); // undefined, fn was not called
+onceFn(4, 6, 8); // undefined, fn was not called
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= calls.length <= 10
  • +
  • 1 <= calls[i].length <= 100
  • +
  • 2 <= JSON.stringify(calls).length <= 1000
  • +
+
\ No newline at end of file diff --git a/2667-create-hello-world-function/2667-create-hello-world-function.js b/2667-create-hello-world-function/2667-create-hello-world-function.js new file mode 100644 index 00000000..e1dc4900 --- /dev/null +++ b/2667-create-hello-world-function/2667-create-hello-world-function.js @@ -0,0 +1,13 @@ +/** + * @return {Function} + */ +var createHelloWorld = function() { + return function(...args) { + return "Hello World"; + } +}; + +/** + * const f = createHelloWorld(); + * f(); // "Hello World" + */ \ No newline at end of file diff --git a/2667-create-hello-world-function/README.md b/2667-create-hello-world-function/README.md new file mode 100644 index 00000000..48112974 --- /dev/null +++ b/2667-create-hello-world-function/README.md @@ -0,0 +1,31 @@ +

2667. Create Hello World Function

Easy


Write a function createHelloWorld. It should return a new function that always returns "Hello World". +

 

+

Example 1:

+ +
Input: args = []
+Output: "Hello World"
+Explanation:
+const f = createHelloWorld();
+f(); // "Hello World"
+
+The function returned by createHelloWorld should always return "Hello World".
+
+ +

Example 2:

+ +
Input: args = [{},null,42]
+Output: "Hello World"
+Explanation:
+const f = createHelloWorld();
+f({}, null, 42); // "Hello World"
+
+Any arguments could be passed to the function but it should still always return "Hello World".
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= args.length <= 10
  • +
+
\ No newline at end of file diff --git a/2672-number-of-adjacent-elements-with-the-same-color/2672-number-of-adjacent-elements-with-the-same-color.cpp b/2672-number-of-adjacent-elements-with-the-same-color/2672-number-of-adjacent-elements-with-the-same-color.cpp new file mode 100644 index 00000000..55f9304a --- /dev/null +++ b/2672-number-of-adjacent-elements-with-the-same-color/2672-number-of-adjacent-elements-with-the-same-color.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector colorTheArray(int n, vector>& queries) { + + vector v(n,0); + + vector ans; + + int cnt = 0; + + for(auto itr : queries) + { + + int idx = itr[0]; + int col = itr[1]; + + if(idx > 0 and v[idx-1] == v[idx] and v[idx]) + --cnt; + if(idx+1 < n and v[idx+1] == v[idx] and v[idx]) + --cnt; + + v[idx] = col; + + if(idx > 0 and v[idx-1] == v[idx]) + ++cnt; + if(idx+1 < n and v[idx+1] == v[idx]) + ++cnt; + + ans.push_back(cnt); + } + + return ans; + + } + + +}; \ No newline at end of file diff --git a/2672-number-of-adjacent-elements-with-the-same-color/README.md b/2672-number-of-adjacent-elements-with-the-same-color/README.md new file mode 100644 index 00000000..07f8e95a --- /dev/null +++ b/2672-number-of-adjacent-elements-with-the-same-color/README.md @@ -0,0 +1,42 @@ +

2672. Number of Adjacent Elements With the Same Color

Medium


There is a 0-indexed array nums of length n. Initially, all elements are uncolored (has a value of 0).

+ +

You are given a 2D integer array queries where queries[i] = [indexi, colori].

+ +

For each query, you color the index indexi with the color colori in the array nums.

+ +

Return an array answer of the same length as queries where answer[i] is the number of adjacent elements with the same color after the ith query.

+ +

More formally, answer[i] is the number of indices j, such that 0 <= j < n - 1 and nums[j] == nums[j + 1] and nums[j] != 0 after the ith query.

+ +

 

+

Example 1:

+ +
Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
+Output: [0,1,1,0,2]
+Explanation: Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array.
+- After the 1st query nums = [2,0,0,0]. The count of adjacent elements with the same color is 0.
+- After the 2nd query nums = [2,2,0,0]. The count of adjacent elements with the same color is 1.
+- After the 3rd query nums = [2,2,0,1]. The count of adjacent elements with the same color is 1.
+- After the 4th query nums = [2,1,0,1]. The count of adjacent elements with the same color is 0.
+- After the 5th query nums = [2,1,1,1]. The count of adjacent elements with the same color is 2.
+
+ +

Example 2:

+ +
Input: n = 1, queries = [[0,100000]]
+Output: [0]
+Explanation: Initially array nums = [0], where 0 denotes uncolored elements of the array.
+- After the 1st query nums = [100000]. The count of adjacent elements with the same color is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 1 <= queries.length <= 105
  • +
  • queries[i].length == 2
  • +
  • 0 <= indexi <= n - 1
  • +
  • 1 <=  colori <= 105
  • +
+
\ No newline at end of file diff --git a/2675-array-of-objects-to-matrix/2675-array-of-objects-to-matrix.js b/2675-array-of-objects-to-matrix/2675-array-of-objects-to-matrix.js new file mode 100644 index 00000000..b8d5b21a --- /dev/null +++ b/2675-array-of-objects-to-matrix/2675-array-of-objects-to-matrix.js @@ -0,0 +1,14 @@ +/** + * @param {Array} arr + * @return {Matrix} + */ +const flatten = (a, prefix = []) => Object.entries(a) + .reduce((r, [k, v]) => (typeof v !== 'object' || v === null) + ? { ...r, [[...prefix, k].join('.')]: v } + : { ...r, ...flatten(v, [...prefix, k]) }, {}) + +const jsonToMatrix = (a) => { + a = a.map(i => flatten(i)) + const keys = Object.keys(a.reduce((r, i) => ({ ...r, ...i }), {})).sort() + return a.reduce((r, i) => [ ...r, keys.map(key => (key in i) ? i[key] : '')], [ keys ]) +} diff --git a/2675-array-of-objects-to-matrix/NOTES.md b/2675-array-of-objects-to-matrix/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2675-array-of-objects-to-matrix/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2675-array-of-objects-to-matrix/README.md b/2675-array-of-objects-to-matrix/README.md new file mode 100644 index 00000000..fc024862 --- /dev/null +++ b/2675-array-of-objects-to-matrix/README.md @@ -0,0 +1,121 @@ +

2675. Array of Objects to Matrix

Medium


Write a function that converts an array of objects arr into a matrix m.

+ +

arr is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and null values.

+ +

The first row m should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names are the respective paths in the object separated by ".".

+ +

Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds to a value in an object. If a given object doesn't contain a value for a given column, the cell should contain an empty string "".

+ +

The colums in the matrix should be in lexographically ascending order.

+ +

 

+

Example 1:

+ +
Input: 
+arr = [
+  {"b": 1, "a": 2},
+  {"b": 3, "a": 4}
+]
+Output: 
+[
+  ["a", "b"],
+  [2, 1],
+  [4, 3]
+]
+
+Explanation:
+There are two unique column names in the two objects: "a" and "b".
+"a" corresponds with [2, 4].
+"b" coresponds with [1, 3].
+
+ +

Example 2:

+ +
Input: 
+arr = [
+  {"a": 1, "b": 2},
+  {"c": 3, "d": 4},
+  {}
+]
+Output: 
+[
+  ["a", "b", "c", "d"],
+  [1, 2, "", ""],
+  ["", "", 3, 4],
+  ["", "", "", ""]
+]
+
+Explanation:
+There are 4 unique column names: "a", "b", "c", "d".
+The first object has values associated with "a" and "b".
+The second object has values associated with "c" and "d".
+The third object has no keys, so it is just a row of empty strings.
+
+ +

Example 3:

+ +
Input: 
+arr = [
+  {"a": {"b": 1, "c": 2}},
+  {"a": {"b": 3, "d": 4}}
+]
+Output: 
+[
+  ["a.b", "a.c", "a.d"],
+  [1, 2, ""],
+  [3, "", 4]
+]
+
+Explanation:
+In this example, the objects are nested. The keys represent the full path to each value separated by periods.
+There are three paths: "a.b", "a.c", "a.d".
+
+ +

Example 4:

+ +
Input: 
+arr = [
+  [{"a": null}],
+  [{"b": true}],
+  [{"c": "x"}]
+]
+Output: 
+[
+  ["0.a", "0.b", "0.c"],
+  [null, "", ""],
+  ["", true, ""],
+  ["", "", "x"]
+]
+
+Explanation:
+Arrays are also considered objects with their keys being their indices.
+Each array has one element so the keys are "0.a", "0.b", and "0.c".
+
+ +

Example 5:

+ +
Input: 
+arr = [
+  {},
+  {},
+  {},
+]
+Output: 
+[
+  [],
+  [],
+  [],
+  []
+]
+
+Explanation:
+There are no keys so every row is an empty array.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 1000
  • +
  • unique keys <= 1000
  • +
+
\ No newline at end of file diff --git a/2676-throttle/2676-throttle.js b/2676-throttle/2676-throttle.js new file mode 100644 index 00000000..85ea9e64 --- /dev/null +++ b/2676-throttle/2676-throttle.js @@ -0,0 +1,23 @@ +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ +var throttle = function(fn, t) { + let id = null + let nextTime = 0 + return function(...args) { + const delay = Math.max(0, nextTime - Date.now()) + clearTimeout(id) + id = setTimeout(() => { + fn(...args) + nextTime = Date.now() + t; + }, delay) + } +}; + +/** + * const throttled = throttle(console.log, 100); + * throttled("log"); // logged immediately. + * throttled("log"); // logged at t=100ms. + */ \ No newline at end of file diff --git a/2676-throttle/NOTES.md b/2676-throttle/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2676-throttle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2676-throttle/README.md b/2676-throttle/README.md new file mode 100644 index 00000000..f38ccfca --- /dev/null +++ b/2676-throttle/README.md @@ -0,0 +1,46 @@ +

2676. Throttle

Medium


Given a function fn and a time in milliseconds t, return a throttled version of that function.

+ +

A throttled function is first called without delay and then, for a time interval of t milliseconds, can't be executed but should store the latest function arguments provided to call fn with them after the end of the delay.

+ +

For instance, t = 50ms, and the function was called at 30ms, 40ms, and 60ms. The first function call would block calling functions for the following t milliseconds. The second function call would save arguments, and the third call arguments should overwrite currently stored arguments from the second call because the second and third calls are called before 80ms. Once the delay has passed, the throttled function should be called with the latest arguments provided during the delay period, and it should also create another delay period of 80ms + t.

+ +

Throttle DiagramThe above diagram shows how throttle will transform events. Each rectangle represents 100ms and the throttle time is 400ms. Each color represents a different set of inputs.

+ +

 

+

Example 1:

+ +
Input: t = 100, calls = [{"t":20,"inputs":[1]}]
+Output: [{"t":20,"inputs":[1]}]
+Explanation: The 1st call is always called without delay
+
+ +

Example 2:

+ +
Input: t = 50, calls = [{"t":50,"inputs":[1]},{"t":75,"inputs":[2]}]
+Output: [{"t":50,"inputs":[1]},{"t":100,"inputs":[2]}]
+Explanation: 
+The 1st is called a function with arguments (1) without delay.
+The 2nd is called at 75ms, within the delay period because 50ms + 50ms = 100ms, so the next call can be reached at 100ms. Therefore, we save arguments from the 2nd call to use them at the callback of the 1st call.
+
+ +

Example 3:

+ +
Input: t = 70, calls = [{"t":50,"inputs":[1]},{"t":75,"inputs":[2]},{"t":90,"inputs":[8]},{"t": 140, "inputs":[5,7]},{"t": 300, "inputs": [9,4]}]
+Output: [{"t":50,"inputs":[1]},{"t":120,"inputs":[8]},{"t":190,"inputs":[5,7]},{"t":300,"inputs":[9,4]}]
+Explanation: 
+The 1st is called a function with arguments (1) without delay.
+The 2nd is called at 75ms within the delay period because 50ms + 70ms = 120ms, so it should only save arguments. 
+The 3rd is also called within the delay period, and because we need just the latest function arguments, we overwrite previous ones. After the delay period, we do a callback at 120ms with saved arguments. That callback makes another delay period of 120ms + 70ms = 190ms so that the next function can be called at 190ms.
+The 4th is called at 140ms in the delay period, so it should be called as a callback at 190ms. That will create another delay period of 190ms + 70ms = 260ms.
+The 5th is called at 300ms, but it is after 260ms, so it should be called immediately and should create another delay period of 300ms + 70ms = 370ms.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= t <= 1000
  • +
  • 1 <= calls.length <= 10
  • +
  • 0 <= calls[i].t <= 1000
  • +
  • 0 <= calls[i].inputs[i], calls[i].inputs.length <= 10
  • +
+
\ No newline at end of file diff --git a/2677-chunk-array/2677-chunk-array.js b/2677-chunk-array/2677-chunk-array.js new file mode 100644 index 00000000..589d37bf --- /dev/null +++ b/2677-chunk-array/2677-chunk-array.js @@ -0,0 +1,16 @@ +/** + * @param {Array} arr + * @param {number} size + * @return {Array[]} + */ +var chunk = function(arr, size) { + var ans = []; + var index = 0; + + while (index < arr.length) { + ans.push(arr.slice(index, index + size)); + index += size; + } + + return ans; +}; diff --git a/2677-chunk-array/NOTES.md b/2677-chunk-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2677-chunk-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2677-chunk-array/README.md b/2677-chunk-array/README.md new file mode 100644 index 00000000..3f945f0a --- /dev/null +++ b/2677-chunk-array/README.md @@ -0,0 +1,43 @@ +

2677. Chunk Array

Easy


Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.

+ +

You may assume the array is the output of JSON.parse. In other words, it is valid JSON.

+ +

Please solve it without using lodash's _.chunk function.

+ +

 

+

Example 1:

+ +
Input: arr = [1,2,3,4,5], size = 1
+Output: [[1],[2],[3],[4],[5]]
+Explanation: The arr has been split into subarrays each with 1 element.
+
+ +

Example 2:

+ +
Input: arr = [1,9,6,3,2], size = 3
+Output: [[1,9,6],[3,2]]
+Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.
+
+ +

Example 3:

+ +
Input: arr = [8,5,3,2,6], size = 6
+Output: [[8,5,3,2,6]]
+Explanation: Size is greater than arr.length thus all elements are in the first subarray.
+
+ +

Example 4:

+ +
Input: arr = [], size = 1
+Output: []
+Explanation: There are no elements to be chunked so an empty array is returned.
+ +

 

+

Constraints:

+ +
    +
  • arr is a valid JSON array
  • +
  • 2 <= JSON.stringify(arr).length <= 105
  • +
  • 1 <= size <= arr.length + 1
  • +
+
\ No newline at end of file diff --git a/2678-number-of-senior-citizens/2678-number-of-senior-citizens.cpp b/2678-number-of-senior-citizens/2678-number-of-senior-citizens.cpp new file mode 100644 index 00000000..d02e9832 --- /dev/null +++ b/2678-number-of-senior-citizens/2678-number-of-senior-citizens.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countSeniors(vector& details) { + + int cnt = 0; + + for(auto& str : details) + { + cnt += (stoi(str.substr(11, 2)) > 60); + } + + return cnt; + } +}; \ No newline at end of file diff --git a/2678-number-of-senior-citizens/README.md b/2678-number-of-senior-citizens/README.md new file mode 100644 index 00000000..f48784b3 --- /dev/null +++ b/2678-number-of-senior-citizens/README.md @@ -0,0 +1,37 @@ +

2678. Number of Senior Citizens

Easy


You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:

+ +
    +
  • The first ten characters consist of the phone number of passengers.
  • +
  • The next character denotes the gender of the person.
  • +
  • The following two characters are used to indicate the age of the person.
  • +
  • The last two characters determine the seat allotted to that person.
  • +
+ +

Return the number of passengers who are strictly more than 60 years old.

+ +

 

+

Example 1:

+ +
Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"]
+Output: 2
+Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.
+
+ +

Example 2:

+ +
Input: details = ["1313579440F2036","2921522980M5644"]
+Output: 0
+Explanation: None of the passengers are older than 60.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= details.length <= 100
  • +
  • details[i].length == 15
  • +
  • details[i] consists of digits from '0' to '9'.
  • +
  • details[i][10] is either 'M' or 'F' or 'O'.
  • +
  • The phone numbers and seat numbers of the passengers are distinct.
  • +
+
\ No newline at end of file diff --git a/2680-maximum-or/2680-maximum-or.cpp b/2680-maximum-or/2680-maximum-or.cpp new file mode 100644 index 00000000..21840949 --- /dev/null +++ b/2680-maximum-or/2680-maximum-or.cpp @@ -0,0 +1,32 @@ + +using ll = long long; +class Solution { +public: + long long maximumOr(vector& nums, int k) { + + int n = nums.size(); + + vector pref(n, 0), suff(n, 0); + + pref[0] = nums[0], suff[n-1] = nums[n-1]; + + for(int i = 1; i < n; ++i) + pref[i] = pref[i-1] | nums[i]; + + for(int i = n-2; i >= 0; --i) + suff[i] = suff[i+1] | nums[i]; + + ll res = 0, mult = 1 << k; + + for(int i = 0; i < n; ++i) + { + ll left = (i == 0 ? 0 : pref[i-1]); + ll right = (i+1 == n ? 0 : suff[i+1]); + + ll ans = left | (mult*nums[i]) | right; + res = max(res, ans); + } + + return res; + } +}; \ No newline at end of file diff --git a/2680-maximum-or/NOTES.md b/2680-maximum-or/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2680-maximum-or/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2680-maximum-or/README.md b/2680-maximum-or/README.md new file mode 100644 index 00000000..1d8976a3 --- /dev/null +++ b/2680-maximum-or/README.md @@ -0,0 +1,30 @@ +

2680. Maximum OR

Medium


You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2.

+ +

Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times.

+ +

Note that a | b denotes the bitwise or between two integers a and b.

+ +

 

+

Example 1:

+ +
Input: nums = [12,9], k = 1
+Output: 30
+Explanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30.
+
+ +

Example 2:

+ +
Input: nums = [8,1,2], k = 2
+Output: 35
+Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= k <= 15
  • +
+
\ No newline at end of file diff --git a/2693-call-function-with-custom-context/2693-call-function-with-custom-context.js b/2693-call-function-with-custom-context/2693-call-function-with-custom-context.js new file mode 100644 index 00000000..48ee53f2 --- /dev/null +++ b/2693-call-function-with-custom-context/2693-call-function-with-custom-context.js @@ -0,0 +1,18 @@ +/** + * @param {Object} context + * @param {any[]} args + * @return {any} + */ +Function.prototype.callPolyfill = function(context, ...args) { + let a = Symbol(); + context[a] = this; + let res = context[a](...args); + delete context[a]; + + return res; +} + +/** + * function increment() { this.count++; return this.count; } + * increment.callPolyfill({count: 1}); // 2 + */ \ No newline at end of file diff --git a/2693-call-function-with-custom-context/README.md b/2693-call-function-with-custom-context/README.md new file mode 100644 index 00000000..87d051a7 --- /dev/null +++ b/2693-call-function-with-custom-context/README.md @@ -0,0 +1,50 @@ +

2693. Call Function with Custom Context

Medium


Enhance all functions to have the callPolyfill method. The method accepts an object obj as it's first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).

+ +

For example if you had the function:

+ +
function tax(price, taxRate) {
+  const totalCost = price * (1 + taxRate);
+  console.log(`The cost of ${this.item} is ${totalCost}`);
+}
+
+ +

Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.

+ +

However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output.

+ +

Please solve this without using the built-in Function.call method.

+ +

 

+

Example 1:

+ +
Input:
+fn = function add(b) {
+  return this.a + b;
+}
+args = [{"a": 5}, 7]
+Output: 12
+Explanation:
+fn.callPolyfill({"a": 5}, 7); // 12
+callPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.
+
+ +

Example 2:

+ +
Input: 
+fn = function tax(price, taxRate) { 
+ return `The cost of the ${this.item} is ${price * taxRate}`; 
+}
+args = [{"item": "burger"}, 10, 1,1]
+Output: "The cost of the burger is 11"
+Explanation: callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments.
+
+ +

 

+

Constraints:

+ +
    +
  • typeof args[0] == 'object' and args[0] != null
  • +
  • 1 <= args.length <= 100
  • +
  • 2 <= JSON.stringify(args[0]).length <= 105
  • +
+
\ No newline at end of file diff --git a/2695-array-wrapper/NOTES.md b/2695-array-wrapper/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2695-array-wrapper/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2695-array-wrapper/README.md b/2695-array-wrapper/README.md new file mode 100644 index 00000000..8d80d3c9 --- /dev/null +++ b/2695-array-wrapper/README.md @@ -0,0 +1,46 @@ +

2695. Array Wrapper

Easy


Create a class ArrayWrapper that accepts an array of integers in it's constructor. This class should have two features:

+ +
    +
  • When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
  • +
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].
  • +
+ +

 

+

Example 1:

+ +
Input: nums = [[1,2],[3,4]], operation = "Add"
+Output: 10
+Explanation:
+const obj1 = new ArrayWrapper([1,2]);
+const obj2 = new ArrayWrapper([3,4]);
+obj1 + obj2; // 10
+
+ +

Example 2:

+ +
Input: nums = [[23,98,42,70]], operation = "String"
+Output: "[23,98,42,70]"
+Explanation:
+const obj = new ArrayWrapper([23,98,42,70]);
+String(obj); // "[23,98,42,70]"
+
+ +

Example 3:

+ +
Input: nums = [[],[]], operation = "Add"
+Output: 0
+Explanation:
+const obj1 = new ArrayWrapper([]);
+const obj2 = new ArrayWrapper([]);
+obj1 + obj2; // 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
  • Note: nums is the array passed to the constructor
  • +
+
\ No newline at end of file diff --git a/2698-find-the-punishment-number-of-an-integer/2698-find-the-punishment-number-of-an-integer.cpp b/2698-find-the-punishment-number-of-an-integer/2698-find-the-punishment-number-of-an-integer.cpp new file mode 100644 index 00000000..6443b82f --- /dev/null +++ b/2698-find-the-punishment-number-of-an-integer/2698-find-the-punishment-number-of-an-integer.cpp @@ -0,0 +1,45 @@ +class Solution { + +private: + + bool possible(string str, int target) + { + if(str == "" and target == 0) + return true; + + if(target < 0) + return false; + + for(int i = 0; i < str.size(); ++i) + { + string left = str.substr(0, i+1); + string right = str.substr(i+1); + + int leftPart = stoi(left); + + if(possible(right, target - leftPart)) + return true; + } + + return false; + } + +public: + + int punishmentNumber(int n) { + + int ans = 0; + + for(int i = 1; i <=n; ++i) + { + int num = (i*i); + string str = to_string(num); + + if(possible(str , i )) + ans += num; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2698-find-the-punishment-number-of-an-integer/NOTES.md b/2698-find-the-punishment-number-of-an-integer/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2698-find-the-punishment-number-of-an-integer/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2698-find-the-punishment-number-of-an-integer/README.md b/2698-find-the-punishment-number-of-an-integer/README.md new file mode 100644 index 00000000..6f307670 --- /dev/null +++ b/2698-find-the-punishment-number-of-an-integer/README.md @@ -0,0 +1,40 @@ +

2698. Find the Punishment Number of an Integer

Medium


Given a positive integer n, return the punishment number of n.

+ +

The punishment number of n is defined as the sum of the squares of all integers i such that:

+ +
    +
  • 1 <= i <= n
  • +
  • The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.
  • +
+ +

 

+

Example 1:

+ +
Input: n = 10
+Output: 182
+Explanation: There are exactly 3 integers i that satisfy the conditions in the statement:
+- 1 since 1 * 1 = 1
+- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1.
+- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0.
+Hence, the punishment number of 10 is 1 + 81 + 100 = 182
+
+ +

Example 2:

+ +
Input: n = 37
+Output: 1478
+Explanation: There are exactly 4 integers i that satisfy the conditions in the statement:
+- 1 since 1 * 1 = 1. 
+- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. 
+- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. 
+- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.
+Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1000
  • +
+
\ No newline at end of file diff --git a/2700-differences-between-two-objects/README.md b/2700-differences-between-two-objects/README.md new file mode 100644 index 00000000..f2f72fb7 --- /dev/null +++ b/2700-differences-between-two-objects/README.md @@ -0,0 +1,113 @@ +

2700. Differences Between Two Objects

Medium


Write a function that accepts two deeply nested objects or arrays obj1 and obj2 and returns a new object representing their differences.

+ +

The function should compare the properties of the two objects and identify any changes. The returned object should only contains keys where the value is different from obj1 to obj2. For each changed key, the value should be represented as an array [obj1 value, obj2 value]. Keys that exist in one object but not in the other should not be included in the returned object. When comparing two arrays, the indices of the arrays are considered to be their keys. The end result should be a deeply nested object where each leaf value is a difference array.

+ +

You may assume that both objects are the output of JSON.parse.

+ +

 

+

Example 1:

+ +
Input: 
+obj1 = {}
+obj2 = {
+  "a": 1, 
+  "b": 2
+}
+Output: {}
+Explanation: There were no modifications made to obj1. New keys "a" and "b" appear in obj2, but keys that are added or removed should be ignored.
+
+ +

Example 2:

+ +
Input: 
+obj1 = {
+  "a": 1,
+  "v": 3,
+  "x": [],
+  "z": {
+    "a": null
+  }
+}
+obj2 = {
+  "a": 2,
+  "v": 4,
+  "x": [],
+  "z": {
+    "a": 2
+  }
+}
+Output: 
+{
+  "a": [1, 2],
+  "v": [3, 4],
+  "z": {
+    "a": [null, 2]
+  }
+}
+Explanation: The keys "a", "v", and "z" all had changes applied. "a" was chnaged from 1 to 2. "v" was changed from 3 to 4. "z" had a change applied to a child object. "z.a" was changed from null to 2.
+
+ +

Example 3:

+ +
Input: 
+obj1 = {
+  "a": 5, 
+  "v": 6, 
+  "z": [1, 2, 4, [2, 5, 7]]
+}
+obj2 = {
+  "a": 5, 
+  "v": 7, 
+  "z": [1, 2, 3, [1]]
+}
+Output: 
+{
+  "v": [6, 7],
+  "z": {
+    "2": [4, 3],
+    "3": {
+      "0": [2, 1]
+    }
+  }
+}
+Explanation: In obj1 and obj2, the keys "v" and "z" have different assigned values. "a" is ignored because the value is unchanged. In the key "z", there is a nested array. Arrays are treated like objects where the indices are keys. There were two alterations to the the array: z[2] and z[3][0]. z[0] and z[1] were unchanged and thus not included. z[3][1] and z[3][2] were removed and thus not included.
+
+ +

Example 4:

+ +
Input: 
+obj1 = {
+  "a": {"b": 1}, 
+}
+obj2 = {
+  "a": [5],
+}
+Output: 
+{
+  "a": [{"b": 1}, [5]]
+}
+Explanation: The key "a" exists in both objects. Since the two associated values have different types, they are placed in the difference array.
+ +

Example 5:

+ +
Input: 
+obj1 = {
+  "a": [1, 2, {}], 
+  "b": false
+}
+obj2 = {   
+  "b": false,
+  "a": [1, 2, {}]
+}
+Output: 
+{}
+Explanation: Apart from a different ordering of keys, the two objects are identical so an empty object is returned.
+ +

 

+

Constraints:

+ +
    +
  • 2 <= JSON.stringify(obj1).length <= 104
  • +
  • 2 <= JSON.stringify(obj2).length <= 104
  • +
+
\ No newline at end of file diff --git a/2706-buy-two-chocolates/2706-buy-two-chocolates.cpp b/2706-buy-two-chocolates/2706-buy-two-chocolates.cpp new file mode 100644 index 00000000..f26c009f --- /dev/null +++ b/2706-buy-two-chocolates/2706-buy-two-chocolates.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int buyChoco(vector& prices, int money) { + sort(prices.begin(), prices.end()); + int sum = prices[0] + prices[1]; + return (sum > money)?money: (money - sum); + } +}; \ No newline at end of file diff --git a/2706-buy-two-chocolates/NOTES.md b/2706-buy-two-chocolates/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2706-buy-two-chocolates/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2706-buy-two-chocolates/README.md b/2706-buy-two-chocolates/README.md new file mode 100644 index 00000000..c6497e3f --- /dev/null +++ b/2706-buy-two-chocolates/README.md @@ -0,0 +1,30 @@ +

2706. Buy Two Chocolates

Easy


You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money.

+ +

You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.

+ +

Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

+ +

 

+

Example 1:

+ +
Input: prices = [1,2,2], money = 3
+Output: 0
+Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.
+
+ +

Example 2:

+ +
Input: prices = [3,2,3], money = 3
+Output: 3
+Explanation: You cannot buy 2 chocolates without going in debt, so we return 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= prices.length <= 50
  • +
  • 1 <= prices[i] <= 100
  • +
  • 1 <= money <= 100
  • +
+
\ No newline at end of file diff --git a/2707-extra-characters-in-a-string/2707-extra-characters-in-a-string.cpp b/2707-extra-characters-in-a-string/2707-extra-characters-in-a-string.cpp new file mode 100644 index 00000000..46b0c857 --- /dev/null +++ b/2707-extra-characters-in-a-string/2707-extra-characters-in-a-string.cpp @@ -0,0 +1,41 @@ +class Solution { + +private: + int helper(int idx, int n, string& s, unordered_set& used, vector& dp) + { + if(idx == n) + return 0; + + if(dp[idx] != -1) + return dp[idx]; + + int minExtra = n; + + string temp; + + for(int i = idx; i < n; ++i) + { + temp += s[i]; + + int currExtra = used.find(temp) != used.end() ? 0 : temp.size(); + int nextExtra = helper(i + 1, n, s, used , dp); + int totalExtra = currExtra + nextExtra; + + minExtra = min(minExtra, totalExtra); + + } + return dp[idx] = minExtra; + } + +public: + int minExtraChar(string s, vector& dictionary) { + + int n = s.size(); + + unordered_set used(dictionary.begin(), dictionary.end()); + + vector dp(n+1, -1); + + return helper(0, n, s, used, dp); + } +}; \ No newline at end of file diff --git a/2707-extra-characters-in-a-string/README.md b/2707-extra-characters-in-a-string/README.md new file mode 100644 index 00000000..1f148b75 --- /dev/null +++ b/2707-extra-characters-in-a-string/README.md @@ -0,0 +1,31 @@ +

2707. Extra Characters in a String

Medium


You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings.

+ +

Return the minimum number of extra characters left over if you break up s optimally.

+ +

 

+

Example 1:

+ +
Input: s = "leetscode", dictionary = ["leet","code","leetcode"]
+Output: 1
+Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
+
+
+ +

Example 2:

+ +
Input: s = "sayhelloworld", dictionary = ["hello","world"]
+Output: 3
+Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 50
  • +
  • 1 <= dictionary.length <= 50
  • +
  • 1 <= dictionary[i].length <= 50
  • +
  • dictionary[i] and s consists of only lowercase English letters
  • +
  • dictionary contains distinct words
  • +
+
\ No newline at end of file diff --git a/2709-greatest-common-divisor-traversal/2709-greatest-common-divisor-traversal.cpp b/2709-greatest-common-divisor-traversal/2709-greatest-common-divisor-traversal.cpp new file mode 100644 index 00000000..242430ac --- /dev/null +++ b/2709-greatest-common-divisor-traversal/2709-greatest-common-divisor-traversal.cpp @@ -0,0 +1,58 @@ +class Solution { + int getf(vector &f, int x) { + return f[x] == x ? x : (f[x] = getf(f, f[x])); + } + + void merge(vector &f, vector &num, int x, int y) { + x = getf(f, x); + y = getf(f, y); + if (x == y) { + return; + } + if (num[x] < num[y]) { + swap(x, y); + } + f[y] = x; + num[x] += num[y]; + } +public: + bool canTraverseAllPairs(vector& nums) { + const int n = nums.size(); + if (n == 1) { + return true; + } + vector f(n), num(n); + for (int i = 0; i < n; ++i) { + f[i] = i; + num[i] = 1; + } + unordered_map have; + for (int i = 0; i < n; ++i) { + int x = nums[i]; + if (x == 1) { + return false; + } + for (int d = 2; d * d <= x; ++d) { + if (x % d == 0) { + if (have.count(d)) { + merge(f, num, i, have[d]); + } else { + have[d] = i; + } + while (x % d == 0) { + x /= d; + } + } + } + if (x > 1) { + if (have.count(x)) { + merge(f, num, i, have[x]); + } else { + have[x] = i; + } + } + } + return num[getf(f, 0)] == n; + + } +}; \ No newline at end of file diff --git a/2709-greatest-common-divisor-traversal/NOTES.md b/2709-greatest-common-divisor-traversal/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2709-greatest-common-divisor-traversal/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2709-greatest-common-divisor-traversal/README.md b/2709-greatest-common-divisor-traversal/README.md new file mode 100644 index 00000000..b66d140a --- /dev/null +++ b/2709-greatest-common-divisor-traversal/README.md @@ -0,0 +1,38 @@ +

2709. Greatest Common Divisor Traversal

Hard


You are given a 0-indexed integer array nums, and you are allowed to traverse between its indices. You can traverse between index i and index j, i != j, if and only if gcd(nums[i], nums[j]) > 1, where gcd is the greatest common divisor.

+ +

Your task is to determine if for every pair of indices i and j in nums, where i < j, there exists a sequence of traversals that can take us from i to j.

+ +

Return true if it is possible to traverse between all such pairs of indices, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,6]
+Output: true
+Explanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2).
+To go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1.
+To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1.
+
+ +

Example 2:

+ +
Input: nums = [3,9,5]
+Output: false
+Explanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false.
+
+ +

Example 3:

+ +
Input: nums = [4,3,12,8]
+Output: true
+Explanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
+
\ No newline at end of file diff --git a/2741-special-permutations/2741-special-permutations.cpp b/2741-special-permutations/2741-special-permutations.cpp new file mode 100644 index 00000000..d236c5bc --- /dev/null +++ b/2741-special-permutations/2741-special-permutations.cpp @@ -0,0 +1,42 @@ +class Solution { + +private: + + int mod = 1e9 + 7; + + int helper(int idx, int prev, int mask, int n, vector& nums, vector>& dp) + { + if(idx == n) + return 1; + + if(dp[prev+1][mask] != -1) + return dp[prev+1][mask]; + + int ans = 0; + + for(int i = 0; i < n; ++i) + { + if(mask & (1 << i)) + continue; + + if(prev == -1 or nums[i] % nums[prev] == 0 or nums[prev] % nums[i] == 0) + { + ans += helper(idx+1, i, mask | (1 << i), n, nums, dp); + ans %= mod; + } + } + + return dp[prev+1][mask] = ans; + } + +public: + int specialPerm(vector& nums) { + + int n = nums.size(); + + vector> dp(n+1, vector(1 << 14 + 1, -1)); + + return helper(0, -1, 0, n, nums, dp); + + } +}; \ No newline at end of file diff --git a/2741-special-permutations/NOTES.md b/2741-special-permutations/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2741-special-permutations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2741-special-permutations/README.md b/2741-special-permutations/README.md new file mode 100644 index 00000000..cffc2930 --- /dev/null +++ b/2741-special-permutations/README.md @@ -0,0 +1,31 @@ +

2741. Special Permutations

Medium


You are given a 0-indexed integer array nums containing n distinct positive integers. A permutation of nums is called special if:

+ +
    +
  • For all indexes 0 <= i < n - 1, either nums[i] % nums[i+1] == 0 or nums[i+1] % nums[i] == 0.
  • +
+ +

Return the total number of special permutations. As the answer could be large, return it modulo 10+ 7.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,6]
+Output: 2
+Explanation: [3,6,2] and [2,6,3] are the two special permutations of nums.
+
+ +

Example 2:

+ +
Input: nums = [1,4,3]
+Output: 2
+Explanation: [3,1,4] and [4,1,3] are the two special permutations of nums.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 14
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2742-painting-the-walls/2742-painting-the-walls.cpp b/2742-painting-the-walls/2742-painting-the-walls.cpp new file mode 100644 index 00000000..7c95a47b --- /dev/null +++ b/2742-painting-the-walls/2742-painting-the-walls.cpp @@ -0,0 +1,30 @@ +class Solution { + +private: + int helper(int idx, int walls, vector& cost, vector& time, vector>& dp) + { + if(walls <= 0) + return 0; + + if(idx >= cost.size()) + return INT_MAX/2; + + if(dp[idx][walls] != -1) + return dp[idx][walls]; + + int notTake = helper(idx+1, walls, cost, time, dp); + int take = cost[idx] + helper(idx+1, walls - time[idx] - 1, cost, time, dp); + + return dp[idx][walls] = min(take, notTake); + } +public: + int paintWalls(vector& cost, vector& time) { + + int n = cost.size(); + + vector> dp(501, vector(501, -1)); + + return helper(0, n, cost, time, dp); + + } +}; \ No newline at end of file diff --git a/2742-painting-the-walls/NOTES.md b/2742-painting-the-walls/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2742-painting-the-walls/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2742-painting-the-walls/README.md b/2742-painting-the-walls/README.md new file mode 100644 index 00000000..cf18a4cb --- /dev/null +++ b/2742-painting-the-walls/README.md @@ -0,0 +1,34 @@ +

2742. Painting the Walls

Hard


You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:

+ +
    +
  • A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of money.
  • +
  • A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied.
  • +
+ +

Return the minimum amount of money required to paint the n walls.

+ +

 

+

Example 1:

+ +
Input: cost = [1,2,3,2], time = [1,2,3,2]
+Output: 3
+Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
+
+ +

Example 2:

+ +
Input: cost = [2,3,4,2], time = [1,1,1,1]
+Output: 4
+Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= cost.length <= 500
  • +
  • cost.length == time.length
  • +
  • 1 <= cost[i] <= 106
  • +
  • 1 <= time[i] <= 500
  • +
+
\ No newline at end of file diff --git a/2785-sort-vowels-in-a-string/NOTES.md b/2785-sort-vowels-in-a-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2785-sort-vowels-in-a-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2785-sort-vowels-in-a-string/README.md b/2785-sort-vowels-in-a-string/README.md new file mode 100644 index 00000000..e6652348 --- /dev/null +++ b/2785-sort-vowels-in-a-string/README.md @@ -0,0 +1,34 @@ +

2785. Sort Vowels in a String

Medium


Given a 0-indexed string s, permute s to get a new string t such that:

+ +
    +
  • All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].
  • +
  • The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].
  • +
+ +

Return the resulting string.

+ +

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

+ +

 

+

Example 1:

+ +
Input: s = "lEetcOde"
+Output: "lEOtcede"
+Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.
+
+ +

Example 2:

+ +
Input: s = "lYmpH"
+Output: "lYmpH"
+Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists only of letters of the English alphabet in uppercase and lowercase.
  • +
+
\ No newline at end of file diff --git a/2811-check-if-it-is-possible-to-split-array/2811-check-if-it-is-possible-to-split-array.cpp b/2811-check-if-it-is-possible-to-split-array/2811-check-if-it-is-possible-to-split-array.cpp new file mode 100644 index 00000000..064b7327 --- /dev/null +++ b/2811-check-if-it-is-possible-to-split-array/2811-check-if-it-is-possible-to-split-array.cpp @@ -0,0 +1,56 @@ +class Solution { + +private: + + bool posibleToPartition(int start, int end, int m, vector& nums) + { + int sum = 0; + + for(int i = start; i <= end; ++i) + { + sum += nums[i]; + + if(sum >= m) + return true; + } + return false; + } + + bool helper(int start, int end, int m, vector& nums, vector>& dp) + { + if(start == end) + return true; + + if(!posibleToPartition(start, end, m, nums)) + return false; + + if(dp[start][end] != -1) + return dp[start][end]; + + for(int i = start; i < end; ++i) + { + bool leftHalf = helper(start, i, m, nums, dp); + bool rightHalf = helper(i+1 , end, m , nums, dp); + + if(leftHalf and rightHalf) + { + return dp[start][end] = true; + } + } + return dp[start][end] = false; + } + +public: + bool canSplitArray(vector& nums, int m) { + + int n = nums.size(); + + if(n <= 2) + return true; + + vector> dp(n, vector(n,-1)); + + return helper(0, n-1, m, nums, dp); + + } +}; \ No newline at end of file diff --git a/2811-check-if-it-is-possible-to-split-array/NOTES.md b/2811-check-if-it-is-possible-to-split-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2811-check-if-it-is-possible-to-split-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2811-check-if-it-is-possible-to-split-array/README.md b/2811-check-if-it-is-possible-to-split-array/README.md new file mode 100644 index 00000000..ee11d137 --- /dev/null +++ b/2811-check-if-it-is-possible-to-split-array/README.md @@ -0,0 +1,42 @@ +

2811. Check if it is Possible to Split Array

Medium


You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n non-empty arrays by performing a series of steps.

+ +

In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two subarrays, if, for each resulting subarray, at least one of the following holds:

+ +
    +
  • The length of the subarray is one, or
  • +
  • The sum of elements of the subarray is greater than or equal to m.
  • +
+ +

Return true if you can split the given array into n arrays, otherwise return false.

+ +

Note: A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [2, 2, 1], m = 4
+Output: true
+Explanation: We can split the array into [2, 2] and [1] in the first step. Then, in the second step, we can split [2, 2] into [2] and [2]. As a result, the answer is true.
+ +

Example 2:

+ +
Input: nums = [2, 1, 3], m = 5 
+Output: false
+Explanation: We can try splitting the array in two different ways: the first way is to have [2, 1] and [3], and the second way is to have [2] and [1, 3]. However, both of these ways are not valid. So, the answer is false.
+ +

Example 3:

+ +
Input: nums = [2, 3, 3, 2, 3], m = 6
+Output: true
+Explanation: We can split the array into [2, 3, 3, 2] and [3] in the first step. Then, in the second step, we can split [2, 3, 3, 2] into [2, 3, 3] and [2]. Then, in the third step, we can split [2, 3, 3] into [2] and [3, 3]. And in the last step we can split [3, 3] into [3] and [3]. As a result, the answer is true.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n == nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
  • 1 <= m <= 200
  • +
+
\ No newline at end of file diff --git a/2812-find-the-safest-path-in-a-grid/2812-find-the-safest-path-in-a-grid.cpp b/2812-find-the-safest-path-in-a-grid/2812-find-the-safest-path-in-a-grid.cpp new file mode 100644 index 00000000..b8afb8d2 --- /dev/null +++ b/2812-find-the-safest-path-in-a-grid/2812-find-the-safest-path-in-a-grid.cpp @@ -0,0 +1,93 @@ +class Solution { +public: + int maximumSafenessFactor(vector>& grid) { + + int n = grid.size(), m = grid[0].size(); + + vector> minimumMahattanDistance(n, vector(m, 0)); + + queue> q; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(grid[i][j] == 1) + { + q.push({i,j}); + minimumMahattanDistance[i][j] = 0; + } + } + } + + vector dx = {-1, 0, 0, +1}; + vector dy = {0, -1, +1, 0}; + + while(!q.empty()) + { + auto curr = q.front(); + q.pop(); + + int x = curr.first; + int y = curr.second; + + for(int i = 0; i < 4; ++i) + { + int newx = x + dx[i]; + int newy = y + dy[i]; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and grid[newx][newy] != 1 and minimumMahattanDistance[newx][newy] == 0) + { + q.push({newx, newy}); + minimumMahattanDistance[newx][newy] = minimumMahattanDistance[x][y] + 1; + } + } + } + + // for(auto itr : minimumMahattanDistance) + // { + // for(auto row : itr) + // cout<> visited(n, vector(m, false)); + + int ans = minimumMahattanDistance[0][0]; + + priority_queue> > pq; + + pq.push({minimumMahattanDistance[0][0],{0,0}}); + + visited[0][0] = true; + + while(!pq.empty()) + { + auto curr = pq.top(); + pq.pop(); + + int maximumSafenessFactor = curr.first; + int x = curr.second.first; + int y = curr.second.second; + + if(x == n-1 and y == m-1) + { + return maximumSafenessFactor; + } + + for(int i = 0; i < 4; ++i) + { + int newx = x + dx[i]; + int newy = y + dy[i]; + + if(newx >= 0 and newy >= 0 and newx < n and newy < m and !visited[newx][newy]) + { + pq.push({min(maximumSafenessFactor,minimumMahattanDistance[newx][newy]),{newx, newy}}); + visited[newx][newy] = true; + } + } + } + + return 0; + } +}; \ No newline at end of file diff --git a/2812-find-the-safest-path-in-a-grid/NOTES.md b/2812-find-the-safest-path-in-a-grid/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2812-find-the-safest-path-in-a-grid/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2812-find-the-safest-path-in-a-grid/README.md b/2812-find-the-safest-path-in-a-grid/README.md new file mode 100644 index 00000000..1565a57a --- /dev/null +++ b/2812-find-the-safest-path-in-a-grid/README.md @@ -0,0 +1,54 @@ +

2812. Find the Safest Path in a Grid

Medium


You are given a 0-indexed 2D matrix grid of size n x n, where (r, c) represents:

+ +
    +
  • A cell containing a thief if grid[r][c] = 1
  • +
  • An empty cell if grid[r][c] = 0
  • +
+ +

You are initially positioned at cell (0, 0). In one move, you can move to any adjacent cell in the grid, including cells containing thieves.

+ +

The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid.

+ +

Return the maximum safeness factor of all paths leading to cell (n - 1, n - 1).

+ +

An adjacent cell of cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) and (r - 1, c) if it exists.

+ +

The Manhattan distance between two cells (a, b) and (x, y) is equal to |a - x| + |b - y|, where |val| denotes the absolute value of val.

+ +

 

+

Example 1:

+ +
Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
+Output: 0
+Explanation: All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
+
+ +

Example 2:

+ +
Input: grid = [[0,0,1],[0,0,0],[0,0,0]]
+Output: 2
+Explanation: The path depicted in the picture above has a safeness factor of 2 since:
+- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
+It can be shown that there are no other paths with a higher safeness factor.
+
+ +

Example 3:

+ +
Input: grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
+Output: 2
+Explanation: The path depicted in the picture above has a safeness factor of 2 since:
+- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
+- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
+It can be shown that there are no other paths with a higher safeness factor.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= grid.length == n <= 400
  • +
  • grid[i].length == n
  • +
  • grid[i][j] is either 0 or 1.
  • +
  • There is at least one thief in the grid.
  • +
+
\ No newline at end of file diff --git a/2816-double-a-number-represented-as-a-linked-list/2816-double-a-number-represented-as-a-linked-list.cpp b/2816-double-a-number-represented-as-a-linked-list/2816-double-a-number-represented-as-a-linked-list.cpp new file mode 100644 index 00000000..d5ac5ea5 --- /dev/null +++ b/2816-double-a-number-represented-as-a-linked-list/2816-double-a-number-represented-as-a-linked-list.cpp @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + + int add(ListNode* head) + { + if(!head) + return 0; + + int sum = (head->val * 2) + add(head->next); + + head->val = sum % 10; + + return sum / 10; + } + + ListNode* doubleIt(ListNode* head) { + + int carry = add(head); + + if(carry) + head = new ListNode(carry, head); + + return head; + + } +}; \ No newline at end of file diff --git a/2816-double-a-number-represented-as-a-linked-list/NOTES.md b/2816-double-a-number-represented-as-a-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2816-double-a-number-represented-as-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2816-double-a-number-represented-as-a-linked-list/README.md b/2816-double-a-number-represented-as-a-linked-list/README.md new file mode 100644 index 00000000..57ca97b0 --- /dev/null +++ b/2816-double-a-number-represented-as-a-linked-list/README.md @@ -0,0 +1,28 @@ +

2816. Double a Number Represented as a Linked List

Medium


You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.

+ +

Return the head of the linked list after doubling it.

+ +

 

+

Example 1:

+ +
Input: head = [1,8,9]
+Output: [3,7,8]
+Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
+
+ +

Example 2:

+ +
Input: head = [9,9,9]
+Output: [1,9,9,8]
+Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998. 
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 104]
  • +
  • 0 <= Node.val <= 9
  • +
  • The input is generated such that the list represents a number that does not have leading zeros, except the number 0 itself.
  • +
+
\ No newline at end of file diff --git a/2833-furthest-point-from-origin/2833-furthest-point-from-origin.cpp b/2833-furthest-point-from-origin/2833-furthest-point-from-origin.cpp new file mode 100644 index 00000000..e428fcc0 --- /dev/null +++ b/2833-furthest-point-from-origin/2833-furthest-point-from-origin.cpp @@ -0,0 +1,39 @@ +class Solution { + +private: + int helper(int idx, int currMove, string& moves, vector>& dp) + { + if(idx == moves.size()) + return currMove; + + if(dp[idx][currMove+51] != -1) + return dp[idx][currMove+51]; + + int first = INT_MIN, second = INT_MIN, both = INT_MIN; + + if(moves[idx] == 'L') + first = abs(helper(idx+1, currMove - 1 ,moves, dp)); + if(moves[idx] == 'R') + second = abs(helper(idx+1, currMove + 1, moves, dp)); + + if(moves[idx] == '_') + both = max(abs(helper(idx+1, currMove + 1, moves, dp)) , abs(helper(idx+1,currMove - 1, moves, dp))); + + return dp[idx][currMove+51] = max({first, second, both}); + } + + // "_R__LL_" + +public: + int furthestDistanceFromOrigin(string moves) { + + int n = moves.size(); + + vector> dp(n+1, vector(n+51, -1)); + + int ans = helper(0, 0,moves, dp); + + return ans; + + } +}; \ No newline at end of file diff --git a/2833-furthest-point-from-origin/NOTES.md b/2833-furthest-point-from-origin/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2833-furthest-point-from-origin/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2842-count-k-subsequences-of-a-string-with-maximum-beauty/2842-count-k-subsequences-of-a-string-with-maximum-beauty.cpp b/2842-count-k-subsequences-of-a-string-with-maximum-beauty/2842-count-k-subsequences-of-a-string-with-maximum-beauty.cpp new file mode 100644 index 00000000..fe1b1734 --- /dev/null +++ b/2842-count-k-subsequences-of-a-string-with-maximum-beauty/2842-count-k-subsequences-of-a-string-with-maximum-beauty.cpp @@ -0,0 +1,88 @@ +class Solution { + +public: + + const int mod = 1e9 + 7; + + long long minv(long long x, long long y) + { + long long res = 1; + + while(y > 0) + { + if(y & 1) + res = (res*x)%mod; + + x = (x*x) % mod; + + y >>= 1; + } + + return (int)res; + } + + long long calculate(int n, int r) + { + long long res = 1; + + for(int i = 1; i <= n; ++i) + { + res *= i; + res %= mod; + } + + for(int i = 1; i <= r; ++i) + { + res *= minv(i, mod-2); + res %= mod; + } + + for(int i = 1; i <= (n-r); ++i) + { + res *= minv(i, mod-2); + res %= mod; + } + + return (int)res; + } + + + + int countKSubsequencesWithMaxBeauty(string s, int k) { + + if(k > 26) + return 0; + + vector v(26,0); + + for(auto& itr : s) + ++v[itr - 'a']; + + sort(v.rbegin(),v.rend()); + + long long res = 1, req = 0; + + for(int i = 0; i < k; ++i) + { + res *= v[i]; + res %= mod; + if(v[i] == v[k-1]) + ++req; + } + + int f = 0; + + for(int i = 0; i < 26; ++i) + { + if(v[i] == v[k-1]) + ++f; + } + + res *= calculate(f, req); + + res %= mod; + + return (int)res; + + } +}; \ No newline at end of file diff --git a/2842-count-k-subsequences-of-a-string-with-maximum-beauty/README.md b/2842-count-k-subsequences-of-a-string-with-maximum-beauty/README.md new file mode 100644 index 00000000..3cb52c69 --- /dev/null +++ b/2842-count-k-subsequences-of-a-string-with-maximum-beauty/README.md @@ -0,0 +1,69 @@ +

2842. Count K-Subsequences of a String With Maximum Beauty

Hard


You are given a string s and an integer k.

+ +

A k-subsequence is a subsequence of s, having length k, and all its characters are unique, i.e., every character occurs once.

+ +

Let f(c) denote the number of times the character c occurs in s.

+ +

The beauty of a k-subsequence is the sum of f(c) for every character c in the k-subsequence.

+ +

For example, consider s = "abbbdd" and k = 2:

+ +
    +
  • f('a') = 1, f('b') = 3, f('d') = 2
  • +
  • Some k-subsequences of s are: +
      +
    • "abbbdd" -> "ab" having a beauty of f('a') + f('b') = 4
    • +
    • "abbbdd" -> "ad" having a beauty of f('a') + f('d') = 3
    • +
    • "abbbdd" -> "bd" having a beauty of f('b') + f('d') = 5
    • +
    +
  • +
+ +

Return an integer denoting the number of k-subsequences whose beauty is the maximum among all k-subsequences. Since the answer may be too large, return it modulo 109 + 7.

+ +

A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.

+ +

Notes

+ +
    +
  • f(c) is the number of times a character c occurs in s, not a k-subsequence.
  • +
  • Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.
  • +
+ +

 

+

Example 1:

+ +
Input: s = "bcca", k = 2
+Output: 4
+Explanation: From s we have f('a') = 1, f('b') = 1, and f('c') = 2.
+The k-subsequences of s are: 
+bcca having a beauty of f('b') + f('c') = 3 
+bcca having a beauty of f('b') + f('c') = 3 
+bcca having a beauty of f('b') + f('a') = 2 
+bcca having a beauty of f('c') + f('a') = 3
+bcca having a beauty of f('c') + f('a') = 3 
+There are 4 k-subsequences that have the maximum beauty, 3. 
+Hence, the answer is 4. 
+
+ +

Example 2:

+ +
Input: s = "abbcd", k = 4
+Output: 2
+Explanation: From s we have f('a') = 1, f('b') = 2, f('c') = 1, and f('d') = 1. 
+The k-subsequences of s are: 
+abbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5
+abbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5 
+There are 2 k-subsequences that have the maximum beauty, 5. 
+Hence, the answer is 2. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2 * 105
  • +
  • 1 <= k <= s.length
  • +
  • s consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2845-count-of-interesting-subarrays/2845-count-of-interesting-subarrays.cpp b/2845-count-of-interesting-subarrays/2845-count-of-interesting-subarrays.cpp new file mode 100644 index 00000000..54fd4eda --- /dev/null +++ b/2845-count-of-interesting-subarrays/2845-count-of-interesting-subarrays.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long countInterestingSubarrays(vector& nums, int modulo, int k) { + + unordered_map mp; + + mp.insert({0, 1}); + + long long prefix = 0, counter = 0; + + for(auto& itr : nums) + { + prefix = (prefix + (itr % modulo == k ? 1 : 0))%modulo; + + int need = (((prefix - k)% modulo) + modulo) % modulo; + + if(mp.find(need) != mp.end()) + counter += mp[need]; + + ++mp[prefix]; + } + + return counter; + } +}; \ No newline at end of file diff --git a/2845-count-of-interesting-subarrays/README.md b/2845-count-of-interesting-subarrays/README.md new file mode 100644 index 00000000..f5d2311e --- /dev/null +++ b/2845-count-of-interesting-subarrays/README.md @@ -0,0 +1,54 @@ +

2845. Count of Interesting Subarrays

Medium


You are given a 0-indexed integer array nums, an integer modulo, and an integer k.

+ +

Your task is to find the count of subarrays that are interesting.

+ +

A subarray nums[l..r] is interesting if the following condition holds:

+ +
    +
  • Let cnt be the number of indices i in the range [l, r] such that nums[i] % modulo == k. Then, cnt % modulo == k.
  • +
+ +

Return an integer denoting the count of interesting subarrays.

+ +

Note: A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [3,2,4], modulo = 2, k = 1
+Output: 3
+Explanation: In this example the interesting subarrays are: 
+The subarray nums[0..0] which is [3]. 
+- There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. 
+- Hence, cnt = 1 and cnt % modulo == k.  
+The subarray nums[0..1] which is [3,2].
+- There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k.  
+- Hence, cnt = 1 and cnt % modulo == k.
+The subarray nums[0..2] which is [3,2,4]. 
+- There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. 
+- Hence, cnt = 1 and cnt % modulo == k. 
+It can be shown that there are no other interesting subarrays. So, the answer is 3.
+ +

Example 2:

+ +
Input: nums = [3,1,9,6], modulo = 3, k = 0
+Output: 2
+Explanation: In this example the interesting subarrays are: 
+The subarray nums[0..3] which is [3,1,9,6]. 
+- There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. 
+- Hence, cnt = 3 and cnt % modulo == k. 
+The subarray nums[1..1] which is [1]. 
+- There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. 
+- Hence, cnt = 0 and cnt % modulo == k. 
+It can be shown that there are no other interesting subarrays. So, the answer is 2.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= modulo <= 109
  • +
  • 0 <= k < modulo
  • +
+
\ No newline at end of file diff --git a/2849-determine-if-a-cell-is-reachable-at-a-given-time/2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp b/2849-determine-if-a-cell-is-reachable-at-a-given-time/2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp new file mode 100644 index 00000000..e87e582f --- /dev/null +++ b/2849-determine-if-a-cell-is-reachable-at-a-given-time/2849-determine-if-a-cell-is-reachable-at-a-given-time.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isReachableAtTime(int sx, int sy, int fx, int fy, int t) { + + int xDiff = abs(sx - fx); + int yDiff = abs(sy - fy); + + int diagonalDist = min(xDiff, yDiff); + + if(sx == fx and sy == fy and t == 1) + return false; + + int minDist = diagonalDist + abs(xDiff - yDiff); + + return minDist <= t; + } +}; \ No newline at end of file diff --git a/2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md b/2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2849-determine-if-a-cell-is-reachable-at-a-given-time/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md b/2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md new file mode 100644 index 00000000..b806424d --- /dev/null +++ b/2849-determine-if-a-cell-is-reachable-at-a-given-time/README.md @@ -0,0 +1,31 @@ +

2849. Determine if a Cell Is Reachable at a Given Time

Medium


You are given four integers sx, sy, fx, fy, and a non-negative integer t.

+ +

In an infinite 2D grid, you start at the cell (sx, sy). Each second, you must move to any of its adjacent cells.

+ +

Return true if you can reach cell (fx, fy) after exactly t seconds, or false otherwise.

+ +

A cell's adjacent cells are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.

+ +

 

+

Example 1:

+ +
Input: sx = 2, sy = 4, fx = 7, fy = 7, t = 6
+Output: true
+Explanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. 
+
+ +

Example 2:

+ +
Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3
+Output: false
+Explanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= sx, sy, fx, fy <= 109
  • +
  • 0 <= t <= 109
  • +
+
\ No newline at end of file diff --git a/2864-maximum-odd-binary-number/2864-maximum-odd-binary-number.cpp b/2864-maximum-odd-binary-number/2864-maximum-odd-binary-number.cpp new file mode 100644 index 00000000..949cc660 --- /dev/null +++ b/2864-maximum-odd-binary-number/2864-maximum-odd-binary-number.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string maximumOddBinaryNumber(string s) { + + int n = s.size(); + int start = 0, end = n-1; + + while(start <= end) + { + if(s[start] == '1') + ++start; + else if(s[end] == '1') + { + swap(s[start], s[end]); + --end; + ++start; + } + else + --end; + } + swap(s[start-1], s[n-1]); + + return s; + + } +}; \ No newline at end of file diff --git a/2864-maximum-odd-binary-number/NOTES.md b/2864-maximum-odd-binary-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2864-maximum-odd-binary-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2864-maximum-odd-binary-number/README.md b/2864-maximum-odd-binary-number/README.md new file mode 100644 index 00000000..598ac213 --- /dev/null +++ b/2864-maximum-odd-binary-number/README.md @@ -0,0 +1,32 @@ +

2864. Maximum Odd Binary Number

Easy


You are given a binary string s that contains at least one '1'.

+ +

You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.

+ +

Return a string representing the maximum odd binary number that can be created from the given combination.

+ +

Note that the resulting string can have leading zeros.

+ +

 

+

Example 1:

+ +
Input: s = "010"
+Output: "001"
+Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".
+
+ +

Example 2:

+ +
Input: s = "0101"
+Output: "1001"
+Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s consists only of '0' and '1'.
  • +
  • s contains at least one '1'.
  • +
+
\ No newline at end of file diff --git a/2870-minimum-number-of-operations-to-make-array-empty/2870-minimum-number-of-operations-to-make-array-empty.cpp b/2870-minimum-number-of-operations-to-make-array-empty/2870-minimum-number-of-operations-to-make-array-empty.cpp new file mode 100644 index 00000000..f86d744f --- /dev/null +++ b/2870-minimum-number-of-operations-to-make-array-empty/2870-minimum-number-of-operations-to-make-array-empty.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minOperations(vector& nums) { + + map mp; + + for(auto& itr : nums) + ++mp[itr]; + + int ans = 0; + + for(auto&[_, e] : mp) + { + if(e == 1) + return -1; + + if(e % 3 == 0) + ans += e/3; + else{ + ans += e/3; + ++ans; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/2870-minimum-number-of-operations-to-make-array-empty/README.md b/2870-minimum-number-of-operations-to-make-array-empty/README.md new file mode 100644 index 00000000..e32a8716 --- /dev/null +++ b/2870-minimum-number-of-operations-to-make-array-empty/README.md @@ -0,0 +1,39 @@ +

2870. Minimum Number of Operations to Make Array Empty

Medium


You are given a 0-indexed array nums consisting of positive integers.

+ +

There are two types of operations that you can apply on the array any number of times:

+ +
    +
  • Choose two elements with equal values and delete them from the array.
  • +
  • Choose three elements with equal values and delete them from the array.
  • +
+ +

Return the minimum number of operations required to make the array empty, or -1 if it is not possible.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,3,2,2,4,2,3,4]
+Output: 4
+Explanation: We can apply the following operations to make the array empty:
+- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4].
+- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4].
+- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4].
+- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = [].
+It can be shown that we cannot make the array empty in less than 4 operations.
+
+ +

Example 2:

+ +
Input: nums = [2,1,2,2,3,3]
+Output: -1
+Explanation: It is impossible to empty the array.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 106
  • +
+
\ No newline at end of file diff --git a/2919-minimum-increment-operations-to-make-array-beautiful/README.md b/2919-minimum-increment-operations-to-make-array-beautiful/README.md new file mode 100644 index 00000000..ea73772b --- /dev/null +++ b/2919-minimum-increment-operations-to-make-array-beautiful/README.md @@ -0,0 +1,60 @@ +

2919. Minimum Increment Operations to Make Array Beautiful

Medium


You are given a 0-indexed integer array nums having length n, and an integer k.

+ +

You can perform the following increment operation any number of times (including zero):

+ +
    +
  • Choose an index i in the range [0, n - 1], and increase nums[i] by 1.
  • +
+ +

An array is considered beautiful if, for any subarray with a size of 3 or more, its maximum element is greater than or equal to k.

+ +

Return an integer denoting the minimum number of increment operations needed to make nums beautiful.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [2,3,0,0,2], k = 4
+Output: 3
+Explanation: We can perform the following increment operations to make nums beautiful:
+Choose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].
+Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].
+Choose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].
+The subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].
+In all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.
+It can be shown that nums cannot be made beautiful with fewer than 3 increment operations.
+Hence, the answer is 3.
+
+ +

Example 2:

+ +
Input: nums = [0,1,3,3], k = 5
+Output: 2
+Explanation: We can perform the following increment operations to make nums beautiful:
+Choose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].
+Choose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].
+The subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].
+In all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.
+It can be shown that nums cannot be made beautiful with fewer than 2 increment operations.
+Hence, the answer is 2.
+
+ +

Example 3:

+ +
Input: nums = [1,1,2], k = 1
+Output: 0
+Explanation: The only subarray with a size of 3 or more in this example is [1,1,2].
+The maximum element, 2, is already greater than k = 1, so we don't need any increment operation.
+Hence, the answer is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n == nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
  • 0 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/2949-count-beautiful-substrings-ii/2949-count-beautiful-substrings-ii.cpp b/2949-count-beautiful-substrings-ii/2949-count-beautiful-substrings-ii.cpp new file mode 100644 index 00000000..53c005cb --- /dev/null +++ b/2949-count-beautiful-substrings-ii/2949-count-beautiful-substrings-ii.cpp @@ -0,0 +1,42 @@ +#define ll long long + +class Solution { +public: + long long beautifulSubstrings(string s, int k) { + + int n = s.size(); + + function isVowel = [&](char ch) + { + return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'); + }; + + unordered_map > mp; + + ll ans = 0; + + ++mp[0][0]; + + ll pref = 0, vow = 0; + + for(int i = 0; i < n; ++i) + { + if(isVowel(s[i])) + ++pref, ++vow; + else + --pref; + + for(auto& [f, cnt] : mp[pref]) + { + ll curr = (vow%k) - f; + if((curr * curr) % k == 0) + ans += cnt; + } + + ++mp[pref][vow%k]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/2949-count-beautiful-substrings-ii/NOTES.md b/2949-count-beautiful-substrings-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2949-count-beautiful-substrings-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2958-length-of-longest-subarray-with-at-most-k-frequency/2958-length-of-longest-subarray-with-at-most-k-frequency.cpp b/2958-length-of-longest-subarray-with-at-most-k-frequency/2958-length-of-longest-subarray-with-at-most-k-frequency.cpp new file mode 100644 index 00000000..46200095 --- /dev/null +++ b/2958-length-of-longest-subarray-with-at-most-k-frequency/2958-length-of-longest-subarray-with-at-most-k-frequency.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) { + + int i = 0, j = 0, n = nums.size(); + + int ans = 0; + + map mp; + + while(j < n) + { + ++mp[nums[j]]; + + while(mp[nums[j]] > k) + { + --mp[nums[i]]; + if(mp[nums[i]] == 0) + mp.erase(nums[i]); + ++i; + } + + ans = max(ans, j-i+1); + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2958-length-of-longest-subarray-with-at-most-k-frequency/NOTES.md b/2958-length-of-longest-subarray-with-at-most-k-frequency/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2958-length-of-longest-subarray-with-at-most-k-frequency/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2958-length-of-longest-subarray-with-at-most-k-frequency/README.md b/2958-length-of-longest-subarray-with-at-most-k-frequency/README.md new file mode 100644 index 00000000..768756e8 --- /dev/null +++ b/2958-length-of-longest-subarray-with-at-most-k-frequency/README.md @@ -0,0 +1,44 @@ +

2958. Length of Longest Subarray With at Most K Frequency

Medium


You are given an integer array nums and an integer k.

+ +

The frequency of an element x is the number of times it occurs in an array.

+ +

An array is called good if the frequency of each element in this array is less than or equal to k.

+ +

Return the length of the longest good subarray of nums.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,1,2,3,1,2], k = 2
+Output: 6
+Explanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good.
+It can be shown that there are no good subarrays with length more than 6.
+
+ +

Example 2:

+ +
Input: nums = [1,2,1,2,1,2,1,2], k = 1
+Output: 2
+Explanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good.
+It can be shown that there are no good subarrays with length more than 2.
+
+ +

Example 3:

+ +
Input: nums = [5,5,5,5,5,5,5], k = 4
+Output: 4
+Explanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray.
+It can be shown that there are no good subarrays with length more than 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/2962-count-subarrays-where-max-element-appears-at-least-k-times/2962-count-subarrays-where-max-element-appears-at-least-k-times.cpp b/2962-count-subarrays-where-max-element-appears-at-least-k-times/2962-count-subarrays-where-max-element-appears-at-least-k-times.cpp new file mode 100644 index 00000000..f4926b3b --- /dev/null +++ b/2962-count-subarrays-where-max-element-appears-at-least-k-times/2962-count-subarrays-where-max-element-appears-at-least-k-times.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + long long countSubarrays(vector& nums, int k) { + + int maxElement = *max_element(nums.begin(), nums.end()); + + int i = 0, j = 0, n = nums.size(); + + long long cnt = 0, ans = 0; + + while(j < n) + { + if(nums[j] == maxElement) + ++cnt; + + while(cnt >= k) + { + ans += (n-j); + if(nums[i] == maxElement) + --cnt; + ++i; + } + ++j; + } + + return ans; + } +}; \ No newline at end of file diff --git a/2962-count-subarrays-where-max-element-appears-at-least-k-times/NOTES.md b/2962-count-subarrays-where-max-element-appears-at-least-k-times/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2962-count-subarrays-where-max-element-appears-at-least-k-times/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2962-count-subarrays-where-max-element-appears-at-least-k-times/README.md b/2962-count-subarrays-where-max-element-appears-at-least-k-times/README.md new file mode 100644 index 00000000..499c8675 --- /dev/null +++ b/2962-count-subarrays-where-max-element-appears-at-least-k-times/README.md @@ -0,0 +1,30 @@ +

2962. Count Subarrays Where Max Element Appears at Least K Times

Medium


You are given an integer array nums and a positive integer k.

+ +

Return the number of subarrays where the maximum element of nums appears at least k times in that subarray.

+ +

A subarray is a contiguous sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,2,3,3], k = 2
+Output: 6
+Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
+
+ +

Example 2:

+ +
Input: nums = [1,4,2,1], k = 3
+Output: 0
+Explanation: No subarray contains the element 4 at least 3 times.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 106
  • +
  • 1 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/2963-count-the-number-of-good-partitions/2963-count-the-number-of-good-partitions.cpp b/2963-count-the-number-of-good-partitions/2963-count-the-number-of-good-partitions.cpp new file mode 100644 index 00000000..70e9c842 --- /dev/null +++ b/2963-count-the-number-of-good-partitions/2963-count-the-number-of-good-partitions.cpp @@ -0,0 +1,52 @@ +#define ll long long + +class Solution { +public: + + const int mod = 1e9 + 7; + + ll expo(ll x, ll y, ll mod) + { + ll res = 1; + + while(y > 0) + { + if(y & 1) + res = (res * x) % mod; + x = (x * x) % mod; + y >>= 1; + } + + return res; + } + + int numberOfGoodPartitions(vector& nums) { + + int n = nums.size(); + + int maxGotSoFar = 0; + + unordered_map mp; + + for(int i = 0; i < n; ++i) + { + mp[nums[i]] = i; + } + + int nonOverLappingPartitions = 0; + + for(int i = 0; i < n; ++i) + { + maxGotSoFar = max(maxGotSoFar, mp[nums[i]]); + + if(mp[nums[i]] == i and maxGotSoFar == i) + { + ++nonOverLappingPartitions; + } + + } + + return expo(2, nonOverLappingPartitions - 1, mod); + + } +}; \ No newline at end of file diff --git a/2963-count-the-number-of-good-partitions/NOTES.md b/2963-count-the-number-of-good-partitions/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2963-count-the-number-of-good-partitions/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2963-count-the-number-of-good-partitions/README.md b/2963-count-the-number-of-good-partitions/README.md new file mode 100644 index 00000000..057c9ef1 --- /dev/null +++ b/2963-count-the-number-of-good-partitions/README.md @@ -0,0 +1,38 @@ +

2963. Count the Number of Good Partitions

Hard


You are given a 0-indexed array nums consisting of positive integers.

+ +

A partition of an array into one or more contiguous subarrays is called good if no two subarrays contain the same number.

+ +

Return the total number of good partitions of nums.

+ +

Since the answer may be large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: 8
+Explanation: The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]).
+
+ +

Example 2:

+ +
Input: nums = [1,1,1,1]
+Output: 1
+Explanation: The only possible good partition is: ([1,1,1,1]).
+
+ +

Example 3:

+ +
Input: nums = [1,2,1,3]
+Output: 2
+Explanation: The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2966-divide-array-into-arrays-with-max-difference/2966-divide-array-into-arrays-with-max-difference.cpp b/2966-divide-array-into-arrays-with-max-difference/2966-divide-array-into-arrays-with-max-difference.cpp new file mode 100644 index 00000000..0353e6b5 --- /dev/null +++ b/2966-divide-array-into-arrays-with-max-difference/2966-divide-array-into-arrays-with-max-difference.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector> divideArray(vector& nums, int k) { + + int n = nums.size(); + + if(n < 3) + return {}; + + vector> output; + + sort(nums.begin(), nums.end()); + + int part = n/3; + + for(int i = 0; i < n-2; i += 3) + { + vector curr; + + if(nums[i+1] - nums[i] <= k and nums[i+2] - nums[i+1] <= k and nums[i+2] - nums[i] <= k) + { + curr.push_back(nums[i]); + curr.push_back(nums[i+1]); + curr.push_back(nums[i+2]); + } + + if(!curr.empty()) + output.push_back(curr); + } + + if((int)output.size() != part) + return {}; + return output; + } +}; \ No newline at end of file diff --git a/2966-divide-array-into-arrays-with-max-difference/NOTES.md b/2966-divide-array-into-arrays-with-max-difference/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2966-divide-array-into-arrays-with-max-difference/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2966-divide-array-into-arrays-with-max-difference/README.md b/2966-divide-array-into-arrays-with-max-difference/README.md new file mode 100644 index 00000000..8e0024aa --- /dev/null +++ b/2966-divide-array-into-arrays-with-max-difference/README.md @@ -0,0 +1,39 @@ +

2966. Divide Array Into Arrays With Max Difference

Medium


You are given an integer array nums of size n and a positive integer k.

+ +

Divide the array into one or more arrays of size 3 satisfying the following conditions:

+ +
    +
  • Each element of nums should be in exactly one array.
  • +
  • The difference between any two elements in one array is less than or equal to k.
  • +
+ +

Return a 2D array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,8,7,9,3,5,1], k = 2
+Output: [[1,1,3],[3,4,5],[7,8,9]]
+Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9].
+The difference between any two elements in each array is less than or equal to 2.
+Note that the order of elements is not important.
+
+ +

Example 2:

+ +
Input: nums = [1,3,3,2,7,3], k = 3
+Output: []
+Explanation: It is not possible to divide the array satisfying all the conditions.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • n is a multiple of 3.
  • +
  • 1 <= nums[i] <= 105
  • +
  • 1 <= k <= 105
  • +
+
\ No newline at end of file diff --git a/2971-find-polygon-with-the-largest-perimeter/2971-find-polygon-with-the-largest-perimeter.cpp b/2971-find-polygon-with-the-largest-perimeter/2971-find-polygon-with-the-largest-perimeter.cpp new file mode 100644 index 00000000..7acb465d --- /dev/null +++ b/2971-find-polygon-with-the-largest-perimeter/2971-find-polygon-with-the-largest-perimeter.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long largestPerimeter(vector& nums) { + + int n = nums.size(); + + sort(nums.begin(), nums.end()); + + vector pref(n, 0); + + pref[0] = nums[0]; + + for(int i = 1; i < n; ++i) + pref[i] = (pref[i-1] + nums[i]); + + for(int i = n-2; i >= 1; --i) + { + if(pref[i] > (pref[i+1] - pref[i])) + return pref[i+1]; + } + + return -1; + + } +}; \ No newline at end of file diff --git a/2971-find-polygon-with-the-largest-perimeter/NOTES.md b/2971-find-polygon-with-the-largest-perimeter/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2971-find-polygon-with-the-largest-perimeter/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2971-find-polygon-with-the-largest-perimeter/README.md b/2971-find-polygon-with-the-largest-perimeter/README.md new file mode 100644 index 00000000..c7d742d1 --- /dev/null +++ b/2971-find-polygon-with-the-largest-perimeter/README.md @@ -0,0 +1,42 @@ +

2971. Find Polygon With the Largest Perimeter

Medium


You are given an array of positive integers nums of length n.

+ +

A polygon is a closed plane figure that has at least 3 sides. The longest side of a polygon is smaller than the sum of its other sides.

+ +

Conversely, if you have k (k >= 3) positive real numbers a1, a2, a3, ..., ak where a1 <= a2 <= a3 <= ... <= ak and a1 + a2 + a3 + ... + ak-1 > ak, then there always exists a polygon with k sides whose lengths are a1, a2, a3, ..., ak.

+ +

The perimeter of a polygon is the sum of lengths of its sides.

+ +

Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1 if it is not possible to create a polygon.

+ +

 

+

Example 1:

+ +
Input: nums = [5,5,5]
+Output: 15
+Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.
+
+ +

Example 2:

+ +
Input: nums = [1,12,1,2,5,50,3]
+Output: 12
+Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12.
+We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them.
+It can be shown that the largest possible perimeter is 12.
+
+ +

Example 3:

+ +
Input: nums = [5,5,50]
+Output: -1
+Explanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= n <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/2976-minimum-cost-to-convert-string-i/2976-minimum-cost-to-convert-string-i.cpp b/2976-minimum-cost-to-convert-string-i/2976-minimum-cost-to-convert-string-i.cpp new file mode 100644 index 00000000..31ba790f --- /dev/null +++ b/2976-minimum-cost-to-convert-string-i/2976-minimum-cost-to-convert-string-i.cpp @@ -0,0 +1,41 @@ +using ll = long long; + +class Solution { +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) { + + vector> mat(26, vector(26, INT_MAX)); + + for(int i = 0; i < original.size(); ++i) + { + int a = original[i] - 'a'; + int b = changed[i] - 'a'; + mat[a][b] = min(mat[a][b], (ll)cost[i]); + } + + for(int k = 0; k < 26; ++k) + { + for(int i = 0; i < 26; ++i) + { + for(int j = 0; j < 26; ++j) + { + mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j]); + } + } + } + + ll ans = 0; + + for(int i = 0; i < source.size(); ++i) + { + if(source[i] != target[i]) + { + ll val = mat[source[i]-'a'][target[i]-'a']; + if(val >= INT_MAX) return -1; + ans += val; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/2976-minimum-cost-to-convert-string-i/README.md b/2976-minimum-cost-to-convert-string-i/README.md new file mode 100644 index 00000000..cc8d73c0 --- /dev/null +++ b/2976-minimum-cost-to-convert-string-i/README.md @@ -0,0 +1,48 @@ +

2976. Minimum Cost to Convert String I

Medium


You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arrays original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].

+ +

You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.

+ +

Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.

+ +

Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].

+ +

 

+

Example 1:

+ +
Input: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]
+Output: 28
+Explanation: To convert the string "abcd" to string "acbe":
+- Change value at index 1 from 'b' to 'c' at a cost of 5.
+- Change value at index 2 from 'c' to 'e' at a cost of 1.
+- Change value at index 2 from 'e' to 'b' at a cost of 2.
+- Change value at index 3 from 'd' to 'e' at a cost of 20.
+The total cost incurred is 5 + 1 + 2 + 20 = 28.
+It can be shown that this is the minimum possible cost.
+
+ +

Example 2:

+ +
Input: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2]
+Output: 12
+Explanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred.
+
+ +

Example 3:

+ +
Input: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000]
+Output: -1
+Explanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= source.length == target.length <= 105
  • +
  • source, target consist of lowercase English letters.
  • +
  • 1 <= cost.length == original.length == changed.length <= 2000
  • +
  • original[i], changed[i] are lowercase English letters.
  • +
  • 1 <= cost[i] <= 106
  • +
  • original[i] != changed[i]
  • +
+
\ No newline at end of file diff --git a/2982-find-longest-special-substring-that-occurs-thrice-ii/2982-find-longest-special-substring-that-occurs-thrice-ii.cpp b/2982-find-longest-special-substring-that-occurs-thrice-ii/2982-find-longest-special-substring-that-occurs-thrice-ii.cpp new file mode 100644 index 00000000..aa1bf6d7 --- /dev/null +++ b/2982-find-longest-special-substring-that-occurs-thrice-ii/2982-find-longest-special-substring-that-occurs-thrice-ii.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + int maximumLength(string str) { + + unordered_map mp, mp2, mp3; + + map, int> mp4; + + vector freq(26, 0); + + int n = str.size(); + + int ans = -1; + + for(int i = 0; i < n; ++i) + { + ++mp[str[i]]; + if(mp[str[i]] >= 3) + ans = 1; + } + + if(ans == -1) + return ans; + + int cnt = 1; + mp[str[0]] = 1; + for(int i = 1; i < n; ++i) + { + if(str[i] == str[i-1]) + { + ++cnt; + // int al = mp[str[i]]; + mp2[str[i]] = max(mp2[str[i]], cnt); + int have = mp2[str[i]]; + if(cnt < have) + { + if(cnt == have-1) + { + mp3[str[i]] = max(mp3[str[i]], cnt); + } + } + + ++mp4[{str[i], cnt}]; + if(mp4[{str[i], cnt}] >= 3) + freq[str[i]-'a'] = max(freq[str[i]-'a'],cnt); + } + else + { + cnt = 1; + mp2[str[i]] = max(mp2[str[i]], cnt); + } + } + for(auto& [f, e] : mp2) + { + // cout<= 3) + { + // cout<= 3) + // { + // ans = max(ans, itr.first.second); + // } + // } + + for(auto& itr : freq) + ans = max(ans, itr); + + return ans; + } +}; \ No newline at end of file diff --git a/2982-find-longest-special-substring-that-occurs-thrice-ii/README.md b/2982-find-longest-special-substring-that-occurs-thrice-ii/README.md new file mode 100644 index 00000000..2a1c8241 --- /dev/null +++ b/2982-find-longest-special-substring-that-occurs-thrice-ii/README.md @@ -0,0 +1,40 @@ +

2982. Find Longest Special Substring That Occurs Thrice II

Medium


You are given a string s that consists of lowercase English letters.

+ +

A string is called special if it is made up of only a single character. For example, the string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.

+ +

Return the length of the longest special substring of s which occurs at least thrice, or -1 if no special substring occurs at least thrice.

+ +

A substring is a contiguous non-empty sequence of characters within a string.

+ +

 

+

Example 1:

+ +
Input: s = "aaaa"
+Output: 2
+Explanation: The longest special substring which occurs thrice is "aa": substrings "aaaa", "aaaa", and "aaaa".
+It can be shown that the maximum length achievable is 2.
+
+ +

Example 2:

+ +
Input: s = "abcdef"
+Output: -1
+Explanation: There exists no special substring which occurs at least thrice. Hence return -1.
+
+ +

Example 3:

+ +
Input: s = "abcaba"
+Output: 1
+Explanation: The longest special substring which occurs thrice is "a": substrings "abcaba", "abcaba", and "abcaba".
+It can be shown that the maximum length achievable is 1.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= s.length <= 5 * 105
  • +
  • s consists of only lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.cpp b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.cpp new file mode 100644 index 00000000..2c31aa57 --- /dev/null +++ b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minOperations(vector& nums, int k) { + + int n = nums.size(); + + vector bits(32, 0); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < 32; ++j) + { + if(nums[i] & (1 << j)) + ++bits[j]; + } + } + + int op = 0; + + for(int i = 0; i < 32; ++i) + { + if(k & (1 << i)) + { + if(bits[i] % 2 == 0) + ++op; + } + else + { + if(bits[i] & 1) + ++op; + } + } + + return op; + + } +}; \ No newline at end of file diff --git a/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/NOTES.md b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/README.md b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/README.md new file mode 100644 index 00000000..8da44784 --- /dev/null +++ b/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k/README.md @@ -0,0 +1,40 @@ +

2997. Minimum Number of Operations to Make Array XOR Equal to K

Medium


You are given a 0-indexed integer array nums and a positive integer k.

+ +

You can apply the following operation on the array any number of times:

+ +
    +
  • Choose any element of the array and flip a bit in its binary representation. Flipping a bit means changing a 0 to 1 or vice versa.
  • +
+ +

Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.

+ +

Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2.

+ +

 

+

Example 1:

+ +
Input: nums = [2,1,3,4], k = 1
+Output: 2
+Explanation: We can do the following operations:
+- Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4].
+- Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4].
+The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
+It can be shown that we cannot make the XOR equal to k in less than 2 operations.
+
+ +

Example 2:

+ +
Input: nums = [2,0,2,0], k = 0
+Output: 0
+Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 106
  • +
  • 0 <= k <= 106
  • +
+
\ No newline at end of file diff --git a/3005-count-elements-with-maximum-frequency/3005-count-elements-with-maximum-frequency.cpp b/3005-count-elements-with-maximum-frequency/3005-count-elements-with-maximum-frequency.cpp new file mode 100644 index 00000000..9b517485 --- /dev/null +++ b/3005-count-elements-with-maximum-frequency/3005-count-elements-with-maximum-frequency.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maxFrequencyElements(vector& nums) { + + int n = nums.size(); + + vector freq(101, 0); + + int sameFrequencyNum = 0, maxi = 0; + + for(int i = 0; i < n; ++i) + { + ++freq[nums[i]]; + maxi = max(maxi, freq[nums[i]]); + } + + for(int i = 0; i < 101; ++i) + { + if(freq[i] == maxi) + sameFrequencyNum += freq[i]; + } + + return sameFrequencyNum; + } +}; \ No newline at end of file diff --git a/3005-count-elements-with-maximum-frequency/README.md b/3005-count-elements-with-maximum-frequency/README.md new file mode 100644 index 00000000..2b9d7d58 --- /dev/null +++ b/3005-count-elements-with-maximum-frequency/README.md @@ -0,0 +1,31 @@ +

3005. Count Elements With Maximum Frequency

Easy


You are given an array nums consisting of positive integers.

+ +

Return the total frequencies of elements in nums such that those elements all have the maximum frequency.

+ +

The frequency of an element is the number of occurrences of that element in the array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,2,3,1,4]
+Output: 4
+Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
+So the number of elements in the array with maximum frequency is 4.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5]
+Output: 5
+Explanation: All elements of the array have a frequency of 1 which is the maximum.
+So the number of elements in the array with maximum frequency is 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/3035-maximum-palindromes-after-operations/3035-maximum-palindromes-after-operations.cpp b/3035-maximum-palindromes-after-operations/3035-maximum-palindromes-after-operations.cpp new file mode 100644 index 00000000..da125d45 --- /dev/null +++ b/3035-maximum-palindromes-after-operations/3035-maximum-palindromes-after-operations.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maxPalindromesAfterOperations(vector& words) { + + vector length; + map mp; + + for(auto& word : words) + { + for(auto& ch : word) + ++mp[ch]; + length.push_back((int)word.size()/2); + } + + int matching = 0, cnt = 0; + + for(auto&[f, e] : mp) + matching += e/2; + + sort(length.begin(), length.end()); + + for(int i = 0; i < length.size(); ++i) + { + if(matching >= length[i]) + { + matching -= length[i]; + ++cnt; + } + } + + return cnt; + } +}; \ No newline at end of file diff --git a/3035-maximum-palindromes-after-operations/NOTES.md b/3035-maximum-palindromes-after-operations/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3035-maximum-palindromes-after-operations/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3035-maximum-palindromes-after-operations/README.md b/3035-maximum-palindromes-after-operations/README.md new file mode 100644 index 00000000..d4aba112 --- /dev/null +++ b/3035-maximum-palindromes-after-operations/README.md @@ -0,0 +1,51 @@ +

3035. Maximum Palindromes After Operations

Medium


You are given a 0-indexed string array words having length n and containing 0-indexed strings.

+ +

You are allowed to perform the following operation any number of times (including zero):

+ +
    +
  • Choose integers i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length, 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y].
  • +
+ +

Return an integer denoting the maximum number of palindromes words can contain, after performing some operations.

+ +

Note: i and j may be equal during an operation.

+ +

 

+

Example 1:

+ +
Input: words = ["abbb","ba","aa"]
+Output: 3
+Explanation: In this example, one way to get the maximum number of palindromes is:
+Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
+All strings in words are now palindromes.
+Hence, the maximum number of palindromes achievable is 3.
+ +

Example 2:

+ +
Input: words = ["abc","ab"]
+Output: 2
+Explanation: In this example, one way to get the maximum number of palindromes is: 
+Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
+Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
+Both strings are now palindromes.
+Hence, the maximum number of palindromes achievable is 2.
+
+ +

Example 3:

+ +
Input: words = ["cd","ef","a"]
+Output: 1
+Explanation: In this example, there is no need to perform any operation.
+There is one palindrome in words "a".
+It can be shown that it is not possible to get more than one palindrome after any number of operations.
+Hence, the answer is 1.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/3068-find-the-maximum-sum-of-node-values/3068-find-the-maximum-sum-of-node-values.cpp b/3068-find-the-maximum-sum-of-node-values/3068-find-the-maximum-sum-of-node-values.cpp new file mode 100644 index 00000000..704e11a4 --- /dev/null +++ b/3068-find-the-maximum-sum-of-node-values/3068-find-the-maximum-sum-of-node-values.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + long long maximumValueSum(vector& nums, int k, vector>& edges) { + + int mini = 1e9; + long long cnt = 0, ans = 0; + + for(auto& ele : nums) + { + int xorVal = ele ^ k; + + if(xorVal > ele) + { + ++cnt; + ans += xorVal; + } + else + { + ans += ele; + } + + mini = min(mini, abs(xorVal - ele)); + } + + if(cnt & 1) + { + return ans - mini; + } + return ans; + } +}; \ No newline at end of file diff --git a/3068-find-the-maximum-sum-of-node-values/NOTES.md b/3068-find-the-maximum-sum-of-node-values/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3068-find-the-maximum-sum-of-node-values/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3068-find-the-maximum-sum-of-node-values/README.md b/3068-find-the-maximum-sum-of-node-values/README.md new file mode 100644 index 00000000..f988eb9a --- /dev/null +++ b/3068-find-the-maximum-sum-of-node-values/README.md @@ -0,0 +1,57 @@ +

3068. Find the Maximum Sum of Node Values

Hard


There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 0-indexed 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree. You are also given a positive integer k, and a 0-indexed array of non-negative integers nums of length n, where nums[i] represents the value of the node numbered i.

+ +

Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree:

+ +
    +
  • Choose any edge [u, v] connecting the nodes u and v, and update their values as follows: + +
      +
    • nums[u] = nums[u] XOR k
    • +
    • nums[v] = nums[v] XOR k
    • +
    +
  • +
+ +

Return the maximum possible sum of the values Alice can achieve by performing the operation any number of times.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]
+Output: 6
+Explanation: Alice can achieve the maximum sum of 6 using a single operation:
+- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].
+The total sum of values is 2 + 2 + 2 = 6.
+It can be shown that 6 is the maximum achievable sum of values.
+
+ +

Example 2:

+ +
Input: nums = [2,3], k = 7, edges = [[0,1]]
+Output: 9
+Explanation: Alice can achieve the maximum sum of 9 using a single operation:
+- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].
+The total sum of values is 5 + 4 = 9.
+It can be shown that 9 is the maximum achievable sum of values.
+
+ +

Example 3:

+ +
Input: nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]
+Output: 42
+Explanation: The maximum achievable sum is 42 which can be achieved by Alice performing no operations.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n == nums.length <= 2 * 104
  • +
  • 1 <= k <= 109
  • +
  • 0 <= nums[i] <= 109
  • +
  • edges.length == n - 1
  • +
  • edges[i].length == 2
  • +
  • 0 <= edges[i][0], edges[i][1] <= n - 1
  • +
  • The input is generated such that edges represent a valid tree.
  • +
+
\ No newline at end of file diff --git a/3075-maximize-happiness-of-selected-children/3075-maximize-happiness-of-selected-children.cpp b/3075-maximize-happiness-of-selected-children/3075-maximize-happiness-of-selected-children.cpp new file mode 100644 index 00000000..23cbcd93 --- /dev/null +++ b/3075-maximize-happiness-of-selected-children/3075-maximize-happiness-of-selected-children.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + long long maximumHappinessSum(vector& happiness, int k) { + + int n = happiness.size(); + + sort(happiness.rbegin(), happiness.rend()); + + int cap = 0; + long long ans = 0; + + for(int i = 0; i < n, i < k; ++i, ++cap) + { + if(happiness[i] - cap > 0) + ans += (happiness[i] - cap); + } + + return ans; + } +}; \ No newline at end of file diff --git a/3075-maximize-happiness-of-selected-children/README.md b/3075-maximize-happiness-of-selected-children/README.md new file mode 100644 index 00000000..16567a73 --- /dev/null +++ b/3075-maximize-happiness-of-selected-children/README.md @@ -0,0 +1,47 @@ +

3075. Maximize Happiness of Selected Children

Medium


You are given an array happiness of length n, and a positive integer k.

+ +

There are n children standing in a queue, where the ith child has happiness value happiness[i]. You want to select k children from these n children in k turns.

+ +

In each turn, when you select a child, the happiness value of all the children that have not been selected till now decreases by 1. Note that the happiness value cannot become negative and gets decremented only if it is positive.

+ +

Return the maximum sum of the happiness values of the selected children you can achieve by selecting k children.

+ +

 

+

Example 1:

+ +
Input: happiness = [1,2,3], k = 2
+Output: 4
+Explanation: We can pick 2 children in the following way:
+- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].
+- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.
+The sum of the happiness values of the selected children is 3 + 1 = 4.
+
+ +

Example 2:

+ +
Input: happiness = [1,1,1,1], k = 2
+Output: 1
+Explanation: We can pick 2 children in the following way:
+- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].
+- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].
+The sum of the happiness values of the selected children is 1 + 0 = 1.
+
+ +

Example 3:

+ +
Input: happiness = [2,3,4,5], k = 1
+Output: 5
+Explanation: We can pick 1 child in the following way:
+- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].
+The sum of the happiness values of the selected children is 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n == happiness.length <= 2 * 105
  • +
  • 1 <= happiness[i] <= 108
  • +
  • 1 <= k <= n
  • +
+
\ No newline at end of file diff --git a/3093-longest-common-suffix-queries/3093-longest-common-suffix-queries.cpp b/3093-longest-common-suffix-queries/3093-longest-common-suffix-queries.cpp new file mode 100644 index 00000000..9e5a32b9 --- /dev/null +++ b/3093-longest-common-suffix-queries/3093-longest-common-suffix-queries.cpp @@ -0,0 +1,131 @@ +class Node{ + public: + Node* child[26] = {nullptr}; + pair p; + bool isWord; + + public: + + Node(){ + p.first = 1e9; + p.second = 1e9; + isWord = false; + } + bool containsKey(char ch) + { + return child[ch-'a'] != nullptr; + } + + void put(char ch, Node* node) + { + child[ch - 'a'] = node; + } + + Node* get(char ch) + { + return child[ch - 'a']; + } + + void setEnd() + { + isWord = true; + } + + void updateMin(int idx, int len) + { + if(len < p.second) + { + p.first = idx; + p.second = len; + } + else if(len == p.second) + p.first = min(p.first, idx); + } + + int getIdx() + { + return p.first; + } +}; + +class Trie{ + private: + Node* root; + + public: + Trie() + { + root = new Node(); + } + + void insert(string& word, int idx) + { + Node* temp = root; + + int n = word.size(); + + for(int i = 0; i < n; ++i) + { + char ch = word[i]; + temp->updateMin(idx, n); + if(!temp->containsKey(ch)) + { + temp->put(ch, new Node()); + + } + temp = temp->get(ch); + } + temp->updateMin(idx, n); + temp->setEnd(); + } + + int search(string& word) + { + Node* temp = root; + int n = word.size(); + int ansIdx = -1; + + for(int i = 0; i < n; ++i) + { + char ch = word[i]; + if(!temp->containsKey(ch)) + { + break; + } + ansIdx= temp->getIdx(); + temp = temp->get(ch); + } + + return temp->getIdx(); + } +}; + +class Solution { +public: + vector stringIndices(vector& wordsContainer, vector& wordsQuery) { + + Trie *trie = new Trie(); + + vector ans; + + int idx = 0, minLength = 1e9;; + for(auto& word : wordsContainer) + { + string rev = word; + reverse(rev.begin(), rev.end()); + minLength = min(minLength, (int)rev.size()); + trie->insert(rev, idx); + ++idx; + } + + for(auto& word : wordsQuery) + { + string rev = word; + reverse(rev.begin(), rev.end()); + int ansIdx = trie->search(rev); + ans.push_back(ansIdx); + } + + return ans; + } +}; \ No newline at end of file diff --git a/3093-longest-common-suffix-queries/README.md b/3093-longest-common-suffix-queries/README.md new file mode 100644 index 00000000..14bd5b40 --- /dev/null +++ b/3093-longest-common-suffix-queries/README.md @@ -0,0 +1,56 @@ +

3093. Longest Common Suffix Queries

Hard


You are given two arrays of strings wordsContainer and wordsQuery.

+ +

For each wordsQuery[i], you need to find a string from wordsContainer that has the longest common suffix with wordsQuery[i]. If there are two or more strings in wordsContainer that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer.

+ +

Return an array of integers ans, where ans[i] is the index of the string in wordsContainer that has the longest common suffix with wordsQuery[i].

+ +

 

+

Example 1:

+ +
+

Input: wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]

+ +

Output: [1,1,1]

+ +

Explanation:

+ +

Let's look at each wordsQuery[i] separately:

+ +
    +
  • For wordsQuery[0] = "cd", strings from wordsContainer that share the longest common suffix "cd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
  • +
  • For wordsQuery[1] = "bcd", strings from wordsContainer that share the longest common suffix "bcd" are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
  • +
  • For wordsQuery[2] = "xyz", there is no string from wordsContainer that shares a common suffix. Hence the longest common suffix is "", that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.
  • +
+
+ +

Example 2:

+ +
+

Input: wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]

+ +

Output: [2,0,2]

+ +

Explanation:

+ +

Let's look at each wordsQuery[i] separately:

+ +
    +
  • For wordsQuery[0] = "gh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.
  • +
  • For wordsQuery[1] = "acbfgh", only the string at index 0 shares the longest common suffix "fgh". Hence it is the answer, even though the string at index 2 is shorter.
  • +
  • For wordsQuery[2] = "acbfegh", strings from wordsContainer that share the longest common suffix "gh" are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.
  • +
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= wordsContainer.length, wordsQuery.length <= 104
  • +
  • 1 <= wordsContainer[i].length <= 5 * 103
  • +
  • 1 <= wordsQuery[i].length <= 5 * 103
  • +
  • wordsContainer[i] consists only of lowercase English letters.
  • +
  • wordsQuery[i] consists only of lowercase English letters.
  • +
  • Sum of wordsContainer[i].length is at most 5 * 105.
  • +
  • Sum of wordsQuery[i].length is at most 5 * 105.
  • +
+
\ No newline at end of file diff --git a/3108-minimum-cost-walk-in-weighted-graph/3108-minimum-cost-walk-in-weighted-graph.cpp b/3108-minimum-cost-walk-in-weighted-graph/3108-minimum-cost-walk-in-weighted-graph.cpp new file mode 100644 index 00000000..193b48fc --- /dev/null +++ b/3108-minimum-cost-walk-in-weighted-graph/3108-minimum-cost-walk-in-weighted-graph.cpp @@ -0,0 +1,112 @@ +class DSU{ + public: + int N; + vector parent, size; + + DSU(int n) + { + N = n; + parent.resize(N); + size.resize(N, 1); + + for(int i = 0; i < n; ++i) + parent[i] = i; + } + + int findParent(int u) + { + if(u == parent[u]) + { + return u; + } + return parent[u] = findParent(parent[u]); + } + + void unionBySize(int u, int v) + { + int parU = findParent(u); + int parV = findParent(v); + + if(parU == parV) + return; + + if(size[parU] < size[parV]) + { + parent[parU] = parV; + size[parV] += size[parU]; + } + else + { + parent[parV] = parU; + size[parU] += size[parV]; + } + } + + bool isSame(int u, int v) + { + return findParent(u) == findParent(v); + } +}; + +class Solution { +public: + + vector minimumCost(int n, vector>& edges, vector>& query) { + + vector ans; + + DSU dsu(n+1); + + vector bitAnd(n, -1); + + for(auto& edge : edges) + { + int u = edge[0]; + int v = edge[1]; + int wt = edge[2]; + + if(bitAnd[u] == -1) + bitAnd[u] = wt; + else + bitAnd[u] &= wt; + + if(bitAnd[v] == -1) + bitAnd[v] = wt; + else + bitAnd[v] &= wt; + + if(!dsu.isSame(u, v)) + { + dsu.unionBySize(u, v); + } + } + + map mp; + + for(int i = 0; i < n; ++i) + { + int ultPar = dsu.findParent(i); + if(bitAnd[ultPar] == -1) + continue; + if(mp.find(ultPar) == mp.end()) + mp[ultPar] = (bitAnd[i] & bitAnd[ultPar]); + else + mp[ultPar] &= bitAnd[i]; + } + + for(auto& q : query) + { + int u = q[0]; + int v = q[1]; + + if(u == v) + ans.push_back(0); + else if(dsu.isSame(u, v)) + ans.push_back(mp[dsu.findParent(u)]); + else + ans.push_back(-1); + } + + return ans; + } +}; \ No newline at end of file diff --git a/3108-minimum-cost-walk-in-weighted-graph/README.md b/3108-minimum-cost-walk-in-weighted-graph/README.md new file mode 100644 index 00000000..e48a0a2f --- /dev/null +++ b/3108-minimum-cost-walk-in-weighted-graph/README.md @@ -0,0 +1,54 @@ +

3108. Minimum Cost Walk in Weighted Graph

Hard


There is an undirected weighted graph with n vertices labeled from 0 to n - 1.

+ +

You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi.

+ +

A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.

+ +

The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator.

+ +

You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1.

+ +

Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.

+ +

 

+

Example 1:

+ +
+

Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]

+ +

Output: [1,-1]

+ +

Explanation:

+ +

To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7).

+ +

In the second query, there is no walk between nodes 3 and 4, so the answer is -1.

+ +

Example 2:

+
+ +
+

Input: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]

+ +

Output: [0]

+ +

Explanation:

+ +

To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1).

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • 0 <= edges.length <= 105
  • +
  • edges[i].length == 3
  • +
  • 0 <= ui, vi <= n - 1
  • +
  • ui != vi
  • +
  • 0 <= wi <= 105
  • +
  • 1 <= query.length <= 105
  • +
  • query[i].length == 2
  • +
  • 0 <= si, ti <= n - 1
  • +
+
\ No newline at end of file diff --git a/3110-score-of-a-string/3110-score-of-a-string.cpp b/3110-score-of-a-string/3110-score-of-a-string.cpp new file mode 100644 index 00000000..cbfc766d --- /dev/null +++ b/3110-score-of-a-string/3110-score-of-a-string.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int scoreOfString(string s) { + + int n = s.size(); + + int ans = 0; + + for(int i = 1; i < n; ++i) + { + ans += abs((s[i] - 'a') - (s[i-1] - 'a')); + } + + return ans; + } +}; \ No newline at end of file diff --git a/3110-score-of-a-string/README.md b/3110-score-of-a-string/README.md new file mode 100644 index 00000000..5859fc38 --- /dev/null +++ b/3110-score-of-a-string/README.md @@ -0,0 +1,37 @@ +

3110. Score of a String

Easy


You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.

+ +

Return the score of s.

+ +

 

+

Example 1:

+ +
+

Input: s = "hello"

+ +

Output: 13

+ +

Explanation:

+ +

The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.

+
+ +

Example 2:

+ +
+

Input: s = "zaz"

+ +

Output: 50

+ +

Explanation:

+ +

The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.

+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 100
  • +
  • s consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/3137-minimum-number-of-operations-to-make-word-k-periodic/3137-minimum-number-of-operations-to-make-word-k-periodic.cpp b/3137-minimum-number-of-operations-to-make-word-k-periodic/3137-minimum-number-of-operations-to-make-word-k-periodic.cpp new file mode 100644 index 00000000..dbb896c6 --- /dev/null +++ b/3137-minimum-number-of-operations-to-make-word-k-periodic/3137-minimum-number-of-operations-to-make-word-k-periodic.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minimumOperationsToMakeKPeriodic(string word, int k) { + + int n = word.size(); + + vector factors; + + for(int i = 0; i < n; ++i) + { + if(i == 0 or i % k == 0) + factors.push_back(i); + } + + map mp; + + int maxi = 0; + + for(auto& idx : factors) + { + string st = word.substr(idx, k); + ++mp[st]; + maxi = max(maxi, mp[st]); + } + + return (int)factors.size() - maxi; + } +}; \ No newline at end of file diff --git a/3137-minimum-number-of-operations-to-make-word-k-periodic/NOTES.md b/3137-minimum-number-of-operations-to-make-word-k-periodic/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3137-minimum-number-of-operations-to-make-word-k-periodic/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3137-minimum-number-of-operations-to-make-word-k-periodic/README.md b/3137-minimum-number-of-operations-to-make-word-k-periodic/README.md new file mode 100644 index 00000000..cc5c44d8 --- /dev/null +++ b/3137-minimum-number-of-operations-to-make-word-k-periodic/README.md @@ -0,0 +1,84 @@ +

3137. Minimum Number of Operations to Make Word K-Periodic

Medium


You are given a string word of size n, and an integer k such that k divides n.

+ +

In one operation, you can pick any two indices i and j, that are divisible by k, then replace the substring of length k starting at i with the substring of length k starting at j. That is, replace the substring word[i..i + k - 1] with the substring word[j..j + k - 1].

+ +

Return the minimum number of operations required to make word k-periodic.

+ +

We say that word is k-periodic if there is some string s of length k such that word can be obtained by concatenating s an arbitrary number of times. For example, if word == “ababab”, then word is 2-periodic for s = "ab".

+ +

 

+

Example 1:

+ +
+

Input: word = "leetcodeleet", k = 4

+ +

Output: 1

+ +

Explanation:

+ +

We can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".

+
+ +

Example 2:

+ +
+

Input: word = "leetcoleet", k = 2

+ +

Output: 3

+ +

Explanation:

+ +

We can obtain a 2-periodic string by applying the operations in the table below.

+ + + + + + + + + + + + + + + + + + + + + + + + +
ijword
02etetcoleet
40etetetleet
60etetetetet
+
+ +
+
 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n == word.length <= 105
  • +
  • 1 <= k <= word.length
  • +
  • k divides word.length.
  • +
  • word consists only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/3138-minimum-length-of-anagram-concatenation/3138-minimum-length-of-anagram-concatenation.cpp b/3138-minimum-length-of-anagram-concatenation/3138-minimum-length-of-anagram-concatenation.cpp new file mode 100644 index 00000000..083fb850 --- /dev/null +++ b/3138-minimum-length-of-anagram-concatenation/3138-minimum-length-of-anagram-concatenation.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minAnagramLength(string s) { + + int n = s.size(); + + map mp; + + for(auto&ch : s) + ++mp[ch]; + + int minFreq = INT_MAX; + + for(auto&[_, e] : mp) + minFreq = min(minFreq, e); + + int ans = n; + + for(int i = 1; i <= minFreq; ++i) + { + bool ok = true; + int len = 0; + + for(auto&[_, e] : mp) + { + ok &= (e % i == 0); + len += (e / i); + } + + if(ok) + { + ans = len; + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/3138-minimum-length-of-anagram-concatenation/NOTES.md b/3138-minimum-length-of-anagram-concatenation/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3138-minimum-length-of-anagram-concatenation/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3138-minimum-length-of-anagram-concatenation/README.md b/3138-minimum-length-of-anagram-concatenation/README.md new file mode 100644 index 00000000..5d4c31a9 --- /dev/null +++ b/3138-minimum-length-of-anagram-concatenation/README.md @@ -0,0 +1,39 @@ +

3138. Minimum Length of Anagram Concatenation

Medium


You are given a string s, which is known to be a concatenation of anagrams of some string t.

+ +

Return the minimum possible length of the string t.

+ +

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

+ +

 

+

Example 1:

+ +
+

Input: s = "abba"

+ +

Output: 2

+ +

Explanation:

+ +

One possible string t could be "ba".

+
+ +

Example 2:

+ +
+

Input: s = "cdef"

+ +

Output: 4

+ +

Explanation:

+ +

One possible string t could be "cdef", notice that t can be equal to s.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consist only of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/3139-minimum-cost-to-equalize-array/3139-minimum-cost-to-equalize-array.cpp b/3139-minimum-cost-to-equalize-array/3139-minimum-cost-to-equalize-array.cpp new file mode 100644 index 00000000..a3da90c1 --- /dev/null +++ b/3139-minimum-cost-to-equalize-array/3139-minimum-cost-to-equalize-array.cpp @@ -0,0 +1,52 @@ +using lli = long long; + +class Solution { +public: + int minCostToEqualizeArray(vector& nums, int cost1, int cost2) { + + int n = nums.size(); + + lli maxi = 0; + lli mini = 1e9; + lli ans = 1e18; + lli sum = 0; + const int mod = 1e9+7; + + for(auto& ele : nums) + { + maxi = max(maxi, 1LL * ele); + mini = min(mini, 1LL * ele); + sum += ele; + } + + for(int curMax = maxi; curMax <= 2 * maxi; ++curMax) + { + lli total = (n * 1LL* curMax) - sum; + lli curr = 0; + if(2 * cost1 <= cost2) + { + curr = (total * cost1); + ans = min(ans, curr); + } + else + { + lli maxDiff = curMax - mini; + lli pair = total - maxDiff; + + if(pair < maxDiff) + { + lli nonPair = maxDiff - pair; + curr = (nonPair * cost1) + (pair * cost2); + ans = min(ans, curr); + continue; + } + + curr = ((total/2) * cost2) + ((total%2) * cost1); + + ans = min(ans, curr); + } + } + + return ans%mod; + } +}; \ No newline at end of file diff --git a/3139-minimum-cost-to-equalize-array/NOTES.md b/3139-minimum-cost-to-equalize-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3139-minimum-cost-to-equalize-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3154-find-number-of-ways-to-reach-the-k-th-stair/3154-find-number-of-ways-to-reach-the-k-th-stair.cpp b/3154-find-number-of-ways-to-reach-the-k-th-stair/3154-find-number-of-ways-to-reach-the-k-th-stair.cpp new file mode 100644 index 00000000..9049bed3 --- /dev/null +++ b/3154-find-number-of-ways-to-reach-the-k-th-stair/3154-find-number-of-ways-to-reach-the-k-th-stair.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + + map>> dp; + + int helper(int i, int backStep, int jump, int target) + { + int ans = 0; + + if(dp[i][backStep].find(jump) != dp[i][backStep].end()) + { + return dp[i][backStep][jump]; + } + + if(i == target) + { + ++ans; + } + + if(backStep and i > 0) + { + ans += helper(i-1, 0, jump, target); + } + + if(i + (1LL<3154. Find Number of Ways to Reach the K-th Stair

Hard


You are given a non-negative integer k. There exists a staircase with an infinite number of stairs, with the lowest stair numbered 0.

+ +

Alice has an integer jump, with an initial value of 0. She starts on stair 1 and wants to reach stair k using any number of operations. If she is on stair i, in one operation she can:

+ +
    +
  • Go down to stair i - 1. This operation cannot be used consecutively or on stair 0.
  • +
  • Go up to stair i + 2jump. And then, jump becomes jump + 1.
  • +
+ +

Return the total number of ways Alice can reach stair k.

+ +

Note that it is possible that Alice reaches the stair k, and performs some operations to reach the stair k again.

+ +

 

+

Example 1:

+ +
+

Input: k = 0

+ +

Output: 2

+ +

Explanation:

+ +

The 2 possible ways of reaching stair 0 are:

+ +
    +
  • Alice starts at stair 1. +
      +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    +
  • +
  • Alice starts at stair 1. +
      +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
    • +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    +
  • +
+
+ +

Example 2:

+ +
+

Input: k = 1

+ +

Output: 4

+ +

Explanation:

+ +

The 4 possible ways of reaching stair 1 are:

+ +
    +
  • Alice starts at stair 1. Alice is at stair 1.
  • +
  • Alice starts at stair 1. +
      +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
    • +
    +
  • +
  • Alice starts at stair 1. +
      +
    • Using an operation of the second type, she goes up 20 stairs to reach stair 2.
    • +
    • Using an operation of the first type, she goes down 1 stair to reach stair 1.
    • +
    +
  • +
  • Alice starts at stair 1. +
      +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
    • +
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • +
    • Using an operation of the second type, she goes up 21 stairs to reach stair 2.
    • +
    • Using an operation of the first type, she goes down 1 stair to reach stair 1.
    • +
    +
  • +
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/3164-find-the-number-of-good-pairs-ii/3164-find-the-number-of-good-pairs-ii.cpp b/3164-find-the-number-of-good-pairs-ii/3164-find-the-number-of-good-pairs-ii.cpp new file mode 100644 index 00000000..e50652d3 --- /dev/null +++ b/3164-find-the-number-of-good-pairs-ii/3164-find-the-number-of-good-pairs-ii.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + long long numberOfPairs(vector& nums1, vector& nums2, int k) { + + map fact; + + for(auto& ele : nums1) + { + int num = ele; + + for(int i = 1; i * i <= num; ++i) + { + if(num % i == 0) + { + ++fact[i]; + if(num/i != i) + ++fact[num/i]; + } + } + } + + long long ans = 0; + + for(auto& ele : nums2) + { + long long num = ele * k; + + ans += fact[num]; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/3164-find-the-number-of-good-pairs-ii/README.md b/3164-find-the-number-of-good-pairs-ii/README.md new file mode 100644 index 00000000..b81081a4 --- /dev/null +++ b/3164-find-the-number-of-good-pairs-ii/README.md @@ -0,0 +1,38 @@ +

3164. Find the Number of Good Pairs II

Medium


You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k.

+ +

A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k (0 <= i <= n - 1, 0 <= j <= m - 1).

+ +

Return the total number of good pairs.

+ +

 

+

Example 1:

+ +
+

Input: nums1 = [1,3,4], nums2 = [1,3,4], k = 1

+ +

Output: 5

+ +

Explanation:

+The 5 good pairs are (0, 0), (1, 0), (1, 1), (2, 0), and (2, 2).
+ +

Example 2:

+ +
+

Input: nums1 = [1,2,4,12], nums2 = [2,4], k = 3

+ +

Output: 2

+ +

Explanation:

+ +

The 2 good pairs are (3, 0) and (3, 1).

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n, m <= 105
  • +
  • 1 <= nums1[i], nums2[j] <= 106
  • +
  • 1 <= k <= 103
  • +
+
\ No newline at end of file diff --git a/3169-count-days-without-meetings/3169-count-days-without-meetings.cpp b/3169-count-days-without-meetings/3169-count-days-without-meetings.cpp new file mode 100644 index 00000000..e82c9dde --- /dev/null +++ b/3169-count-days-without-meetings/3169-count-days-without-meetings.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int countDays(int days, vector>& meetings) { + + int n = meetings.size(); + + vector> events; + + for(auto& e : meetings) + { + events.push_back({e[0], +1}); + events.push_back({e[1], -1}); + } + + events.push_back({0, 0}); + events.push_back({days+1, 0}); + + sort(events.begin(), events.end()); + + int ans = 0, currMeetings = 0; + + for(int i = 0; i < events.size()-1; ++i) + { + currMeetings += events[i].second; + + if(currMeetings == 0) + { + ans += max(0, events[i+1].first - events[i].first - 1); + } + + } + + return ans; + + } +}; \ No newline at end of file diff --git a/3169-count-days-without-meetings/NOTES.md b/3169-count-days-without-meetings/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3169-count-days-without-meetings/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3169-count-days-without-meetings/README.md b/3169-count-days-without-meetings/README.md new file mode 100644 index 00000000..ecd8d5e6 --- /dev/null +++ b/3169-count-days-without-meetings/README.md @@ -0,0 +1,53 @@ +

3169. Count Days Without Meetings

Medium


You are given a positive integer days representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array meetings of size n where, meetings[i] = [start_i, end_i] represents the starting and ending days of meeting i (inclusive).

+ +

Return the count of days when the employee is available for work but no meetings are scheduled.

+ +

Note: The meetings may overlap.

+ +

 

+

Example 1:

+ +
+

Input: days = 10, meetings = [[5,7],[1,3],[9,10]]

+ +

Output: 2

+ +

Explanation:

+ +

There is no meeting scheduled on the 4th and 8th days.

+
+ +

Example 2:

+ +
+

Input: days = 5, meetings = [[2,4],[1,3]]

+ +

Output: 1

+ +

Explanation:

+ +

There is no meeting scheduled on the 5th day.

+
+ +

Example 3:

+ +
+

Input: days = 6, meetings = [[1,6]]

+ +

Output: 0

+ +

Explanation:

+ +

Meetings are scheduled for all working days.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= days <= 109
  • +
  • 1 <= meetings.length <= 105
  • +
  • meetings[i].length == 2
  • +
  • 1 <= meetings[i][0] <= meetings[i][1] <= days
  • +
+
\ No newline at end of file diff --git a/3171-find-subarray-with-bitwise-and-closest-to-k/3171-find-subarray-with-bitwise-and-closest-to-k.cpp b/3171-find-subarray-with-bitwise-and-closest-to-k/3171-find-subarray-with-bitwise-and-closest-to-k.cpp new file mode 100644 index 00000000..1bc8d5f5 --- /dev/null +++ b/3171-find-subarray-with-bitwise-and-closest-to-k/3171-find-subarray-with-bitwise-and-closest-to-k.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minimumDifference(vector& nums, int k) { + + set curSet; + + int ans = INT_MAX; + + for(auto& ele : nums) + { + set newSet; + + for(auto& vals : curSet) + { + newSet.insert(vals & ele); + } + + newSet.insert(ele); + + for(auto& vals : newSet) + { + ans = min(ans, abs(k - vals)); + } + + curSet = newSet; + } + + return ans; + + } +}; \ No newline at end of file diff --git a/3171-find-subarray-with-bitwise-and-closest-to-k/README.md b/3171-find-subarray-with-bitwise-and-closest-to-k/README.md new file mode 100644 index 00000000..8e2e15f6 --- /dev/null +++ b/3171-find-subarray-with-bitwise-and-closest-to-k/README.md @@ -0,0 +1,52 @@ +

3171. Find Subarray With Bitwise AND Closest to K

Hard


You are given an array nums and an integer k. You need to find a subarray of nums such that the absolute difference between k and the bitwise AND of the subarray elements is as small as possible. In other words, select a subarray nums[l..r] such that |k - (nums[l] AND nums[l + 1] ... AND nums[r])| is minimum.

+ +

Return the minimum possible value of the absolute difference.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
+

Input: nums = [1,2,4,5], k = 3

+ +

Output: 1

+ +

Explanation:

+ +

The subarray nums[2..3] has AND value 4, which gives the minimum absolute difference |3 - 4| = 1.

+
+ +

Example 2:

+ +
+

Input: nums = [1,2,1,2], k = 2

+ +

Output: 0

+ +

Explanation:

+ +

The subarray nums[1..1] has AND value 2, which gives the minimum absolute difference |2 - 2| = 0.

+
+ +

Example 3:

+ +
+

Input: nums = [1], k = 10

+ +

Output: 9

+ +

Explanation:

+ +

There is a single subarray with AND value 1, which gives the minimum absolute difference |10 - 1| = 9.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/3186-maximum-total-damage-with-spell-casting/3186-maximum-total-damage-with-spell-casting.cpp b/3186-maximum-total-damage-with-spell-casting/3186-maximum-total-damage-with-spell-casting.cpp new file mode 100644 index 00000000..a7c22a40 --- /dev/null +++ b/3186-maximum-total-damage-with-spell-casting/3186-maximum-total-damage-with-spell-casting.cpp @@ -0,0 +1,34 @@ +using ll = long long; + +class Solution { +public: + + long long maximumTotalDamage(vector& power) { + + map mp; + + for(auto& ele : power) + ++mp[ele]; + + vector vec; + + for(auto& [f, _] : mp) + vec.push_back(f); + + vector dp(vec.size()+1, 0); + + for(int i = vec.size()-1; i >= 0; --i) + { + ll notTake = dp[i+1]; + + int ubIdx = upper_bound(vec.begin(), vec.end(), vec[i] + 2) - vec.begin(); + + ll take = vec[i] * 1LL * mp[vec[i]] + dp[ubIdx]; + + dp[i] = max(take, notTake); + } + + return dp[0]; + + } +}; \ No newline at end of file diff --git a/3186-maximum-total-damage-with-spell-casting/NOTES.md b/3186-maximum-total-damage-with-spell-casting/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3186-maximum-total-damage-with-spell-casting/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3186-maximum-total-damage-with-spell-casting/README.md b/3186-maximum-total-damage-with-spell-casting/README.md new file mode 100644 index 00000000..3408ac47 --- /dev/null +++ b/3186-maximum-total-damage-with-spell-casting/README.md @@ -0,0 +1,43 @@ +

3186. Maximum Total Damage With Spell Casting

Medium


A magician has various spells.

+ +

You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value.

+ +

It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.

+ +

Each spell can be cast only once.

+ +

Return the maximum possible total damage that a magician can cast.

+ +

 

+

Example 1:

+ +
+

Input: power = [1,1,3,4]

+ +

Output: 6

+ +

Explanation:

+ +

The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.

+
+ +

Example 2:

+ +
+

Input: power = [7,1,6,6]

+ +

Output: 13

+ +

Explanation:

+ +

The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= power.length <= 105
  • +
  • 1 <= power[i] <= 109
  • +
+
\ No newline at end of file diff --git a/3187-peaks-in-array/3187-peaks-in-array.cpp b/3187-peaks-in-array/3187-peaks-in-array.cpp new file mode 100644 index 00000000..f3beefc1 --- /dev/null +++ b/3187-peaks-in-array/3187-peaks-in-array.cpp @@ -0,0 +1,133 @@ +template +class SEG +{ +public: + vector tree, lazy, arr; + T N; + SEG() {} + SEG(vector v) + { + N = v.size(); + arr.resize(N); + for (int i = 0; i < N; ++i) + arr[i] = v[i]; + tree.resize(4 * N + 5); + lazy.resize(4 * N + 5, 0); + + buildTree(0, 0, N - 1); + } + + bool isPeak(int idx) + { + if(idx <= 0 or idx >= N-1) + return false; + + return (arr[idx] > arr[idx-1] and arr[idx] > arr[idx+1]); + } + + void buildTree(int idx, int low, int high) + { + if (low == high) + { + tree[idx] = (isPeak(low) ? 1 : 0); + return; + } + + int mid = (low + high) >> 1; + buildTree(2 * idx + 1, low, mid); + buildTree(2 * idx + 2, mid + 1, high); + + tree[idx] = tree[2 * idx + 1] + tree[2 * idx + 2]; + + return; + } + + + int queryTree(int idx, int low, int high, int l, int r) + { + // no overlap + // l r low high or low high l r + if (r < low or l > high) + return 0; + + // complete overlap + // [l low high r] + if (low >= l and high <= r) + return tree[idx]; + + // partial overlap + int mid = (low + high) / 2; + int left = queryTree(2 * idx + 1, low, mid, l, r); + int right = queryTree(2 * idx + 2, mid + 1, high, l, r); + + return left + right; + } + +public: + void updateTree(int idx, int low, int high, int ind, int val) + { + if (low == high) + { + tree[idx] = (isPeak(low) ? 1 : 0); + return; + } + int mid = (low + high) >> 1; + if (ind <= mid) + updateTree(2 * idx + 1, low, mid, ind, val); + else + updateTree(2 * idx + 2, mid + 1, high, ind, val); + + tree[idx] = tree[2 * idx + 1] + tree[2 * idx + 2]; + } + + int query(int l, int r) + { + return queryTree(0, 0, N - 1, l, r); + } + + void update(int ind, int val) + { + updateTree(0, 0, N - 1, ind, val); + } + + void build() + { + buildTree(0, 0, N - 1); + } +}; + + +class Solution { +public: + vector countOfPeaks(vector& nums, vector>& queries) { + + vector ans; + + int n = nums.size(); + + SEG seg(nums); + + for(auto& q : queries) + { + int type = q[0]; + int x = q[1]; + int y = q[2]; + + if(type == 1) + { + ans.push_back(seg.query(x+1, y-1)); + } + else + { + seg.arr[x] = y; + seg.update(x, y); + if(x - 1 > 0) + seg.update(x-1, nums[x-1]); + if(x + 1 < n-1) + seg.update(x+1, nums[x+1]); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/3187-peaks-in-array/README.md b/3187-peaks-in-array/README.md new file mode 100644 index 00000000..822bb1d9 --- /dev/null +++ b/3187-peaks-in-array/README.md @@ -0,0 +1,66 @@ +

3187. Peaks in Array

Hard


A peak in an array arr is an element that is greater than its previous and next element in arr.

+ +

You are given an integer array nums and a 2D integer array queries.

+ +

You have to process queries of two types:

+ +
    +
  • queries[i] = [1, li, ri], determine the count of peak elements in the subarray nums[li..ri].
  • +
  • queries[i] = [2, indexi, vali], change nums[indexi] to vali.
  • +
+ +

Return an array answer containing the results of the queries of the first type in order.

+ +

Notes:

+ +
    +
  • The first and the last element of an array or a subarray cannot be a peak.
  • +
+ +

 

+

Example 1:

+ +
+

Input: nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]

+ +

Output: [0]

+ +

Explanation:

+ +

First query: We change nums[3] to 4 and nums becomes [3,1,4,4,5].

+ +

Second query: The number of peaks in the [3,1,4,4,5] is 0.

+
+ +

Example 2:

+ +
+

Input: nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]

+ +

Output: [0,1]

+ +

Explanation:

+ +

First query: nums[2] should become 4, but it is already set to 4.

+ +

Second query: The number of peaks in the [4,1,4] is 0.

+ +

Third query: The second 4 is a peak in the [4,1,4,2,1].

+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
  • 1 <= queries.length <= 105
  • +
  • queries[i][0] == 1 or queries[i][0] == 2
  • +
  • For all i that: +
      +
    • queries[i][0] == 1: 0 <= queries[i][1] <= queries[i][2] <= nums.length - 1
    • +
    • queries[i][0] == 2: 0 <= queries[i][1] <= nums.length - 1, 1 <= queries[i][2] <= 105
    • +
    +
  • +
+
\ No newline at end of file diff --git a/3202-find-the-maximum-length-of-valid-subsequence-ii/3202-find-the-maximum-length-of-valid-subsequence-ii.cpp b/3202-find-the-maximum-length-of-valid-subsequence-ii/3202-find-the-maximum-length-of-valid-subsequence-ii.cpp new file mode 100644 index 00000000..88f28610 --- /dev/null +++ b/3202-find-the-maximum-length-of-valid-subsequence-ii/3202-find-the-maximum-length-of-valid-subsequence-ii.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maximumLength(vector& nums, int k) { + + int ans = 0; + + for(int i = 0; i < k; ++i) + { + vector dp(k, 0); + + for(auto& x : nums) + { + int rem = x % k; + + dp[rem] = max(dp[rem], dp[(i - rem + k)%k] + 1); + + ans = max(ans, dp[rem]); + } + } + + return ans; + } +}; \ No newline at end of file diff --git a/3202-find-the-maximum-length-of-valid-subsequence-ii/NOTES.md b/3202-find-the-maximum-length-of-valid-subsequence-ii/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/3202-find-the-maximum-length-of-valid-subsequence-ii/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/3202-find-the-maximum-length-of-valid-subsequence-ii/README.md b/3202-find-the-maximum-length-of-valid-subsequence-ii/README.md new file mode 100644 index 00000000..d8d412fe --- /dev/null +++ b/3202-find-the-maximum-length-of-valid-subsequence-ii/README.md @@ -0,0 +1,41 @@ +

3202. Find the Maximum Length of Valid Subsequence II

Medium


You are given an integer array nums and a positive integer k. +

A subsequence sub of nums with length x is called valid if it satisfies:

+ +
    +
  • (sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.
  • +
+Return the length of the longest valid subsequence of nums. +

 

+

Example 1:

+ +
+

Input: nums = [1,2,3,4,5], k = 2

+ +

Output: 5

+ +

Explanation:

+ +

The longest valid subsequence is [1, 2, 3, 4, 5].

+
+ +

Example 2:

+ +
+

Input: nums = [1,4,2,3,1,4], k = 3

+ +

Output: 4

+ +

Explanation:

+ +

The longest valid subsequence is [1, 4, 1, 4].

+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 103
  • +
  • 1 <= nums[i] <= 107
  • +
  • 1 <= k <= 103
  • +
+
\ No newline at end of file diff --git a/3203-find-minimum-diameter-after-merging-two-trees/3203-find-minimum-diameter-after-merging-two-trees.cpp b/3203-find-minimum-diameter-after-merging-two-trees/3203-find-minimum-diameter-after-merging-two-trees.cpp new file mode 100644 index 00000000..0ad2e2d1 --- /dev/null +++ b/3203-find-minimum-diameter-after-merging-two-trees/3203-find-minimum-diameter-after-merging-two-trees.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + + void constructingList(vector>& edges, vector adj[]) + { + for(auto& edge : edges) + { + int u = edge[0]; + int v = edge[1]; + + adj[u].push_back(v); + adj[v].push_back(u); + } + } + + int maximumDiameter(vector adj[], int n) + { + vector dist(n, 0); + + function dfs = [&](int sv, int d) + { + dist[sv] = d; + for(auto& node : adj[sv]) + { + if(dist[node] == 0) + dfs(node, d+1); + } + }; + + dfs(0, 1); + int farthest = max_element(dist.begin(), dist.end()) - dist.begin(); + fill(dist.begin(), dist.end(), 0); + dfs(farthest, 1); + return *max_element(dist.begin(), dist.end()) - 1; + } + + int minimumDiameterAfterMerge(vector>& edges1, vector>& edges2) { + + int n = edges1.size(); + int m = edges2.size(); + + vector adj[n+1], adj2[m+1]; + + constructingList(edges1, adj); + constructingList(edges2, adj2); + + int diameter1 = maximumDiameter(adj, n+1); + int diameter2 = maximumDiameter(adj2, m+1); + + return max({diameter1, diameter2, (diameter1 + 1)/2 + (diameter2 + 1)/2 + 1}); + } +}; \ No newline at end of file diff --git a/3203-find-minimum-diameter-after-merging-two-trees/README.md b/3203-find-minimum-diameter-after-merging-two-trees/README.md new file mode 100644 index 00000000..97f18b2d --- /dev/null +++ b/3203-find-minimum-diameter-after-merging-two-trees/README.md @@ -0,0 +1,48 @@ +

3203. Find Minimum Diameter After Merging Two Trees

Hard


There exist two undirected trees with n and m nodes, numbered from 0 to n - 1 and from 0 to m - 1, respectively. You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.

+ +

You must connect one node from the first tree with another node from the second tree with an edge.

+ +

Return the minimum possible diameter of the resulting tree.

+ +

The diameter of a tree is the length of the longest path between any two nodes in the tree.

+ +

 

+

Example 1:

+ +
+

Input: edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]

+ +

Output: 3

+ +

Explanation:

+ +

We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.

+
+ +

Example 2:

+ +
+

Input: edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]

+ +

Output: 5

+ +

Explanation:

+ +

We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n, m <= 105
  • +
  • edges1.length == n - 1
  • +
  • edges2.length == m - 1
  • +
  • edges1[i].length == edges2[i].length == 2
  • +
  • edges1[i] = [ai, bi]
  • +
  • 0 <= ai, bi < n
  • +
  • edges2[i] = [ui, vi]
  • +
  • 0 <= ui, vi < m
  • +
  • The input is generated such that edges1 and edges2 represent valid trees.
  • +
+
\ No newline at end of file diff --git a/3224-minimum-array-changes-to-make-differences-equal/3224-minimum-array-changes-to-make-differences-equal.cpp b/3224-minimum-array-changes-to-make-differences-equal/3224-minimum-array-changes-to-make-differences-equal.cpp new file mode 100644 index 00000000..edd38009 --- /dev/null +++ b/3224-minimum-array-changes-to-make-differences-equal/3224-minimum-array-changes-to-make-differences-equal.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minChanges(vector& nums, int k) { + + int n = nums.size(); + + map mp; + + for(int i = 0; i < n/2; ++i) + { + int diff = abs(nums[i] - nums[n-i-1]); + int maxDiff = max(k - min(nums[i], nums[n-i-1]), max(nums[i], nums[n-i-1])); + ++mp[0]; + --mp[diff]; + ++mp[diff+1]; + ++mp[maxDiff + 1]; + } + + int ans = INT_MAX, sum = 0; + + for(auto&[f, e] : mp) + { + sum += e; + ans = min(ans, sum); + } + + return ans; + } +}; \ No newline at end of file diff --git a/3224-minimum-array-changes-to-make-differences-equal/README.md b/3224-minimum-array-changes-to-make-differences-equal/README.md new file mode 100644 index 00000000..a40cf925 --- /dev/null +++ b/3224-minimum-array-changes-to-make-differences-equal/README.md @@ -0,0 +1,58 @@ +

3224. Minimum Array Changes to Make Differences Equal

Medium


You are given an integer array nums of size n where n is even, and an integer k.

+ +

You can perform some changes on the array, where in one change you can replace any element in the array with any integer in the range from 0 to k.

+ +

You need to perform some changes (possibly none) such that the final array satisfies the following condition:

+ +
    +
  • There exists an integer X such that abs(a[i] - a[n - i - 1]) = X for all (0 <= i < n).
  • +
+ +

Return the minimum number of changes required to satisfy the above condition.

+ +

 

+

Example 1:

+ +
+

Input: nums = [1,0,1,2,4,3], k = 4

+ +

Output: 2

+ +

Explanation:
+We can perform the following changes:

+ +
    +
  • Replace nums[1] by 2. The resulting array is nums = [1,2,1,2,4,3].
  • +
  • Replace nums[3] by 3. The resulting array is nums = [1,2,1,3,4,3].
  • +
+ +

The integer X will be 2.

+
+ +

Example 2:

+ +
+

Input: nums = [0,1,2,3,3,6,5,4], k = 6

+ +

Output: 2

+ +

Explanation:
+We can perform the following operations:

+ +
    +
  • Replace nums[3] by 0. The resulting array is nums = [0,1,2,0,3,6,5,4].
  • +
  • Replace nums[4] by 4. The resulting array is nums = [0,1,2,0,4,6,5,4].
  • +
+ +

The integer X will be 4.

+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n == nums.length <= 105
  • +
  • n is even.
  • +
  • 0 <= nums[i] <= k <= 105
  • +
+
\ No newline at end of file diff --git a/6911-continuous-subarrays/6911-continuous-subarrays.cpp b/6911-continuous-subarrays/6911-continuous-subarrays.cpp new file mode 100644 index 00000000..49146e41 --- /dev/null +++ b/6911-continuous-subarrays/6911-continuous-subarrays.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + long long continuousSubarrays(vector& nums) { + + int n = nums.size(); + + long long int ans = 0, j = 0; + + multiset st; + + for(int i = 0; i < n; ++i) + { + st.insert(nums[i]); + + while(*st.rbegin() - *st.begin() > 2) + { + auto it = st.find(nums[j]); + st.erase(it); + ++j; + } + + ans += (i - j + 1); + } + + return ans; + + } +}; \ No newline at end of file diff --git a/6911-continuous-subarrays/NOTES.md b/6911-continuous-subarrays/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/6911-continuous-subarrays/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/6911-continuous-subarrays/README.md b/6911-continuous-subarrays/README.md new file mode 100644 index 00000000..4afbbdcf --- /dev/null +++ b/6911-continuous-subarrays/README.md @@ -0,0 +1,45 @@ +

6911. Continuous Subarrays

Medium


You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:

+ +
    +
  • Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.
  • +
+ +

Return the total number of continuous subarrays.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [5,4,2,4]
+Output: 8
+Explanation: 
+Continuous subarray of size 1: [5], [4], [2], [4].
+Continuous subarray of size 2: [5,4], [4,2], [2,4].
+Continuous subarray of size 3: [4,2,4].
+Thereare no subarrys of size 4.
+Total continuous subarrays = 4 + 3 + 1 = 8.
+It can be shown that there are no more continuous subarrays.
+
+ +

 

+ +

Example 2:

+ +
Input: nums = [1,2,3]
+Output: 6
+Explanation: 
+Continuous subarray of size 1: [1], [2], [3].
+Continuous subarray of size 2: [1,2], [2,3].
+Continuous subarray of size 3: [1,2,3].
+Total continuous subarrays = 3 + 2 + 1 = 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/BFS of graph - GFG/README.md b/BFS of graph - GFG/README.md new file mode 100644 index 00000000..aad23504 --- /dev/null +++ b/BFS of graph - GFG/README.md @@ -0,0 +1,26 @@ +# BFS of graph +## Easy +

Given a directed graph. The task is to do Breadth First Traversal of this graph starting from 0.
Note: One can move from node u to node v only if there's an edge from u to v. Find the BFS traversal of the graph starting from the 0th vertex,
from left to right according to the input graph. Also, you should only take nodes directly or indirectly connected from Node 0 in consideration.

+


Example 1:

+
Input:
+
+Output: 0 1 2 3 4
+Explanation: 
+0 is connected to 1 , 2 , 3.
+2 is connected to 4.
+so starting from 0, it will go to 1 then 2
+then 3. After this 2 to 4, thus bfs will be
+0 1 2 3 4.
+
+

Example 2:

+
Input:
+
+Output: 0 1 2
+Explanation:
+0 is connected to 1 , 2.
+so starting from 0, it will go to 1 then 2,
+thus bfs will be 0 1 2. 
+
+


Your task:
You dont need to read input or print anything. Your task is to complete the function bfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns
 a list containing the BFS traversal of the graph starting from the 0th vertex from left to right.

+


Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

+


Constraints:
1 ≤ V, E ≤ 104

\ No newline at end of file diff --git a/Boolean Matrix - GFG/README.md b/Boolean Matrix - GFG/README.md new file mode 100644 index 00000000..5c0cc0a5 --- /dev/null +++ b/Boolean Matrix - GFG/README.md @@ -0,0 +1,35 @@ +# Boolean Matrix +## Medium +

Given a boolean matrix of size RxC where each cell contains either 0 or 1, modify it such that if a matrix cell matrix[i][j] is 1 then all the cells in its ith row and jth column will become 1.

+

Example 1:

+
Input:
+R = 2, C = 2
+matrix[][] = {{1, 0},
+              {0, 0}}
+Output: 
+1 1
+1 0 
+Explanation:
+Only cell that has 1 is at (0,0) so all 
+cells in row 0 are modified to 1 and all 
+cells in column 0 are modified to 1.
+


Example 2:

+
Input:
+R = 4, C = 3
+matrix[][] = {{ 1, 0, 0},
+              { 1, 0, 0},
+              { 1, 0, 0},
+              { 0, 0, 0}}
+Output: 
+1 1 1
+1 1 1
+1 1 1
+1 0 0 
+Explanation:
+The position of cells that have 1 in
+the original matrix are (0,0), (1,0)
+and (2,0). Therefore, all cells in row
+0,1,2 are and column 0 are modified to 1. 
+

Your Task:
You dont need to read input or print anything. Complete the function booleanMatrix() that takes the matrix as input parameter and modifies it in-place.

+

Expected Time Complexity: O(R * C)
Expected Auxiliary Space: O(R + C) 

+

Constraints:
1 ≤ R, C ≤ 1000
0 ≤ matrix[i][j] ≤ 1

\ No newline at end of file diff --git a/Boolean Matrix - GFG/boolean-matrix.cpp b/Boolean Matrix - GFG/boolean-matrix.cpp new file mode 100644 index 00000000..fd1cca9b --- /dev/null +++ b/Boolean Matrix - GFG/boolean-matrix.cpp @@ -0,0 +1,81 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + + +class Solution +{ + public: + //Function to modify the matrix such that if a matrix cell matrix[i][j] + //is 1 then all the cells in its ith row and jth column will become 1. + void booleanMatrix(vector > &matrix) + { + // code here + + int n = matrix.size(); + int m = matrix[0].size(); + + vector row(n, 0), col(m, 0); + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(matrix[i][j] == 1) + { + row[i] = col[j] = 1; + } + } + } + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(row[i] or col[j]) + matrix[i][j] = 1; + } + } + } +}; + + +//{ Driver Code Starts. +int main() { + int t; + cin>>t; + while(t--) + { + int row, col; + cin>> row>> col; + vector > matrix(row); + for(int i=0; i>matrix[i][j]; + } + } + + Solution ob; + ob.booleanMatrix(matrix); + + + for (int i = 0; i < row; ++i) + { + for (int j = 0; j < col; ++j) + { + cout<

You are given a matrix of dimensions n x m. The task is to perform boundary traversal on the matrix in a clockwise manner.

Example 1:

+
Input:
+n = 4, m = 4
+matrix[][] = {{1, 2, 3, 4},
+         {5, 6, 7, 8},
+         {9, 10, 11, 12},
+         {13, 14, 15,16}}
+Output: 1 2 3 4 8 12 16 15 14 13 9 5
+Explanation:
+The matrix is:
+1 2 3 4
+5 6 7 8
+9 10 11 12
+13 14 15 16
+The boundary traversal is:
+1 2 3 4 8 12 16 15 14 13 9 5
+
+

Example 2:

+
Input:
+n = 3, m = 4
+matrrix[][] = {{12, 11, 10, 9},
+         {8, 7, 6, 5},
+         {4, 3, 2, 1}}
+Output: 12 11 10 9 5 1 2 3 4 8
+
+

Your Task:
Complete the function boundaryTraversal() that takes matrix, n and m as input parameters and returns the list of integers that form the boundary traversal of the matrix in a clockwise manner.


Expected Time Complexity: O(N + M)
Expected Auxiliary Space: O(1)


Constraints:
1 <= n, m<= 1000
0 <= matrixi <= 1000

\ No newline at end of file diff --git a/Boundary traversal of matrix - GFG/boundary-traversal-of-matrix.cpp b/Boundary traversal of matrix - GFG/boundary-traversal-of-matrix.cpp new file mode 100644 index 00000000..9688b6c2 --- /dev/null +++ b/Boundary traversal of matrix - GFG/boundary-traversal-of-matrix.cpp @@ -0,0 +1,69 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + +class Solution +{ + public: + //Function to return list of integers that form the boundary + //traversal of the matrix in a clockwise manner. + vector boundaryTraversal(vector > matrix, int n, int m) + { + // code here + + vector ans; + + for(int i = 0; i < m; ++i) + ans.push_back(matrix[0][i]); + + if(n > 1) + { + for(int i = 1; i < n; ++i) + ans.push_back(matrix[i][m-1]); + + for(int i = m-2; i >= 0; --i) + ans.push_back(matrix[n-1][i]); + + if(m > 1) + { + for(int i = n-2; i >= 1; --i) + ans.push_back(matrix[i][0]); + } + } + + return ans; + } +}; + + +//{ Driver Code Starts. +int main() { + int t; + cin>>t; + + while(t--) + { + int n,m; + cin>>n>>m; + vector > matrix(n); + + for(int i=0; i>matrix[i][j]; + } + } + + Solution ob; + vector result = ob.boundaryTraversal(matrix, n, m); + for (int i = 0; i < result.size(); ++i) + cout<

Given a binary tree, find if it is height balanced or not. 
A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. 

+

A height balanced tree
        1
     /     \
   10      39
  /
5

+

An unbalanced tree
        1
     /    
   10   
  /
5

+

Example 1:

+
Input:
+      1
+    /
+   2
+    \
+     3 
+Output: 0
+Explanation: The max difference in height
+of left subtree and right subtree is 2,
+which is greater than 1. Hence unbalanced
+
+

Example 2:

+
Input:
+       10
+     /   \
+    20   30 
+  /   \
+ 40   60
+Output: 1
+Explanation: The max difference in height
+of left subtree and right subtree is 1.
+Hence balanced. 
+
+

Your Task:
You don't need to take input. Just complete the function isBalanced() that takes root node as parameter and returns true, if the tree is balanced else returns false.

+

Constraints:
1 <= Number of nodes <= 105
1 <= Data of a node <= 109

+

Expected time complexity: O(N)
Expected auxiliary space: O(h) , where h = height of tree

\ No newline at end of file diff --git a/Check for Balanced Tree - GFG/check-for-balanced-tree.cpp b/Check for Balanced Tree - GFG/check-for-balanced-tree.cpp new file mode 100644 index 00000000..df84409c --- /dev/null +++ b/Check for Balanced Tree - GFG/check-for-balanced-tree.cpp @@ -0,0 +1,152 @@ +//{ Driver Code Starts +//Initial Template for C++ + + +#include +using namespace std; + + +// Tree Node +struct Node { + int data; + Node* left; + Node* right; +}; + +// Utility function to create a new Tree Node +Node* newNode(int val) { + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + + +// Function to Build Tree +Node* buildTree(string str) { + // Corner Case + if (str.length() == 0 || str[0] == 'N') return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +// } Driver Code Ends +/* A binary tree node structure + +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; + */ + +class Solution{ + public: + //Function to check whether a binary tree is balanced or not. + + int height(Node* root) + { + if(!root) + return 0; + return 1 + max(height(root->left), height(root->right)); + } + + bool isBalanced(Node *root) + { + // Your Code here + + if(!root) + return true; + + int left = height(root->left); + int right = height(root->right); + + return abs(left-right) <=1 and isBalanced(root->left) and isBalanced(root->right); + } +}; + + +//{ Driver Code Starts. + +/* Driver program to test size function*/ + + + +int main() { + + + int t; + scanf("%d ", &t); + while (t--) { + string s, ch; + getline(cin, s); + + Node* root = buildTree(s); + Solution ob; + cout << ob.isBalanced(root) << endl; + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Check if Tree is Isomorphic - GFG/README.md b/Check if Tree is Isomorphic - GFG/README.md new file mode 100644 index 00000000..728fd7bb --- /dev/null +++ b/Check if Tree is Isomorphic - GFG/README.md @@ -0,0 +1,26 @@ +# Check if Tree is Isomorphic +## Easy +

Given two Binary Trees. Check whether they are Isomorphic or not.

+

Note: 
Two trees are called isomorphic if one can be obtained from another by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.
For example, the following two trees are isomorphic with the following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8.
ISomorphicTrees

+

Example 1:

+
Input:
+ T1    1     T2:   1
+     /   \        /  \
+    2     3      3    2
+   /            /
+  4            4
+Output: No
+
+
+

Example 2:

+
Input:
+T1    1     T2:    1
+    /  \         /   \
+   2    3       3     2
+  /                    \
+  4                     4
+Output: Yes
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function isomorphic() that takes the root nodes of both the Binary Trees as its input and returns True if the two trees are isomorphic. Else, it returns False. (The driver code will print Yes if the returned values are true, otherwise false.)

+

Expected Time Complexity: O(min(M, N)) where M and N are the sizes of the two trees.
Expected Auxiliary Space: O(min(H1, H2)) where H1 and H2 are the heights of the two trees.

+

Constraints:
1<=Number of nodes<=105

\ No newline at end of file diff --git a/Check if Tree is Isomorphic - GFG/check-if-tree-is-isomorphic.cpp b/Check if Tree is Isomorphic - GFG/check-if-tree-is-isomorphic.cpp new file mode 100644 index 00000000..3f9bc783 --- /dev/null +++ b/Check if Tree is Isomorphic - GFG/check-if-tree-is-isomorphic.cpp @@ -0,0 +1,139 @@ +//{ Driver Code Starts +#include +using namespace std; +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +// } Driver Code Ends +/*Complete the function below +Node is as follows: +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; +*/ + +class Solution{ + + public: + // Return True if the given trees are isomotphic. Else return False. + bool isIsomorphic(Node *root1,Node *root2) + { + //add code here. + + if(!root1 and !root2) + return true; + + if(!root1 or !root2) + return false; + + bool valCheck = root1->data == root2->data; + + bool one = isIsomorphic(root1->left, root2->left) and isIsomorphic(root1->right, root2->right); + + bool two = isIsomorphic(root1->left, root2->right) and isIsomorphic(root1->right, root2->left); + + return valCheck & (one or two); + } +}; + +//{ Driver Code Starts. + +int main() +{ + int t; + scanf("%d ",&t); + while(t--) + { + string s1,s2; + getline(cin,s1); + getline(cin,s2); + Node* root1 = buildTree(s1); + Node* root2 = buildTree(s2); + Solution obj; + if(obj.isIsomorphic(root1,root2)) + cout<<"Yes"<

Given a number N and a bit number K, check if Kth index bit of N is set or not. A bit is called set if it is 1. Position of set bit '1' should be indexed starting with 0 from LSB side in binary representation of the number.
Note: Index is starting from 0. You just need to return true or false, driver code will take care of printing "Yes" and "No".

+

Example 1:

+
Input: 
N = 4
K = 0 +Output:
No +Explanation:
Binary representation of 4 is 100, in which 0th index bit from LSB is not set. So, return false.
+

Example 2:

+
Input: 
N = 4
K = 2 +Output:
Yes +Explanation:
Binary representation of 4 is 100, in which 2nd index bit from LSB is set. So, return true.
+

Example 3:

+
Input: 
N = 500
K = 3 +Output:
No +Explanation:
Binary representation of 500 is 111110100, in which 3rd index bit from LSB is not set. So, return false.
+
Your task:
+
You don't have to read input or print anything. Your task is to complete the function checkKthbit that takes n and k as parameters and returns either true(if kth bit is set) or false(if kth bit is not set).

Expected Time Complexity:
 O(1).
Expected Auxiliary Space: O(1).


Constraints:
1 ≤ N ≤ 109
0 ≤ K ≤ 31
\ No newline at end of file diff --git a/Check whether K-th bit is set or not - GFG/check-whether-kth-bit-is-set-or-not.cpp b/Check whether K-th bit is set or not - GFG/check-whether-kth-bit-is-set-or-not.cpp new file mode 100644 index 00000000..8a7874e7 --- /dev/null +++ b/Check whether K-th bit is set or not - GFG/check-whether-kth-bit-is-set-or-not.cpp @@ -0,0 +1,46 @@ +//{ Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + +// } Driver Code Ends +//User function Template for C++ + + +class Solution +{ + public: + // Function to check if Kth bit is set or not. + bool checkKthBit(int n, int k) + { + // Your code here + // It can be a one liner logic!! Think of it!! + + return n & (1 << k); + } +}; + +//{ Driver Code Starts. + +// Driver Code +int main() +{ + int t; + cin>>t;//taking testcases + while(t--) + { + long long n; + cin>>n;//input n + int k; + cin>>k;//bit number k + Solution obj; + if(obj.checkKthBit(n, k)) + cout << "Yes" << endl; + else + cout << "No" << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Chocolate Distribution Problem - GFG/README.md b/Chocolate Distribution Problem - GFG/README.md new file mode 100644 index 00000000..9682977c --- /dev/null +++ b/Chocolate Distribution Problem - GFG/README.md @@ -0,0 +1,19 @@ +# Chocolate Distribution Problem +## Easy +

Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that :
1. Each student gets exactly one packet.
2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum.

+

Example 1:

+
Input:
+N = 8, M = 5
+A = {3, 4, 1, 9, 56, 7, 9, 12}
+Output: 6
+Explanation: The minimum difference between maximum chocolates and minimum chocolates is 9 - 3 = 6 by choosing following M packets :{3, 4, 9, 7, 9}.
+
+

Example 2:

+
Input:
+N = 7, M = 3
+A = {7, 3, 2, 4, 9, 12, 56}
+Output: 2
+Explanation: The minimum difference between maximum chocolates and minimum chocolates is 4 - 2 = 2 by choosing following M packets :{3, 2, 4}.
+

Your Task:
You don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student.

+

Expected Time Complexity: O(N*Log(N))
Expected Auxiliary Space: O(1)

+

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 105
1 ≤ Ai ≤ 109
1 ≤ M ≤ N

\ No newline at end of file diff --git a/Chocolate Distribution Problem - GFG/chocolate-distribution-problem.cpp b/Chocolate Distribution Problem - GFG/chocolate-distribution-problem.cpp new file mode 100644 index 00000000..b16c3333 --- /dev/null +++ b/Chocolate Distribution Problem - GFG/chocolate-distribution-problem.cpp @@ -0,0 +1,57 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ + public: + long long findMinDiff(vector a, long long n, long long m){ + //code + sort(a.begin(),a.end()); + + int i = 0, j = 0, ans = a[a.size()-1]; + + list l; + + while(j < n) + { + l.push_back(a[j]); + + if(l.size() == m) + { + ans = min(ans, l.back() - l.front()); + + l.pop_front(); + ++i; + } + ++j; + } + + return ans; + } +}; + +//{ Driver Code Starts. +int main() { + long long t; + cin>>t; + while(t--) + { + long long n; + cin>>n; + vector a; + long long x; + for(long long i=0;i>x; + a.push_back(x); + } + + long long m; + cin>>m; + Solution ob; + cout<

Given an integer array coins[ ] of sizerepresenting different denominations of currency and an integer sum, find the number of ways you can make sum by using different combinations from coins[ ].  
Note: Assume that you have an infinite supply of each type of coin. And you can use any coin as many times as you want.

+

Example 1:

+
Input:
+N = 3, sum = 4
+coins = {1,2,3}
+Output: 4
+Explanation: Four Possible ways are: {1,1,1,1},{1,1,2},{2,2},{1,3}.
+
+

Example 2:

+
Input:
+N = 4, Sum = 10
+coins = {2,5,3,6}
+Output: 5
+Explanation: Five Possible ways are: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function count() which accepts an array coins its size N and sum as input parameters and returns the number of ways to make change for given sum of money. 

+

Expected Time Complexity: O(sum*N)
Expected Auxiliary Space: O(sum)

+

Constraints:
1 <= sum, N, coins[i] <= 103

\ No newline at end of file diff --git a/Coin Change - GFG/coin-change.cpp b/Coin Change - GFG/coin-change.cpp new file mode 100644 index 00000000..bea08df6 --- /dev/null +++ b/Coin Change - GFG/coin-change.cpp @@ -0,0 +1,54 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + long long int count(int coins[], int N, int sum) { + + // code here. + + vector> dp(N+1, vector(sum+1,0)); + + for(int i = 0; i <= sum; ++i) + { + dp[N-1][i] = (i % coins[N-1] == 0); + } + + for(int i = N-2; i >= 0; --i) + { + for(int j = 0; j <= sum; ++j) + { + long long int notTake = dp[i+1][j]; + long long int take = 0; + + if(coins[i] <= j) + take = dp[i][j-coins[i]]; + + dp[i][j] = take + notTake; + } + } + + return dp[0][sum]; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int sum, N; + cin >> sum >> N; + int coins[N]; + for (int i = 0; i < N; i++) cin >> coins[i]; + Solution ob; + cout << ob.count(coins, N, sum) << endl; + } + + return 0; +} + + +// } Driver Code Ends \ No newline at end of file diff --git a/Column name from a given column number - GFG/README.md b/Column name from a given column number - GFG/README.md new file mode 100644 index 00000000..eb24562d --- /dev/null +++ b/Column name from a given column number - GFG/README.md @@ -0,0 +1,21 @@ +# Column name from a given column number +## Medium +

Given a positive integer, return its corresponding column title as appear in an Excel sheet.
Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ, AAA, AAB ….. etc. In other words, column 1 is named as “A”, column 2 as “B”, column 27 as “AA” and so on.

+

Example 1:

+
Input:
+N = 28
+Output: AB
+Explanation: 1 to 26 are A to Z.
+Then, 27 is AA and 28 = AB.
+
+
+

Example 2:

+
Input: 
+N = 13
+Output: M
+Explanation: M is the 13th character of
+alphabet.
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function colName() which takes the column number N as input and returns the column name represented as a string.

Expected Time Complexity: O(LogN).
Expected Auxiliary Space: O(1).

+

Constraints:
1 <= N <= 1018

+

 

\ No newline at end of file diff --git a/Column name from a given column number - GFG/column-name-from-a-given-column-number.cpp b/Column name from a given column number - GFG/column-name-from-a-given-column-number.cpp new file mode 100644 index 00000000..c1086872 --- /dev/null +++ b/Column name from a given column number - GFG/column-name-from-a-given-column-number.cpp @@ -0,0 +1,41 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + + +class Solution{ + public: + string colName (long long int n) + { + // your code here + + string ans; + + while(n--) + { + int rem = n%26; + ans.push_back(rem + 'A'); + n /= 26; + } + + reverse(ans.begin(), ans.end()); + + return ans; + } +}; + +//{ Driver Code Starts. +int main() +{ + int t; cin >> t; + while (t--) + { + long long int n; cin >> n; + Solution ob; + cout << ob.colName (n) << '\n'; + } +} + +// } Driver Code Ends \ No newline at end of file diff --git a/DFS of Graph - GFG/README.md b/DFS of Graph - GFG/README.md new file mode 100644 index 00000000..5921428f --- /dev/null +++ b/DFS of Graph - GFG/README.md @@ -0,0 +1,33 @@ +# DFS of Graph +## Easy +

You are given a connected undirected graph. Perform a Depth First Traversal of the graph.
Note: Use a recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph.

+


Example 1:

+
Input: V = 5 , adj = [[2,3,1] , [0], [0,4], [0], [2]]
+
+Output: 0 2 4 3 1
+Explanation: 
+0 is connected to 2, 3, 1.
+1 is connected to 0.
+2 is connected to 0 and 4.
+3 is connected to 0.
+4 is connected to 2.
+so starting from 0, it will go to 2 then 4,
+and then 3 and 1.
+Thus dfs will be 0 2 4 3 1.
+
+

Example 2:

+
Input: V = 4, adj = [[1,3], [2,0], [1], [0]]
+
+Output: 0 1 2 3
+Explanation:
+0 is connected to 1 , 3.
+1 is connected to 0, 2. 
+2 is connected to 1.
+3 is connected to 0. 
+so starting from 0, it will go to 1 then 2
+then back to 0 then 0 to 3
+thus dfs will be 0 1 2 3. 
+
+


Your task:
You don't need to read input or print anything. Your task is to complete the function dfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns a list containing the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph.

+


Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

+


Constraints:
1 ≤ V, E ≤ 104

\ No newline at end of file diff --git a/DFS of Graph - GFG/dfs-of-graph.java b/DFS of Graph - GFG/dfs-of-graph.java new file mode 100644 index 00000000..38473f8f --- /dev/null +++ b/DFS of Graph - GFG/dfs-of-graph.java @@ -0,0 +1,67 @@ +//{ Driver Code Starts +// Initial Template for Java +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG { + public static void main(String[] args) throws IOException { + BufferedReader br = + new BufferedReader(new InputStreamReader(System.in)); + int T = Integer.parseInt(br.readLine().trim()); + while (T-- > 0) { + String[] s = br.readLine().trim().split(" "); + int V = Integer.parseInt(s[0]); + int E = Integer.parseInt(s[1]); + ArrayList> adj = + new ArrayList>(); + for (int i = 0; i < V; i++) adj.add(new ArrayList()); + for (int i = 0; i < E; i++) { + String[] S = br.readLine().trim().split(" "); + int u = Integer.parseInt(S[0]); + int v = Integer.parseInt(S[1]); + adj.get(u).add(v); + adj.get(v).add(u); + } + Solution obj = new Solution(); + ArrayList ans = obj.dfsOfGraph(V, adj); + for (int i = 0; i < ans.size(); i++) + System.out.print(ans.get(i) + " "); + System.out.println(); + } + } +} + +// } Driver Code Ends + + +class Solution { + // Function to return a list containing the DFS traversal of the graph. + + void dfs(int sv, ArrayList> adj, boolean visited[], ArrayList arr) + { + arr.add(sv); + + visited[sv] = true; + + for(int i = 0; i < adj.get(sv).size(); ++i) + { + int val = adj.get(sv).get(i); + if(!visited[val]) + { + dfs(val, adj, visited, arr); + } + } + } + + public ArrayList dfsOfGraph(int V, ArrayList> adj) { + // Code here + + ArrayList arr = new ArrayList(); + + boolean[] visited = new boolean[V+1]; + + dfs(0, adj, visited, arr); + + return arr; + } +} \ No newline at end of file diff --git a/Delete a Node in Single Linked List - GFG/README.md b/Delete a Node in Single Linked List - GFG/README.md new file mode 100644 index 00000000..7889f292 --- /dev/null +++ b/Delete a Node in Single Linked List - GFG/README.md @@ -0,0 +1,22 @@ +# Delete a Node in Single Linked List +## Easy +

Given a singly linked list and an integer x.Delete xth node from the singly linked list.

+

Example 1:

+
Input: 1 -> 3 -> 4 
+       x = 3
+Output: 1 -> 3
+Explanation:
+After deleting the node at 3rd
+position (1-base indexing), the
+linked list is as 1 -> 3. 
+
+

Example 2:

+
Input: 1 -> 5 -> 2 -> 9 
+x = 2
+Output: 1 -> 2 -> 9
+Explanation: 
+After deleting the node at 2nd
+position (1-based indexing), the
+linked list is as 1 -> 2 -> 9.
+

Your task: Your task is to complete the method deleteNode() which takes two arguments: the address of the head of the linked list and an integer x. The function returns the head of the modified linked list.

+

Constraints:
2 <= N <= 105
1 <= x <= N

\ No newline at end of file diff --git a/Delete a Node in Single Linked List - GFG/delete-a-node-in-single-linked-list.cpp b/Delete a Node in Single Linked List - GFG/delete-a-node-in-single-linked-list.cpp new file mode 100644 index 00000000..e611a5c7 --- /dev/null +++ b/Delete a Node in Single Linked List - GFG/delete-a-node-in-single-linked-list.cpp @@ -0,0 +1,104 @@ +//{ Driver Code Starts +// C program to find n'th Node in linked list +#include +#include +#include +using namespace std; + +/* Link list Node */ +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; + +void append(struct Node** head_ref, struct Node **tail_ref, + int new_data) +{ + struct Node* new_node = new Node(new_data); + + if (*head_ref == NULL) + *head_ref = new_node; + else + (*tail_ref)->next = new_node; + *tail_ref = new_node; +} + +/* Function to get the middle of the linked list*/ +struct Node* deleteNode(struct Node *head,int ); + +void printList(Node *head) +{ + while (head != NULL) + { + cout << head->data << " "; + head = head->next; + } + cout << "\n"; +} + +/* Driver program to test above function*/ +int main() +{ + int T, i, n, l; + + cin>>T; + + while(T--){ + struct Node *head = NULL, *tail = NULL; + + cin>>n; + for(i=1;i<=n;i++) + { + cin>>l; + append(&head, &tail, l); + } + + int kk; + cin>>kk; + head = deleteNode(head,kk); + printList(head); + } + return 0; +} + +// } Driver Code Ends + + +/* Link list Node +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; +*/ + +/*You are required to complete below method*/ +Node* deleteNode(Node *head,int x) +{ + //Your code here + + if(!head) + return nullptr; + + if(x == 1) + { + Node* newHead = head->next; + delete(head); + return newHead; + } + + head->next = deleteNode(head->next, x-1); + + return head; +} diff --git a/Equilibrium Point - GFG/README.md b/Equilibrium Point - GFG/README.md new file mode 100644 index 00000000..78a09c4b --- /dev/null +++ b/Equilibrium Point - GFG/README.md @@ -0,0 +1,22 @@ +# Equilibrium Point +## Easy +

Given an array A of n positive numbers. The task is to find the first equilibrium point in an array. Equilibrium point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.

+

Note: Return equilibrium point in 1-based indexing. Return -1 if no such point exists. 

+

Example 1:

+
Input: 
+n = 5 
+A[] = {1,3,5,2,2} 
+Output: 
3 +Explanation: +equilibrium point is at position 3 as sum of elements before it (1+3) = sum of elements after it (2+2).
+
+

Example 2:

+
Input:
+n = 1
+A[] = {1}
+Output: 
1 +Explanation: +Since there's only element hence its only the equilibrium point.
+

Your Task:
The task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium. 

+

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= n <= 105
1 <= A[i] <= 109

\ No newline at end of file diff --git a/Equilibrium Point - GFG/equilibrium-point.java b/Equilibrium Point - GFG/equilibrium-point.java new file mode 100644 index 00000000..749dd797 --- /dev/null +++ b/Equilibrium Point - GFG/equilibrium-point.java @@ -0,0 +1,67 @@ +//{ Driver Code Starts +import java.io.*; +import java.util.*; +import java.util.stream.*; + +class Main { + + public static void main(String[] args) throws IOException { + BufferedReader br = + new BufferedReader(new InputStreamReader(System.in)); + int t = + Integer.parseInt(br.readLine().trim()); // Inputting the testcases + while (t-- > 0) { + + //taking input n + int n = Integer.parseInt(br.readLine().trim()); + long arr[] = new long[n]; + String inputLine[] = br.readLine().trim().split(" "); + + //adding elements to the array + for (int i = 0; i < n; i++) { + arr[i] = Long.parseLong(inputLine[i]); + } + + Solution ob = new Solution(); + + //calling equilibriumPoint() function + System.out.println(ob.equilibriumPoint(arr, n)); + } + } +} +// } Driver Code Ends + + +class Solution { + + + // a: input array + // n: size of array + // Function to find equilibrium point in the array. + public static int equilibriumPoint(long arr[], int n) { + + // Your code here + + int totalSum = 0 ; + + for(int i = 0; i < n; ++i) + totalSum += arr[i]; + + int currSum = 0 ; + + for(int i = 0; i < n; ++i) + { + currSum += arr[i]; + + long left = (i == 0 ? 0 : currSum - arr[i]); + long right = (i == n-1 ? 0 : totalSum - currSum); + + // System.out.println(left + " " + right); + + if(left == right) + return i+1; + } + + return -1; + } +} diff --git a/Eventual Safe States - GFG/README.md b/Eventual Safe States - GFG/README.md new file mode 100644 index 00000000..59c21c34 --- /dev/null +++ b/Eventual Safe States - GFG/README.md @@ -0,0 +1,51 @@ +# Eventual Safe States +## Medium +

A directed graph of V vertices and E edges is given in the form of an adjacency list adj. Each node of the graph is labelled with a distinct integer in the range 0 to V - 1.

+ +

A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node.

+ +

You have to return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

+ +

Example 1:

+ +
Input:
+
+
+Output:
+2 4 5 6
+Explanation:
+The given graph is shown above.
+Nodes 5 and 6 are terminal nodes as there are no 
+outgoing edges from either of them. 
+Every path starting at nodes 2, 4, 5, and 6 all 
+lead to either node 5 or 6.
+
+ +

Example 2:

+ +
Input:
+
+
+Output:
+3
+Explanation:
+Only node 3 is a terminal node, and every path 
+starting at node 3 leads to node 3.
+
+ +

Your Task:
+You don't need to read or print anything. Your task is to complete the function eventualSafeNodes() which takes an integer V denoting no. of vertices and adj denoting adjacency list of the graph and returns an array of safe nodes.

+ +

Expected Time Complexity: O(V + E)

+ +

Expected Space Complexity: O(V)

+ +

Constraints:

+ +
    +
  • 1 <= V <= 104
  • +
  • 0 <= E <= 104
  • +
  • The graph won't contain self loops.
  • +
  • Each node in the graph has a distinct value in the range 0 to V - 1.
  • +
+
\ No newline at end of file diff --git a/Eventual Safe States - GFG/eventual-safe-states.cpp b/Eventual Safe States - GFG/eventual-safe-states.cpp new file mode 100644 index 00000000..e6f97a13 --- /dev/null +++ b/Eventual Safe States - GFG/eventual-safe-states.cpp @@ -0,0 +1,95 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + +// } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + vector eventualSafeNodes(int V, vector adj[]) { + // code here + + + vector revAdj[V+1]; + + for(int i = 0; i < V; ++i) + { + for(auto& itr : adj[i]) + { + revAdj[itr].push_back(i); + } + } + + vector indegree(V+1,0); + + for(int i = 0; i < V; ++i) + { + for(auto& itr : revAdj[i]) + ++indegree[itr]; + } + + queue q; + + for(int i = 0; i < V; ++i) + { + if(indegree[i] == 0) + q.push(i); + } + + + vector safe; + + while(!q.empty()) + { + int curr = q.front(); + q.pop(); + + safe.push_back(curr); + + for(auto& itr : revAdj[curr]) + { + --indegree[itr]; + + if(indegree[itr] == 0) + q.push(itr); + } + } + + sort(safe.begin(), safe.end()); + + return safe; + } +}; + + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + + int V, E; + cin >> V >> E; + vector adj[V]; + + for (int i = 0; i < E; i++) { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + } + + Solution obj; + vector safeNodes = obj.eventualSafeNodes(V, adj); + for (auto i : safeNodes) { + cout << i << " "; + } + cout << endl; + } +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Find Common Nodes in two BSTs - GFG/README.md b/Find Common Nodes in two BSTs - GFG/README.md new file mode 100644 index 00000000..be9f1877 --- /dev/null +++ b/Find Common Nodes in two BSTs - GFG/README.md @@ -0,0 +1,40 @@ +# Find Common Nodes in two BSTs +## Easy +

Given two Binary Search Trees. Find the nodes that are common in both of them, ie- find the intersection of the two BSTs.

+

Note: Return the common nodes in sorted order.

+

Example 1:

+
Input:
+BST1:
+                  5
+               /     \
+             1        10
+           /   \      /
+          0     4    7
+                      \
+                       9
+BST2:
+                10 
+              /    \
+             7     20
+           /   \ 
+          4     9
+Output: 4 7 9 10
+
+
+

Example 2:

+
Input:
+BST1:
+     10
+    /  \
+   2   11
+  /  \
+ 1   3
+BST2:
+       2
+     /  \
+    1    3
+Output: 1 2 3
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function findCommon() that takes roots of the two BSTs as input parameters and returns a list of integers containing the common nodes in sorted order. 

+

Expected Time Complexity: O(N1 + N2) where N1 and N2 are the sizes of the 2 BSTs.
Expected Auxiliary Space: O(H1 + H2) where H1 and H2 are the heights of the 2 BSTs.

+

Constraints:
1 <= Number of Nodes <= 105
1 <= Node data <= 109

\ No newline at end of file diff --git a/Find Common Nodes in two BSTs - GFG/find-common-nodes-in-two-bsts.cpp b/Find Common Nodes in two BSTs - GFG/find-common-nodes-in-two-bsts.cpp new file mode 100644 index 00000000..d57d7cf2 --- /dev/null +++ b/Find Common Nodes in two BSTs - GFG/find-common-nodes-in-two-bsts.cpp @@ -0,0 +1,149 @@ +//{ Driver Code Starts +#include +using namespace std; + +// Tree Node +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +// } Driver Code Ends + + +class Solution +{ + public: + //Function to find the nodes that are common in both BST. + + map mp; + + void helper(Node* root) + { + if(root) + { + helper(root->left); + ++mp[root->data]; + helper(root->right); + } + } + + vector findCommon(Node *root1, Node *root2) + { + //Your code here + + helper(root1); + helper(root2); + + vector ans; + + for(auto& itr : mp) + { + if(itr.second > 1) + ans.push_back(itr.first); + } + + return ans; + + } +}; + + + + +//{ Driver Code Starts. + +int main() +{ + int t; + cin>>t; + getchar(); + while(t--) + { + string s; + getline(cin,s); + Node* root1 = buildTree(s); + + getline(cin,s); + Node* root2 = buildTree(s); + Solution ob; + vector res = ob.findCommon(root1, root2); + for (int i : res) + cout << i << " "; + cout<< endl; + } + + return 1; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Find duplicates in an array - GFG/README.md b/Find duplicates in an array - GFG/README.md new file mode 100644 index 00000000..81f21dc6 --- /dev/null +++ b/Find duplicates in an array - GFG/README.md @@ -0,0 +1,19 @@ +# Find duplicates in an array +## Easy +

Given an array a of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array. Return the answer in ascending order. If no such element is found, return list containing [-1]

+

Note: The extra space is only for the array to be returned. Try and perform all operations within the provided array. 

+

Example 1:

+
Input:
+N = 4
+a[] = {0,3,1,2}
+Output: 
-1 +Explanation:
There is no repeating element in the array. Therefore output is -1.
+

Example 2:

+
Input:
+N = 5
+a[] = {2,3,1,2,3}
+Output: 
2 3  +Explanation:
2 and 3 occur more than once in the given array.
+

Your Task:
Complete the function duplicates() which takes array a[] and n as input as parameters and returns a list of elements that occur more than once in the given array in a sorted manner. 

+

Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).

+

Constraints:
1 <= N <= 105
0 <= A[i] <= N-1, for each valid i

\ No newline at end of file diff --git a/Find duplicates in an array - GFG/find-duplicates-in-an-array.java b/Find duplicates in an array - GFG/find-duplicates-in-an-array.java new file mode 100644 index 00000000..e60293f5 --- /dev/null +++ b/Find duplicates in an array - GFG/find-duplicates-in-an-array.java @@ -0,0 +1,54 @@ +//{ Driver Code Starts +import java.io.*; +import java.util.*; +import java.util.Map.Entry; + +class GFG { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + while (t-- > 0) { + int n = sc.nextInt(); + int[] a = new int[n]; + for (int i = 0; i < n; i++) a[i] = sc.nextInt(); + Solution g = new Solution(); + ArrayList ans = g.duplicates(a, n); + for (Integer val : ans) System.out.print(val + " "); + System.out.println(); + } + } +} + +// } Driver Code Ends + + +class Solution { + public static ArrayList duplicates(int arr[], int n) { + // code here + + Map mp = new TreeMap(); + + for(int i = 0; i < n; ++i) + { + if(mp.containsKey(arr[i])) + { + mp.put(arr[i], mp.get(arr[i]) + 1); + } + else + mp.put(arr[i], 1); + } + + ArrayList ans = new ArrayList(); + + for(Map.Entry ele : mp.entrySet()) + { + if(ele.getValue() > 1) + ans.add(ele.getKey()); + } + + if(ans.isEmpty()) + ans.add(-1); + + return ans; + } +} diff --git a/Find first set bit - GFG/find-first-set-bit.cpp b/Find first set bit - GFG/find-first-set-bit.cpp new file mode 100644 index 00000000..1bcfc21c --- /dev/null +++ b/Find first set bit - GFG/find-first-set-bit.cpp @@ -0,0 +1,54 @@ +//{ Driver Code Starts +//Initial Template for C++ + + +#include +using namespace std; + + +// } Driver Code Ends +//User function Template for C++ + +class Solution +{ + public: + //Function to find position of first set bit in the given number. + unsigned int getFirstSetBit(int n) + { + // Your code here + + int posFromRight = 0; + + while(n > 0) + { + ++posFromRight; + + if(n&1) + return posFromRight; + + n/=2; + + } + + return posFromRight; + } +}; + +//{ Driver Code Starts. + +// Driver code +int main() +{ + int t; + cin>>t; // testcases + while(t--) + { + int n; + cin>>n; //input n + Solution ob; + printf("%u\n", ob.getFirstSetBit(n)); // function to get answer + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Find kth element of spiral matrix - GFG/README.md b/Find kth element of spiral matrix - GFG/README.md new file mode 100644 index 00000000..a3977203 --- /dev/null +++ b/Find kth element of spiral matrix - GFG/README.md @@ -0,0 +1,26 @@ +# Find kth element of spiral matrix +## Medium +

Given a matrix with n rows and m columns. Your task is to find the kth element which is obtained while traversing the matrix spirally. You need to complete the method findK which takes four arguments the first argument is the matrix A and the next two arguments will be n and m denoting the size of the matrix A and then the forth argument is an integer k. The function will return the kth element obtained while traversing the matrix spirally.

+

Example 1:

+
Input:
+n = 4, m = 4, k = 10
+A[][] = {{1  2  3  4},
+         {5  6  7  8},
+         {9  10 11 12},
{13 14 15 16}} +Output: +13 +Explanation:
+The spiral order of matrix will look like 1->2->3->4->8->12->16->15->14->13->9->5->6->7->11->10. So the 10th element in this order is 13.
+

Example 2:

+
Input:
+n = 3, m = 3, k = 4
+A[][] = {{1 2 3},
+         {4 5 6},
+         {7 8 9}}
+Output:
+6
+Explanation:
+The spiral order of matrix will look like 1->2->3->6->9->8->7->4->5. So the 4th element in this order is 6.
+

Your Task:
You only need to implement the given function findK(). Do not read input, instead use the arguments given in the function. Return the K'th element obtained by traversing matrix spirally.

+

Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n*m)

+

Constraints:
1<=n,m<=103
1<=k<=n*m

\ No newline at end of file diff --git a/Find kth element of spiral matrix - GFG/find-kth-element-of-spiral-matrix.java b/Find kth element of spiral matrix - GFG/find-kth-element-of-spiral-matrix.java new file mode 100644 index 00000000..3f1fbb07 --- /dev/null +++ b/Find kth element of spiral matrix - GFG/find-kth-element-of-spiral-matrix.java @@ -0,0 +1,74 @@ +//{ Driver Code Starts +import java.util.*; + +class Find_Given_Element_Of_Spiral_Matrix +{ + public static void main(String args[]) + { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + while(t > 0) + { + int n = sc.nextInt(); + int m = sc.nextInt(); + int k = sc.nextInt(); + int arr[][] = new int[1000][1000]; + for(int i=0; i v = new ArrayList<>(); + + while(top <= bottom && left <= right) + { + for(int i = left; i <= right; ++i) + { + v.add(A[top][i]); + } + ++top; + + for(int i = top; i <= bottom; ++i) + { + v.add(A[i][right]); + } + --right; + + for(int i = right; i >= left; --i) + { + v.add(A[bottom][i]); + } + --bottom; + for(int i = bottom; i >= top; --i) + { + v.add(A[i][left]); + } + ++left; + + } + + // for(int i = 0; i < v.size(); ++i) + // System.out.println(v.get(i)); + + return v.get(k-1); + } +} \ No newline at end of file diff --git a/Find triplets with zero sum - GFG/README.md b/Find triplets with zero sum - GFG/README.md new file mode 100644 index 00000000..f9e99296 --- /dev/null +++ b/Find triplets with zero sum - GFG/README.md @@ -0,0 +1,14 @@ +# Find triplets with zero sum +## Easy +

Given an array arr[] of n integers. Check whether it contains a triplet that sums up to zero. 

+

Note: Return 1, if there is at least one triplet following the condition else return 0.

+

Example 1:

+
Input: n = 5, arr[] = {0, -1, 2, -3, 1}
+Output: 1
+Explanation: 0, -1 and 1 forms a triplet
+with sum equal to 0.
+

Example 2:

+
Input: n = 3, arr[] = {1, 2, 3}
+Output: 0
+Explanation: No triplet with zero sum exists. 
+


Your Task:
You don't need to read input or print anything. Your task is to complete the boolean function findTriplets() which takes the array arr[] and the size of the array (n) as inputs and print 1 if the function returns true else print 0 if the function returns false. 

Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(1)

Constrains:
1 <= n <= 104

-106 <= Ai <= 106

\ No newline at end of file diff --git a/Find triplets with zero sum - GFG/find-triplets-with-zero-sum.java b/Find triplets with zero sum - GFG/find-triplets-with-zero-sum.java new file mode 100644 index 00000000..ba976361 --- /dev/null +++ b/Find triplets with zero sum - GFG/find-triplets-with-zero-sum.java @@ -0,0 +1,58 @@ +//{ Driver Code Starts +import java.util.*; +class Triplets{ + public static void main(String[] args){ + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(); + while(t-->0){ + int n=sc.nextInt(); + int[] a=new int[n]; + for(int i=0;i

Given a sorted array arr containing n elements with possibly duplicate is to find indexes of first elements, the task is to find the first and last occurrences of an element x in the given array.
Note: If the number x is not found in the array then return both the indices as -1.

+

Example 1:

+
Input:
+n=9, x=5
+arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
+Output:  
2 5 +Explanation:
First occurrence of 5 is at index 2 and last occurrence of 5 is at index 5. +
+

Example 2:

+
Input:
+n=9, x=7
+arr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }
+Output:  
6 6
Explanation:
First and last occurrence of 7 is at index 6. +
+

Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function find() that takes array arr, integer n and integer x as parameters and returns the required answer.

+

Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1).

+

Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i],x ≤ 109

\ No newline at end of file diff --git a/First and last occurrences of x - GFG/first-and-last-occurrences-of-x.cpp b/First and last occurrences of x - GFG/first-and-last-occurrences-of-x.cpp new file mode 100644 index 00000000..e85b429f --- /dev/null +++ b/First and last occurrences of x - GFG/first-and-last-occurrences-of-x.cpp @@ -0,0 +1,54 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution +{ + public: + vector find(int arr[], int n , int x ) + { + // code here + + int idx1 = lower_bound(arr,arr+n, x) - arr; + int idx2 = lower_bound(arr, arr+n,x+1) - arr; + + bool ok = false, ok2 = false; + + if(idx1 >= 0 and idx1 < n and arr[idx1] == x) + ok = true; + if(idx2-1 >= 0 and idx2-1 < n and arr[idx2-1] == x) + ok2 = true; + + // cout<>t; + while(t--) + { + int n,x; + cin>>n>>x; + int arr[n],i; + for(i=0;i>arr[i]; + vector ans; + Solution ob; + ans=ob.find(arr,n,x); + cout<

Given an input stream A of n characters consisting only of lower case alphabets. While reading characters from the stream, you have to tell which character has appeared only once in the stream upto that point. If there are many characters that have appeared only once, you have to tell which one of them was the first one to appear. If there is no such character then append '#' to the answer.
 

+

Example 1:

+
Input: A = "aabc"
+Output: "a#bb"
+Explanation: For every character first non
+repeating character is as follow-
+"a" - first non-repeating character is 'a'
+"aa" - no non-repeating character so '#'
+"aab" - first non-repeating character is 'b'
+"aabc" - first non-repeating character is 'b'
+
+

Example 2:

+
Input: A = "zz"
+Output: "z#"
+Explanation: For every character first non
+repeating character is as follow-
+"z" - first non-repeating character is 'z'
+"zz" - no non-repeating character so '#'
+
+

 

+

Your Task:
You don't need to read or print anything. Your task is to complete the function FirstNonRepeating() which takes A as input parameter and returns a string after processing the input stream.

 

+

Expected Time Complexity: O(n)
Expected Space Complexity: O(n)

 

+

Constraints:
1 <= n <= 105

\ No newline at end of file diff --git a/First non-repeating character in a stream - GFG/first-nonrepeating-character-in-a-stream.cpp b/First non-repeating character in a stream - GFG/first-nonrepeating-character-in-a-stream.cpp new file mode 100644 index 00000000..78d118e1 --- /dev/null +++ b/First non-repeating character in a stream - GFG/first-nonrepeating-character-in-a-stream.cpp @@ -0,0 +1,65 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + string FirstNonRepeating(string A){ + // Code here + + int n = A.size(); + + vector v(26,0), first(26,n+1); + + string ans; + + for(int i = 0; i < n; ++i) + { + ++v[A[i] - 'a']; + + if(first[A[i] - 'a'] == n+1) + first[A[i] - 'a'] = i; + + bool ok = false; + int mini = n+1; + char ch = '#'; + + for(int j = 0; j < 26; ++j) + { + if(v[j] == 1) + { + ok = true; + if(first[j] < mini) + { + mini = first[j]; + ch = A[mini]; + } + } + } + + if(ok) + ans += ch; + else + ans += ch; + } + + return ans; + } + +}; + +//{ Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + string A; + cin >> A; + Solution obj; + string ans = obj.FirstNonRepeating(A); + cout << ans << "\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Flip Bits - GFG/README.md b/Flip Bits - GFG/README.md new file mode 100644 index 00000000..760ef31a --- /dev/null +++ b/Flip Bits - GFG/README.md @@ -0,0 +1,28 @@ +# Flip Bits +## Easy +

Given an array A[] consisting of 0’s and 1’s. A flip operation is one in which you turn 1 into 0 and a 0 into 1. You have to do at most one “Flip” operation of any subarray. Formally, select a range (l, r) in the array A[], such that (0 ≤ l ≤ r < n) holds and flip the elements in this range to get the maximum ones in the final array. You can possibly make zero operations to get the answer.

+

Example 1:

+
Input:
+N = 5
+A[] = {1, 0, 0, 1, 0} 
+Output:
+4
+Explanation:
+We can perform a flip operation in the range [1,2]
+After flip operation array is : [ 1 1 1 1 0 ]
+Count of one after fliping is : 4
+[Note: the subarray marked in bold is the flipped subarray]
+

Example 2:

+
Input:
+N = 7
+A[] = {1, 0, 0, 1, 0, 0, 1}
+Output:
+6
+Explanation:
+We can perform a flip operation in the range [1,5]
+After flip operation array is : [ 1 1 1 0 1 1 1]
+Count of one after fliping is : 6
+[Note: the subarray marked in bold is the flipped subarray]
+

Your Task:  
You don't need to read input or print anything. Your task is to complete the function maxOnes() which takes the array A[] and its size N as inputs and returns the maximum number of 1's you can have in the array after atmost one flip operation.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 ≤ N ≤ 106
0 ≤ A[i] ≤ 1

\ No newline at end of file diff --git a/Flip Bits - GFG/flip-bits.cpp b/Flip Bits - GFG/flip-bits.cpp new file mode 100644 index 00000000..e9a780b5 --- /dev/null +++ b/Flip Bits - GFG/flip-bits.cpp @@ -0,0 +1,63 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + + +class Solution{ + public: + int maxOnes(int a[], int n) + { + // Your code goes here + + int cnt = 0; + + for(int i = 0; i < n; ++i) + { + if(a[i] == 1) + { + a[i] = -1; + ++cnt; + } + else + { + a[i] = 1; + } + } + + int ans = 0, sum = 0; + + for(int i = 0; i < n; ++i) + { + sum += a[i]; + + ans = max(ans, sum); + + if(sum < 0) + sum = 0; + } + + return ans + cnt; + } +}; + + +//{ Driver Code Starts. +int main() +{ + int t; cin>>t; + while(t--) + { + int n; + cin>>n; + int a[n+5]; + for(int i=0;i>a[i]; + Solution ob; + cout<< ob.maxOnes(a, n) <

You will be given an array arr of integers of length N. You can construct an integer from two integers by treating the integers as strings, and then concatenating them. For example, 19 and 4 can be used to construct 194 and 419.

+

The task is to find whether it’s possible to construct an integer using all the digits of these numbers such that it would be divisible by 3.
If it is possible then print 1 and if not print 0.

+

Example 1:

+
Input: N = 3
+arr = {40, 50, 90}
+Output: 1
+Explanation: One such number is 405090.
+

Example 2:

+
Input: N = 2
+arr = {1, 4}
+Output: 0
+Explanation: The numbers we can form 
+are 14 and 41. But neither of them are 
+divisible by 3.
+

Your Task:
You do not need to read input or print anything. Your task is to complete the function isPossible() which takes N and arr as input parameters and returns 1 if we can form a number by the digits of the given number, that would be divisible by 3, otherwise returns 0.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 ≤ N, arr[i] ≤ 105

\ No newline at end of file diff --git a/Form a number divisible by 3 using array digits - GFG/form-a-number-divisible-by-3-using-array-digits.cpp b/Form a number divisible by 3 using array digits - GFG/form-a-number-divisible-by-3-using-array-digits.cpp new file mode 100644 index 00000000..50b25f4d --- /dev/null +++ b/Form a number divisible by 3 using array digits - GFG/form-a-number-divisible-by-3-using-array-digits.cpp @@ -0,0 +1,42 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + int isPossible(int N, int arr[]) { + // code here + + int sum = 0; + + for(int i = 0; i < N; ++i) + { + sum += (arr[i] % 3); + } + + return (sum % 3 == 0 ? 1 : 0); + } +}; + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int N; + cin >> N; + int arr[N]; + for (int i = 0; i < N; i++) cin >> arr[i]; + + Solution ob; + cout << ob.isPossible(N, arr) << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Fraction pairs with sum 1 - GFG/README.md b/Fraction pairs with sum 1 - GFG/README.md new file mode 100644 index 00000000..72b810f0 --- /dev/null +++ b/Fraction pairs with sum 1 - GFG/README.md @@ -0,0 +1,15 @@ +# Fraction pairs with sum 1 +## Medium +

Given a list of N fractions, represented as two lists numerator and denominator, the task is to determine the count of pairs of fractions whose sum equals 1.

+

Example 1:

+
Input:
N = 4
numerator = [1, 2, 2, 8]
denominator = [2, 4, 6, 12]
Output: +2 +Explanation:
Fractions 1/2 and 2/4 sum to 1. Similarly fractions 2/6 and 8/12 sum to 1. So there are 2 pairs of fractions which sum to 1. +
+

Example 2:

+
Input:
N = 5
numerator = [3, 1, 12, 81, 2]
denominator = [9, 10, 18, 90, 5]
Output: +2 +Explanation:
Fractions 3/9 and 12/18 sum to 1. Similarly fractions 1/10 and 81/90 sum to 1. So there are 2 pairs of fractions which sum to 1.
+

Your task:
You don't need to read input or print anything. Your task is to complete the function countFractions() which take integer N and arrays numerator 
and denominator of size N as arguments, and returns an integer.

+

Expected Time Complexity: O(N*log(N))
Expected Auxiliary Space: O(N)

+

Constraints:
1 <= N <=105
1 <= numerator[i] <= denominator[i] <= 109

\ No newline at end of file diff --git a/Fraction pairs with sum 1 - GFG/fraction-pairs-with-sum-1.cpp b/Fraction pairs with sum 1 - GFG/fraction-pairs-with-sum-1.cpp new file mode 100644 index 00000000..af8fdaab --- /dev/null +++ b/Fraction pairs with sum 1 - GFG/fraction-pairs-with-sum-1.cpp @@ -0,0 +1,55 @@ +//{ Driver Code Starts +//Initial Template for C++ +#include +using namespace std; + +// } Driver Code Ends +//User function Template for C++ +class Solution +{ + public: + int countFractions(int n, int numerator[], int denominator[]) + { + unordered_map mp; + + int cnt = 0; + + for(int i = 0; i < n; ++i){ + float a = (float)numerator[i]/(float)denominator[i]; + + float b = (float)(denominator[i] - numerator[i])/(float)denominator[i]; + + if(mp[b]) + cnt += mp[b]; + + // cout<>t; + while(t--) + { + int n; + cin>>n; + int numerator[n],denominator[n]; + for(int i=0;i>numerator[i]; + for(int i=0;i>denominator[i]; + Solution ob; + int ans=ob.countFractions(n,numerator,denominator); + cout<

Given a binary tree, find its height.

+

Example 1:

+
Input:
+     1
+    /  \
+   2    3
+Output: 2
+
+

Example 2:

+
Input:
+  2
+   \
+    1
+   /
+ 3
+Output: 3   
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function height() which takes root node of the tree as input parameter and returns an integer denoting the height of the tree. If the tree is empty, return 0. 

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

+

Constraints:
1 <= Number of nodes <= 105
1 <= Data of a node <= 109

\ No newline at end of file diff --git a/Height of Binary Tree - GFG/height-of-binary-tree.cpp b/Height of Binary Tree - GFG/height-of-binary-tree.cpp new file mode 100644 index 00000000..325faf43 --- /dev/null +++ b/Height of Binary Tree - GFG/height-of-binary-tree.cpp @@ -0,0 +1,127 @@ +//{ Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left; + struct Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current Node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + +// } Driver Code Ends +//User function template for C++ + +/* +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; +*/ +class Solution{ + public: + //Function to find the height of a binary tree. + int height(struct Node* node){ + // code here + + if(!node) + return 0; + + return 1 + max(height(node->left), height(node->right)); + } +}; + +//{ Driver Code Starts. +int main() +{ + int t; + scanf("%d ",&t); + while(t--) + { + string treeString; + getline(cin,treeString); + Node* root = buildTree(treeString); + Solution ob; + cout<

Your task is to implement  2 stacks in one array efficiently. You need to implement 4 methods.
push1 : pushes element into first stack.
push2 : pushes element into second stack.
pop1 : pops element from first stack and returns the popped element. If first stack is empty, it should return -1.
pop2 : pops element from second stack and returns the popped element. If second stack is empty, it should return -1.

+

Example 1:

+
Input:
+push1(2)
+push1(3)
+push2(4)
+pop1()
+pop2()
+pop2()
+Output:
+3 4 -1
+Explanation:
+push1(2) the stack1 will be {2}
+push1(3) the stack1 will be {2,3}
+push2(4) the stack2 will be {4}
+pop1()   the poped element will be 3 from stack1 and stack1 will be {2}
+pop2()   the poped element will be 4 from stack2 and now stack2 is empty
+pop2()   the stack2 is now empty hence returned -1.
+

Example 2:

+
Input:
+push1(1)
+push2(2)
pop1() +push1(3) +pop1() +pop1() +Output: +3 1 -1 +Explanation: +push1(1) the stack1 will be {1} +push2(2) the stack2 will be {2}
pop1() the poped element will be 1 from stack1 and stack1 will be empty
push1(3) the stack1 will be {3} +pop1()   the poped element will be 3 from stack1 and stack1 will be empty
pop1()  the stack1 is now empty hence returned -1.
+

Your Task:
You don't need to read input or print anything. You are required to complete the 4 methods push1, push2 which takes one argument an integer 'x' to be pushed into stack one and two and pop1, pop2 which returns the integer poped out from stack one and two. If no integer is present in the stack return -1.

+

Expected Time Complexity: O(1) for all the four methods.
Expected Auxiliary Space: O(1) for all the four methods.

+

Constraints:
1 <= Number of queries <= 104
1 <= Number of elements in the stack
<= 100
The sum of elements in both the stacks < size of the given array

\ No newline at end of file diff --git a/Implement two stacks in an array - GFG/implement-two-stacks-in-an-array.cpp b/Implement two stacks in an array - GFG/implement-two-stacks-in-an-array.cpp new file mode 100644 index 00000000..c0c0fe42 --- /dev/null +++ b/Implement two stacks in an array - GFG/implement-two-stacks-in-an-array.cpp @@ -0,0 +1,106 @@ +//{ Driver Code Starts +#include + +using namespace std; + + +// } Driver Code Ends + + +class twoStacks +{ + int *arr; + int size; + int top1, top2; + public: + + twoStacks(int n=100) + { + size = n; + arr = new int[n]; + top1 = -1; + top2 = size; + } + + //Function to push an integer into the stack1. + void push1(int x) + { + if(top1 + 1 < top2) + arr[++top1] = x; + } + + //Function to push an integer into the stack2. + void push2(int x) + { + if(top2-1 > top1) + arr[--top2] = x; + } + + //Function to remove an element from top of the stack1. + int pop1() + { + if(top1 < 0) + return -1; + + int val = arr[top1]; + --top1; + + return val; + + } + + //Function to remove an element from top of the stack2. + int pop2() + { + if(top2>=size) + return -1; + + int val = arr[top2]; + ++top2; + + return val; + } +}; + + + +//{ Driver Code Starts. + +int main() +{ + + int T; + cin>>T; + while(T--) + { + twoStacks *sq = new twoStacks(); + + int Q; + cin>>Q; + while(Q--){ + int stack_no; + cin>>stack_no; + int QueryType=0; + cin>>QueryType; + + if(QueryType==1) + { + int a; + cin>>a; + if(stack_no ==1) + sq->push1(a); + else if(stack_no==2) + sq->push2(a); + }else if(QueryType==2){ + if(stack_no==1) + cout<pop1()<<" "; + else if(stack_no==2) + cout<pop2()<<" "; + + } + } + cout<0) + { + twoStacks g = new twoStacks(); + int Q = sc.nextInt(); + while(Q>0) + { + int stack_no = sc.nextInt(); + int QueryType = sc.nextInt(); + + + if(QueryType == 1) + { + int a = sc.nextInt(); + if(stack_no == 1) + g.push1(a); + else if(stack_no ==2) + g.push2(a); + }else if(QueryType == 2) + { + if(stack_no==1) + System.out.print(g.pop1()+" "); + else if(stack_no==2) + System.out.print(g.pop2()+" "); + } + + Q--; + } + System.out.println(); + T--; + } + } +} + + +// } Driver Code Ends + + + +class twoStacks +{ + int arr[]; + int size; + int top1, top2; + twoStacks() + { + size = 100; + arr = new int[100]; + top1 = -1; + top2 = size; + } + //Function to push an integer into the stack1. + void push1(int x) + { + if(top1 + 1 < top2) + { + arr[++top1] = x; + } + } + //Function to push an integer into the stack2. + void push2(int x) + { + if(top2 - 1 > top1) + arr[--top2] = x; + } + //Function to remove an element from top of the stack1. + int pop1() + { + if(top1 <= -1) + return -1; + + int val = arr[top1]; + --top1; + + return val; + } + //Function to remove an element from top of the stack2. + int pop2() + { + if(top2 >= size) + return -1; + + int val = arr[top2]; + ++top2; + + return val; + } +} + diff --git a/Insert in a Sorted List - GFG/README.md b/Insert in a Sorted List - GFG/README.md new file mode 100644 index 00000000..61d4403b --- /dev/null +++ b/Insert in a Sorted List - GFG/README.md @@ -0,0 +1,16 @@ +# Insert in a Sorted List +## Easy +

Given a linked list sorted in ascending order and an integer called data, insert data in the linked list such that the list remains sorted.

+

Example 1:

+
Input:
+LinkedList: 25->36->47->58->69->80
+data: 19
+Output: 
19 25 36 47 58 69 80
Explanation:

After inserting 19 the sorted linked list will look like the one in the output.
+

Example 2:

+
Input:
+LinkedList: 50->100
+data: 75
+Output: 
50 75 100
Explanation:
After inserting 75 the sorted linked list will look like the one in the output.
+

Your Task:
The task is to complete the function sortedInsert() which should insert the element in sorted Linked List and return the head of the linked list

+

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

+

Constraints:
1 <= N <= 104
-99999 <= A[i] <= 99999, for each valid i

\ No newline at end of file diff --git a/Insert in a Sorted List - GFG/insert-in-a-sorted-list.cpp b/Insert in a Sorted List - GFG/insert-in-a-sorted-list.cpp new file mode 100644 index 00000000..2f15ec45 --- /dev/null +++ b/Insert in a Sorted List - GFG/insert-in-a-sorted-list.cpp @@ -0,0 +1,114 @@ +//{ Driver Code Starts +// + +#include +using namespace std; + +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; + + +void printList(Node* node) +{ + while (node != NULL) { + cout << node->data <<" "; + node = node->next; + } + cout<<"\n"; +} + +// } Driver Code Ends +/* +structure of the node of the list is as +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; +*/ + +class Solution{ + public: + // Should return head of the modified linked list + Node *sortedInsert(struct Node* head, int data) { + // Code + + + Node* newNode = new Node(data); + + Node* prev = nullptr, *temp = head; + + if(data <= temp->data) + { + newNode->next = head; + return newNode; + } + + while(temp) + { + if(temp->data >= data) + { + prev->next = newNode; + newNode->next = temp; + break; + } + prev = temp; + temp = temp->next; + } + + if(prev->data < data) + { + prev->next = newNode; + } + + return head; + + } +}; + + +//{ Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + + int data; + cin>>data; + + struct Node *head = new Node(data); + struct Node *tail = head; + for (int i = 0; i < n-1; ++i) + { + cin>>data; + tail->next = new Node(data); + tail = tail->next; + } + + int k; + cin>>k; + Solution obj; + head = obj.sortedInsert(head,k); + printList(head); + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Knapsack with Duplicate Items - GFG/README.md b/Knapsack with Duplicate Items - GFG/README.md new file mode 100644 index 00000000..07f5effd --- /dev/null +++ b/Knapsack with Duplicate Items - GFG/README.md @@ -0,0 +1,21 @@ +# Knapsack with Duplicate Items +## Medium +

Given a set of N items, each with a weight and a value, represented by the array w and val respectively. Also, a knapsack with weight limit W.
The task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.
Note: Each item can be taken any number of times.

+

Example 1:

+
Input: 
N = 2
W = 3 +val = {1, 1} +wt = {2, 1} +Output:
3 +Explanation: +1.Pick the 2nd element thrice. +2.Total profit = 1 + 1 + 1 = 3. Also the total weight = 1 + 1 + 1 = 3 which is <= 3.
+
+

Example 2:

+
Input: 
N = 4
W = 8 +val[] = {6, 1, 7, 7} +wt[] = {1, 3, 4, 5} +Output:
48 +Explanation:
The optimal choice is to pick the 1st element 8 times.
+

Your Task:
You do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and the arrays val and wt as input parameters and returns the maximum possible value.

+

Expected Time Complexity: O(N*W)
Expected Auxiliary Space: O(W)

+

Constraints:
1 ≤ N, W ≤ 1000
1 ≤ val[i], wt[i] ≤ 100

\ No newline at end of file diff --git a/Knapsack with Duplicate Items - GFG/knapsack-with-duplicate-items.cpp b/Knapsack with Duplicate Items - GFG/knapsack-with-duplicate-items.cpp new file mode 100644 index 00000000..d158438b --- /dev/null +++ b/Knapsack with Duplicate Items - GFG/knapsack-with-duplicate-items.cpp @@ -0,0 +1,60 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + + int helper(int idx, int n, int W, int val[], int wt[], vector>& dp) + { + if(idx == n) + return 0; + + if(dp[idx][W] != -1) + return dp[idx][W]; + + int notTake = helper(idx+1, n, W, val, wt, dp); + + int take = 0; + + if(wt[idx] <= W) + take = val[idx] + helper(idx, n, W - wt[idx], val, wt, dp); + + return dp[idx][W] = max(take, notTake); + } + + int knapSack(int N, int W, int val[], int wt[]) + { + // code here + + vector> dp(N+1, vector(W+1, -1)); + + return helper(0, N, W, val, wt, dp); + } +}; + +//{ Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N, W; + cin>>N>>W; + int val[N], wt[N]; + for(int i = 0;i < N;i++) + cin>>val[i]; + for(int i = 0;i < N;i++) + cin>>wt[i]; + + Solution ob; + cout<

Given a binary tree of size  N, a node, and a positive integer k., Your task is to complete the function kthAncestor(), the function should return the kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1.
Note: It is guaranteed that the node exists in the tree.

+

Example 1:

+

+
+Input:
+K = 2 Node = 4
+Output: 1
+Explanation:
+Since, K is 2 and node is 4, so we
+first need to locate the node and
+look k times its ancestors.
+Here in this Case node 4 has 1 as his
+2nd Ancestor aka the Root of the tree.
+

Example 2:

+
Input:
+k=1 
+node=3
+      1
+    /   \
+    2     3
+
+Output:
+1
+Explanation:
+K=1 and node=3 ,Kth ancestor of node 3 is 1.
+

Your Task:
You are asked to complete the function kthAncestor() which accepts root of the tree, k and node as input parameters, and returns the kth ancestor of Node which contains node as its value.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

+

Constraints:
1<=N<=105
1<= K <= 100
1 <= Node.data <= N

\ No newline at end of file diff --git a/Kth Ancestor in a Tree - GFG/kth-ancestor-in-a-tree.cpp b/Kth Ancestor in a Tree - GFG/kth-ancestor-in-a-tree.cpp new file mode 100644 index 00000000..5d60c091 --- /dev/null +++ b/Kth Ancestor in a Tree - GFG/kth-ancestor-in-a-tree.cpp @@ -0,0 +1,152 @@ +//{ Driver Code Starts +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left; + struct Node *right; +}; +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} +int kthAncestor(Node *root, int k, int node); + +int main() +{ + int t; + scanf("%d ",&t); + while(t--) + { + int k , node; + scanf("%d ",&k); + scanf("%d ",&node); + string s; + getline(cin,s); + Node* root = buildTree(s); + cout<data == node) + return 0; + + int left = helper(root->left, k , node, ans); + int right = helper(root->right, k, node, ans); + + if(left != -1 and right == -1) + { + if(left + 1 == k) + ans = root->data; + return left + 1; + } + + if(left == -1 and right != -1) + { + if(right + 1 == k) + ans = root->data; + return right + 1; + } + + return -1; +} + +int kthAncestor(Node *root, int k, int node) +{ + // Code here + int ans = -1; + + helper(root, k , node, ans); + + return ans; +} diff --git a/Largest number possible - GFG/README.md b/Largest number possible - GFG/README.md new file mode 100644 index 00000000..eb5566b9 --- /dev/null +++ b/Largest number possible - GFG/README.md @@ -0,0 +1,16 @@ +# Largest number possible +## Easy +

Given two numbers 'N' and 'S' , find the largest number that can be formed with 'N' digits and whose sum of digits should be equals to 'S'. Return -1 if it is not possible.

+

Example 1:

+
Input: N = 2, S = 9
+Output: 90
+Explaination: It is the biggest number 
+with sum of digits equals to 9.
+

Example 2:

+
Input: N = 3, S = 20
+Output: 992
+Explaination: It is the biggest number 
+with sum of digits equals to 20.
+

Your Task:
You do not need to read input or print anything. Your task is to complete the function findLargest() which takes N and S as input parameters and returns the largest possible number. Return -1 if no such number is possible.

+

Expected Time Complexity: O(N)
Exepcted Auxiliary Space: O(1)

+

Constraints:
1 ≤ N ≤ 104
0 ≤ S ≤ 105

\ No newline at end of file diff --git a/Largest number possible - GFG/largest-number-possible.cpp b/Largest number possible - GFG/largest-number-possible.cpp new file mode 100644 index 00000000..b8408e03 --- /dev/null +++ b/Largest number possible - GFG/largest-number-possible.cpp @@ -0,0 +1,52 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: + string findLargest(int N, int sum){ + // code here + + string ans=""; + if( N>1 && sum==0) return "-1"; + + for(int i=0 ;i= 0 ){ + ans.push_back('9'); + sum-=9; + } + else if( sum ==0 ){ + ans.push_back('0') ; + } + else{ + ans += to_string(sum); + sum=0; + } + } + + if(sum==0) return ans; + return "-1"; + } +}; + +//{ Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N, S; + cin>>N>>S; + + Solution ob; + cout<

Given a number N, the task is to find the largest prime factor of that number.
 Example 1:

+
Input:
+N = 5
+Output:
+5
+Explanation:
+5 has 1 prime factor i.e 5 only.
+
+

Example 2:

+
Input:
+N = 24
+Output:
+3
+Explanation:
+24 has 2 prime factors 2 and 3 in which 3 is greater.
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function largestPrimeFactor() which takes an integer N as input parameters and returns an integer, largest prime factor of N.

+

Expected Time Complexity: O(sqrt(N))
Expected Space Complexity: O(1)

+

Constraints:
2 <= N <= 109

\ No newline at end of file diff --git a/Largest prime factor - GFG/largest-prime-factor.cpp b/Largest prime factor - GFG/largest-prime-factor.cpp new file mode 100644 index 00000000..30fefee6 --- /dev/null +++ b/Largest prime factor - GFG/largest-prime-factor.cpp @@ -0,0 +1,50 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ +public: + long long int largestPrimeFactor(int N){ + // code here + + int ans; + + for(int i = 2; i * i <= N; ++i) + { + if(N % i == 0) + { + ans = i; + + while((N % i) == 0) + { + N /= i; + } + } + } + + + if(N > 1) + { + ans = max(ans, N); + } + + return ans; + } +}; + +//{ Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int N; + cin>>N; + Solution ob; + cout << ob.largestPrimeFactor(N) << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Leaders in an array - GFG/README.md b/Leaders in an array - GFG/README.md new file mode 100644 index 00000000..8288b29c --- /dev/null +++ b/Leaders in an array - GFG/README.md @@ -0,0 +1,23 @@ +# Leaders in an array +## Easy +

Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. 

+

Example 1:

+
Input:
+n = 6
+A[] = {16,17,4,3,5,2}
+Output: 17 5 2
+Explanation: The first leader is 17 
+as it is greater than all the elements
+to its right.  Similarly, the next 
+leader is 5. The right most element 
+is always a leader so it is also 
+included.
+
+

Example 2:

+
Input:
+n = 5
+A[] = {1,2,3,4,0}
+Output: 4 0
Explanation: 0 is the rightmost element
and 4 is the only element which is greater
than all the elements to its right.
+

Your Task:
You don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance.

+

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)

+

Constraints:
1 <= n <= 107
0 <= Ai <= 107

\ No newline at end of file diff --git a/Leaders in an array - GFG/leaders-in-an-array.cpp b/Leaders in an array - GFG/leaders-in-an-array.cpp new file mode 100644 index 00000000..a24c600e --- /dev/null +++ b/Leaders in an array - GFG/leaders-in-an-array.cpp @@ -0,0 +1,65 @@ +//{ Driver Code Starts +// C++ program to remove recurring digits from +// a given number +#include +using namespace std; + + +// } Driver Code Ends + + +class Solution{ + //Function to find the leaders in the array. + public: + vector leaders(int a[], int n){ + // Code here + + int maxi = a[n-1]; + + vector v; + + for(int i = n-1; i >= 0; --i) + { + if(a[i] >= maxi) + v.push_back(a[i]); + maxi = max(a[i], maxi); + } + + reverse(v.begin(), v.end()); + + return v; + } +}; + +//{ Driver Code Starts. + +int main() +{ + long long t; + cin >> t;//testcases + while (t--) + { + long long n; + cin >> n;//total size of array + + int a[n]; + + //inserting elements in the array + for(long long i =0;i> a[i]; + } + Solution obj; + //calling leaders() function + vector v = obj.leaders(a, n); + + //printing elements of the vector + for(auto it = v.begin();it!=v.end();it++){ + cout << *it << " "; + } + + cout << endl; + + } +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Leaf under budget - GFG/README.md b/Leaf under budget - GFG/README.md new file mode 100644 index 00000000..b6c78481 --- /dev/null +++ b/Leaf under budget - GFG/README.md @@ -0,0 +1,32 @@ +# Leaf under budget +## Easy +

Given a binary tree and a budget. Assume you are at the root of the tree(level 1), you need to maximise the count of leaf nodes you can visit in your budget if the cost of visiting a leaf node is equal to the level of that leaf node.

+

Example 1:

+
Input: 
+                  10
+                /    \
+               8      2
+             /      /   \
+            3      3     6
+                    \
+                     4
+and budget = 8
+Output: 2
+Explanation:
+Cost For visiting Leaf Node 3: 3
+Cost For visiting Leaf Node 4: 4
+Cost For visiting Leaf Node 6: 3
+In budget 8 one can visit Max 2 Leaf Nodes.
+

Example 2:

+
Input: 
+         1
+       /   \
+      2     3
+     / \   / \
+    4   5 6   7
+and budget = 5
+Output: 1
Explanation: We can only visit either node 4 or 5.
+

Your Task:

+

You don't need to read input or print anything. Your task is to complete the function getCount() which takes root node of the tree and a integer denoting the budget as input parameters and returns an integer denoting the count of visited leaf nodes of the tree.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

+

Constraints:
1<=N<=105
1<=budget<=104

\ No newline at end of file diff --git a/Leaf under budget - GFG/leaf-under-budget.cpp b/Leaf under budget - GFG/leaf-under-budget.cpp new file mode 100644 index 00000000..ef9c38d3 --- /dev/null +++ b/Leaf under budget - GFG/leaf-under-budget.cpp @@ -0,0 +1,193 @@ +//{ Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left; + struct Node *right; + + Node(int x) + { + data = x; + left = NULL; + right = NULL; + } +}; + +void printInorder(Node *node) +{ + if (node == NULL) + { + return; + } + printInorder(node->left); + cout << node->data << " "; + printInorder(node->right); +} +Node *buildTree(string str) +{ + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) + { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") + { + + // Create the left child for the current Node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") + { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +// } Driver Code Ends +/* +struct Node +{ + int data; + struct Node *left; + struct Node *right; + + Node(int x) + { + data = x; + left = NULL; + right = NULL; + } +}; +*/ +class Solution +{ +public: + int getCount(Node *root, int k) + { + //code here + + map mp; + + queue q; + + q.push(root); + + int level = 1; + + while(!q.empty()) + { + int size = q.size(); + + for(int i = 0; i < size; ++i) + { + Node* curr = q.front(); + q.pop(); + + if(!curr->left and !curr->right) + { + ++mp[level]; + continue; + } + + if(curr->left) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + } + ++level; + } + + int leaf = 0; + + for(auto itr : mp) + { + if(itr.second * itr.first <= k) + { + leaf += itr.second; + k -= (itr.second * itr.first); + } + else{ + leaf += k/itr.first; + break; + } + } + + return leaf; + } +}; + +//{ Driver Code Starts. + +int main() +{ + int t; + scanf("%d", &t); + cin.ignore(); + while (t--) + { + string treeString; + getline(cin, treeString); + Node *root = buildTree(treeString); + int k; + cin >> k; + cin.ignore(); + Solution obj; + int res = obj.getCount(root, k); + cout << res << "\n"; + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Leftmost and rightmost nodes of binary tree - GFG/README.md b/Leftmost and rightmost nodes of binary tree - GFG/README.md new file mode 100644 index 00000000..60b2e632 --- /dev/null +++ b/Leftmost and rightmost nodes of binary tree - GFG/README.md @@ -0,0 +1,28 @@ +# Leftmost and rightmost nodes of binary tree +## Medium +

Given a Binary Tree of size N, Print the corner nodes ie- the node at the leftmost and rightmost of each level.

+

Example 1:

+
Input :
+         1
+       /  \
+     2      3
+    / \    / \
+   4   5  6   7    
+Output: 1 2 3 4 7
+Explanation:
+Corners at level 0: 1
+Corners at level 1: 2 3
+Corners at level 2: 4 7
+
+

Example 2:

+
Input:
+
+        10
+      /    \
+     20     30
+    / \  
+   40  60
+Output: 10 20 30 40 60
+

Your Task:  
You dont need to read input. Complete the function printCorner() which takes root node as input parameter and prints the corner nodes separated by spaces. The left corner should be printed before the right for each level starting from level 0.
Note: Don't print a new line after printing all the corner nodes.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(number of nodes in a level)

+

Constraints:
1 ≤ N ≤ 10^5

\ No newline at end of file diff --git a/Leftmost and rightmost nodes of binary tree - GFG/leftmost-and-rightmost-nodes-of-binary-tree.cpp b/Leftmost and rightmost nodes of binary tree - GFG/leftmost-and-rightmost-nodes-of-binary-tree.cpp new file mode 100644 index 00000000..4f1c0b18 --- /dev/null +++ b/Leftmost and rightmost nodes of binary tree - GFG/leftmost-and-rightmost-nodes-of-binary-tree.cpp @@ -0,0 +1,165 @@ +//{ Driver Code Starts +#include +using namespace std; +#define MAX_HEIGHT 100000 + +// Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; + +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + + +void printCorner(Node *root); + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + +int main() { + int t; + string tc; + getline(cin, tc); + t=stoi(tc); + while(t--) + { + string s ,ch; + getline(cin, s); + Node* root = buildTree(s); + + printCorner(root); + cout< q; + + q.push(root); + + cout<data<<' '; + + while(!q.empty()) + { + int size = q.size(); + + for(int i = 0; i < size; ++i) + { + Node* curr = q.front(); + q.pop(); + + if(curr->left) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + } + + if(q.size() == 1) + cout<data<<' '; + else if(q.size() >= 2) + cout<data <<' '<data<<' '; + } + +} \ No newline at end of file diff --git a/Level order traversal in spiral form - GFG/README.md b/Level order traversal in spiral form - GFG/README.md new file mode 100644 index 00000000..e58fd3f4 --- /dev/null +++ b/Level order traversal in spiral form - GFG/README.md @@ -0,0 +1,24 @@ +# Level order traversal in spiral form +## Easy +

Given a binary tree and the task is to find the spiral order traversal of the tree.

+

Spiral order Traversal mean: Starting from level 0 for root node, for all the even levels we print the node's value from right to left and for all the odd levels we print the node's value from left to right. 

+

For below tree, function should return 1, 2, 3, 4, 5, 6, 7.


 

 

+

Example 1:

+
Input:
+      1
+    /   \
+   3     2
+Output:1 3 2
+
+
+

Example 2:

+
Input:
+           10
+         /     \
+        20     30
+      /    \
+    40     60
+Output: 10 20 30 60 40 
+
+

Your Task:
The task is to complete the function findSpiral() which takes root node as input parameter and returns the elements in spiral form of level order traversal as a list. The newline is automatically appended by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

+

Constraints:
1 <= Number of nodes <= 105
0 <= Data of a node <= 105

\ No newline at end of file diff --git a/Level order traversal in spiral form - GFG/level-order-traversal-in-spiral-form.java b/Level order traversal in spiral form - GFG/level-order-traversal-in-spiral-form.java new file mode 100644 index 00000000..7afd39e1 --- /dev/null +++ b/Level order traversal in spiral form - GFG/level-order-traversal-in-spiral-form.java @@ -0,0 +1,191 @@ +//{ Driver Code Starts +//Initial Template for Java + + + +//Initial Template for Java + +//Contributed by Sudarshan Sharma +import java.util.LinkedList; +import java.util.Queue; +import java.io.*; +import java.util.*; + +class Node{ + int data; + Node left; + Node right; + Node(int data){ + this.data = data; + left=null; + right=null; + } +} + + +class GfG { + + static Node buildTree(String str){ + + if(str.length()==0 || str.charAt(0)=='N'){ + return null; + } + + String ip[] = str.split(" "); + // Create the root of the tree + Node root = new Node(Integer.parseInt(ip[0])); + // Push the root to the queue + + Queue queue = new LinkedList<>(); + + queue.add(root); + // Starting from the second element + + int i = 1; + while(queue.size()>0 && i < ip.length) { + + // Get and remove the front of the queue + Node currNode = queue.peek(); + queue.remove(); + + // Get the current node's value from the string + String currVal = ip[i]; + + // If the left child is not null + if(!currVal.equals("N")) { + + // Create the left child for the current node + currNode.left = new Node(Integer.parseInt(currVal)); + // Push it to the queue + queue.add(currNode.left); + } + + // For the right child + i++; + if(i >= ip.length) + break; + + currVal = ip[i]; + + // If the right child is not null + if(!currVal.equals("N")) { + + // Create the right child for the current node + currNode.right = new Node(Integer.parseInt(currVal)); + + // Push it to the queue + queue.add(currNode.right); + } + i++; + } + + return root; + } + void inOrder(Node node) { + if (node == null) { + return; + } + + inOrder(node.left); + System.out.print(node.data + " "); + + inOrder(node.right); + } + + public static void main (String[] args) throws IOException{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int t=Integer.parseInt(br.readLine()); + + while(t-- > 0){ + String s = br.readLine(); + Node root = buildTree(s); + Spiral g = new Spiral(); + ArrayList result = g.findSpiral(root); + for(int value : result) + System.out.print(value + " "); + System.out.println(); + + } + } +} + + + + +// } Driver Code Ends + + +//User function Template for Java + + +/* +// A Binary Tree node +class Node +{ + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} +*/ + +class Spiral +{ + //Function to return a list containing the level order + //traversal in spiral form. + ArrayList findSpiral(Node root) + { + // Your code here + + ArrayList arr = new ArrayList<>(); + + if(root == null) + return arr; + + Queue q = new LinkedList<>(); + + q.add(root); + + int cnt = 0; + + while(!q.isEmpty()) + { + int size = q.size(); + + ArrayList level = new ArrayList<>(); + + for(int i = 0; i < size; ++i) + { + Node cur = q.poll(); + + level.add(cur.data); + + if(cur.left != null) + q.add(cur.left); + if(cur.right != null) + q.add(cur.right); + } + + if(cnt % 2 == 0) + { + for(int i = size-1; i >= 0; --i) + arr.add(level.get(i)); + } + else + { + for(int i = 0; i < size; ++i) + arr.add(level.get(i)); + } + + ++cnt; + } + + return arr; + + } +} \ No newline at end of file diff --git a/Longest Common Subsequence - GFG/README.md b/Longest Common Subsequence - GFG/README.md new file mode 100644 index 00000000..b0ea3c77 --- /dev/null +++ b/Longest Common Subsequence - GFG/README.md @@ -0,0 +1,21 @@ +# Longest Common Subsequence +## Medium +

Given two strings, find the length of longest subsequence present in both of them. Both the strings are in uppercase latin alphabets.

+

Example 1:

+
Input:
+A = 6, B = 6
+str1 = ABCDGH
+str2 = AEDFHR
+Output: 3
+Explanation: LCS for input strings “ABCDGH” and “AEDFHR” is “ADH” of length 3.
+
+

Example 2:

+
Input:
+A = 3, B = 2
+str1 = ABC
+str2 = AC
+Output: 2
+Explanation: LCS of "ABC" and "AC" is "AC" of length 2.
+

Your Task:
Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them.

+

Expected Time Complexity : O(|str1|*|str2|)
Expected Auxiliary Space: O(|str1|*|str2|)

+

Constraints:
1<=size(str1),size(str2)<=103

\ No newline at end of file diff --git a/Longest Common Subsequence - GFG/longest-common-subsequence.cpp b/Longest Common Subsequence - GFG/longest-common-subsequence.cpp new file mode 100644 index 00000000..d4b891ce --- /dev/null +++ b/Longest Common Subsequence - GFG/longest-common-subsequence.cpp @@ -0,0 +1,55 @@ +//{ Driver Code Starts +#include +const int mod=1e9+7; +using namespace std; + +// } Driver Code Ends +// function to find longest common subsequence + +class Solution +{ + public: + //Function to find the length of longest common subsequence in two strings. + int lcs(int n, int m, string s1, string s2) + { + // your code here + + vector> dp(n+1, vector(m+1,0)); + + for(int i = n-1; i >= 0; --i) + { + for(int j = m-1; j >= 0; --j) + { + if(s1[i] == s2[j]) + { + dp[i][j] = 1 + dp[i+1][j+1]; + } + else + { + dp[i][j] = max(dp[i][j+1], dp[i+1][j]); + } + } + } + + return dp[0][0]; + } +}; + + +//{ Driver Code Starts. +int main() +{ + int t,n,m; + cin>>t; + while(t--) + { + cin>>n>>m; // Take size of both the strings as input + string s1,s2; + cin>>s1>>s2; // Take both the string as input + Solution ob; + cout << ob.lcs(n, m, s1, s2) << endl; + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Longest K unique characters substring - GFG/README.md b/Longest K unique characters substring - GFG/README.md new file mode 100644 index 00000000..5e77d8bc --- /dev/null +++ b/Longest K unique characters substring - GFG/README.md @@ -0,0 +1,18 @@ +# Longest K unique characters substring +## Medium +

Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.

+

Example 1:

+
Input:
+S = "aabacbebebe", K = 3
+Output: 
7 +Explanation:
"cbebebe" is the longest substring with 3 distinct characters. +
+

Example 2:

+
Input: 
+S = "aaaa", K = 2
+Output: -1
+Explanation: 
There's no substring with 2 distinct characters. +
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1.

+

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(|S|).

+

Constraints:
1 ≤ |S| ≤ 105
1 ≤ K ≤ 26
All characters are lowercase latin characters.

\ No newline at end of file diff --git a/Longest K unique characters substring - GFG/longest-k-unique-characters-substring.cpp b/Longest K unique characters substring - GFG/longest-k-unique-characters-substring.cpp new file mode 100644 index 00000000..b934511e --- /dev/null +++ b/Longest K unique characters substring - GFG/longest-k-unique-characters-substring.cpp @@ -0,0 +1,61 @@ +//{ Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + +// } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + int longestKSubstr(string s, int k) { + // your code here + + unordered_map mp; + + int i = 0, j = 0, n = s.size(); + + int ans = -1; + + while(j < n) + { + ++mp[s[j]]; + + if(mp.size() == k) + { + ans = max(ans, j - i + 1); + } + + while(mp.size() > k) + { + --mp[s[i]]; + + if(mp[s[i]] == 0) + mp.erase(s[i]); + + ++i; + } + + ++j; + } + + return ans; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + string s; + cin >> s; + int k; + cin >> k; + Solution ob; + cout << ob.longestKSubstr(s, k) << endl; + } +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Longest Palindromic Subsequence - GFG/README.md b/Longest Palindromic Subsequence - GFG/README.md new file mode 100644 index 00000000..90467274 --- /dev/null +++ b/Longest Palindromic Subsequence - GFG/README.md @@ -0,0 +1,20 @@ +# Longest Palindromic Subsequence +## Medium +

Given a String, find the longest palindromic subsequence.

+

Example 1:

+
Input:
+S = "bbabcbcab"
+Output: 7
+Explanation: Subsequence "babcbab" is the
+longest subsequence which is also a palindrome.
+
+

Example 2:

+
Input: 
+S = "abcd"
+Output: 1
+Explanation: "a", "b", "c" and "d" are
+palindromic and all have a length 1.
+
+


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPalinSubseq() which takes the string S as input and returns an integer denoting the length of the longest palindromic subsequence of S.

+

Expected Time Complexity: O(|S|*|S|).
Expected Auxiliary Space: O(|S|*|S|).

+

Constraints:
1 ≤ |S| ≤ 1000

\ No newline at end of file diff --git a/Longest Palindromic Subsequence - GFG/longest-palindromic-subsequence.java b/Longest Palindromic Subsequence - GFG/longest-palindromic-subsequence.java new file mode 100644 index 00000000..9060a828 --- /dev/null +++ b/Longest Palindromic Subsequence - GFG/longest-palindromic-subsequence.java @@ -0,0 +1,52 @@ +//{ Driver Code Starts +//Initial Template for Java + +import java.io.*; +import java.util.*; + +class GfG +{ + public static void main(String args[]) + { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + while(t-->0) + { + String s = sc.next(); + Solution obj = new Solution(); + System.out.println(obj.longestPalinSubseq(s)); + } + + } +} +// } Driver Code Ends + + +//User function Template for Java + +class Solution +{ + public int longestPalinSubseq(String S) + { + //code here + + int n = S.length(); + + String rev = new StringBuilder(S).reverse().toString(); + + int[][] dp = new int[n+1][n+1]; + + for(int i = n-1; i >= 0; --i) + { + for(int j = n-1; j >= 0; --j) + { + if(S.charAt(i) == rev.charAt(j)) + dp[i][j] = 1 + dp[i+1][j+1]; + else + dp[i][j] = Math.max(dp[i+1][j], dp[i][j+1]); + } + } + + return dp[0][0]; + } +} \ No newline at end of file diff --git a/Longest Repeating Subsequence - GFG/README.md b/Longest Repeating Subsequence - GFG/README.md new file mode 100644 index 00000000..d1c44f65 --- /dev/null +++ b/Longest Repeating Subsequence - GFG/README.md @@ -0,0 +1,80 @@ +# Longest Repeating Subsequence +## Medium +

Given string str, find the length of the longest repeating subsequence such that it can be found twice in the given string.

+ +

The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B. For example, A = "xax" and B = "xax" then the index of first "x" must be different in the original string for A and B.

+ +

Example 1:

+ +
Input:
+str = "axxzxy"
+Output: 2
+Explanation:
+The given array with indexes looks like
+a x x z x y 
+0 1 2 3 4 5
+
+The longest subsequence is "xx". 
+It appears twice as explained below.
+
+subsequence A
+x x
+0 1  <-- index of subsequence A
+------
+1 2  <-- index of str 
+
+
+subsequence B
+x x
+0 1  <-- index of subsequence B
+------
+2 4  <-- index of str 
+
+We are able to use character 'x' 
+(at index 2 in str) in both subsequences
+as it appears on index 1 in subsequence A 
+and index 0 in subsequence B.
+ +

Example 2:

+ +
Input:
+str = "axxxy"
+Output: 2
+Explanation:
+The given array with indexes looks like
+a x x x y 
+0 1 2 3 4
+
+The longest subsequence is "xx". 
+It appears twice as explained below.
+
+subsequence A
+x x
+0 1  <-- index of subsequence A
+------
+1 2  <-- index of str 
+
+
+subsequence B
+x x
+0 1  <-- index of subsequence B
+------
+2 3  <-- index of str 
+
+We are able to use character 'x' 
+(at index 2 in str) in both subsequences
+as it appears on index 1 in subsequence A 
+and index 0 in subsequence B.
+ +


+Your Task:
+You don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece.

+ +


+Expected Time Complexity: O(n2)
+Expected Space Complexity: O(n2)

+ +


+Constraints:
+1 <= |str| <= 103

+
\ No newline at end of file diff --git a/Longest Repeating Subsequence - GFG/longest-repeating-subsequence.cpp b/Longest Repeating Subsequence - GFG/longest-repeating-subsequence.cpp new file mode 100644 index 00000000..27f2c8dc --- /dev/null +++ b/Longest Repeating Subsequence - GFG/longest-repeating-subsequence.cpp @@ -0,0 +1,68 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + + private: + int helper(int i, int j, int n, string& str1, string& str2, vector>& dp) + { + if(i >= n or j >= n) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + int take = 0; + + if(str1[i] == str2[j] and i != j) + take = 1 + helper(i+1, j+1, n, str1, str2, dp); + + int notTake = max(helper(i+1, j ,n, str1, str2, dp), helper(i, j+1, n, str1, str2, dp)); + + dp[i][j] = max(take, notTake); + } + + public: + int LongestRepeatingSubsequence(string str){ + // Code here + + int n = str.size(); + + vector> dp(n+1, vector(n+1, 0)); + + for(int i = n-1; i >= 0; --i) + { + for(int j = n-1; j >= 0; --j) + { + int take = 0; + + if(str[i] == str[j] and i != j) + take = 1 + dp[i+1][j+1]; + + int notTake = max(dp[i+1][j], dp[i][j+1]); + + dp[i][j] = max(take, notTake); + } + } + + return dp[0][0]; + } + +}; + +//{ Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + string str; + cin >> str; + Solution obj; + int ans = obj.LongestRepeatingSubsequence(str); + cout << ans << "\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Lowest Common Ancestor in a BST - GFG/README.md b/Lowest Common Ancestor in a BST - GFG/README.md new file mode 100644 index 00000000..2d3883ae --- /dev/null +++ b/Lowest Common Ancestor in a BST - GFG/README.md @@ -0,0 +1,26 @@ +# Lowest Common Ancestor in a BST +## Easy +

Given a Binary Search Tree (with all values unique) and two node values n1 and n2 (n1!=n2). Find the Lowest Common Ancestors of the two nodes in the BST.

+

Example 1:

+
Input:
+              5
+            /   \
+          4      6
+         /        \
+        3          7
+                    \
+                     8
+n1 = 7, n2 = 8
+Output: 7
+
+

Example 2:

+
Input:
+     2
+   /   \
+  1     3
+n1 = 1, n2 = 3
+Output: 2
+
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function LCA() which takes the root Node of the BST and two integer values n1 and n2 as inputs and returns the Lowest Common Ancestor of the Nodes with values n1 and n2 in the given BST. 

+

Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).

+

Constraints:
1 <= N <= 104

\ No newline at end of file diff --git a/Lowest Common Ancestor in a BST - GFG/lowest-common-ancestor-in-a-bst.cpp b/Lowest Common Ancestor in a BST - GFG/lowest-common-ancestor-in-a-bst.cpp new file mode 100644 index 00000000..b0ce9934 --- /dev/null +++ b/Lowest Common Ancestor in a BST - GFG/lowest-common-ancestor-in-a-bst.cpp @@ -0,0 +1,129 @@ +//{ Driver Code Starts +#include +using namespace std; + +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; +// Function to Build Tree + + +// } Driver Code Ends +//Function to find the lowest common ancestor in a BST. +class Solution{ + public: + Node* LCA(Node *root, int n1, int n2) + { + // code here + + if(!root or root->data == n1 or root->data == n2) + return root; + + Node* left = LCA(root->left, n1, n2); + Node* right = LCA(root->right, n1, n2); + + if(!left and !right) + return nullptr; + else if(!left) + return right; + else if(!right) + return left; + return root; + } + +}; + + +//{ Driver Code Starts. + +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +int main() +{ + + int t; + scanf("%d ",&t); + while(t--) + { + string s; + int l , h; + getline(cin,s); + scanf("%d ",&l); + scanf("%d ",&h); + Node* root = buildTree(s); + Solution sol; + int ans = sol.LCA(root, l, h)->data; + cout<

Thank you for consistently taking part in the POTD.
Feel free to share your feedback and suggestions by filling up the Form below.
https://forms.gle/Ga6fVJBzEtDSvEop9
____________________________________________________________________________________________________________________________________________

Given two integer array A and B of size N each.
A sum combination is made by adding one element from array A and another element of array B.
Return the maximum K valid sum combinations from all the possible sum combinations.

+

Note : Output array must be sorted in non-increasing order.

+

Example 1:

+
Input:
N = 2
K = 2
A [ ] = {3, 2}
B [ ] = {1, 4}
Output: {7, 6}
Explanation: 
7 -> (A : 3) + (B : 4)
6 -> (A : 2) + (B : 4)
+

Example 2:

+
Input:
N = 4
K = 3
A [ ] = {1, 4, 2, 3}
B [ ] = {2, 5, 1, 6}
Output: {10, 9, 9}
Explanation: 
10 -> (A : 4) + (B : 6)
9 -> (A : 4) + (B : 5)
9 -> (A : 3) + (B : 6)
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function maxCombinations() which takes the interger N,integer K and two integer arrays A [ ] and B [ ] as parameters and returns the maximum K valid distinct sum combinations .

+

Expected Time Complexity: O(Nlog(N))
Expected Auxiliary Space: O(N)

+

Constraints:
1 ≤ N ≤  105
1 ≤ K ≤  N
1 ≤ A [ i ] , B [ i ] ≤ 104

\ No newline at end of file diff --git a/Maximum Sum Combination - GFG/maximum-sum-combination.cpp b/Maximum Sum Combination - GFG/maximum-sum-combination.cpp new file mode 100644 index 00000000..a13755ac --- /dev/null +++ b/Maximum Sum Combination - GFG/maximum-sum-combination.cpp @@ -0,0 +1,77 @@ +//{ Driver Code Starts +#include +using namespace std; + + +// } Driver Code Ends +class Solution { + public: + vector maxCombinations(int N, int K, vector &A, vector &B) { + // code here + + priority_queue, greater > pq; + + sort(A.rbegin(), A.rend()); + sort(B.rbegin(), B.rend()); + + for(int i = 0; i < K; ++i) + { + for(int j = 0; j < K; ++j) + { + int sum = A[i] + B[j]; + + if(pq.size() < K) + pq.push(sum); + else + { + int curr = pq.top(); + + if(curr < sum) + { + pq.pop(); + pq.push(sum); + } + else + break; + } + } + } + + vector ans; + + while(!pq.empty()) + { + ans.push_back(pq.top()); + pq.pop(); + } + + reverse(ans.begin(), ans.end()); + + return ans; + } +}; + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int N, K; + cin >> N >> K; + + vector A(N), B(N); + for (int i = 0; i < N; i++) { + cin >> A[i]; + } + for (int i = 0; i < N; i++) { + cin >> B[i]; + } + Solution obj; + vector ans = obj.maxCombinations(N, K, A, B); + for (auto &it : ans) cout << it << ' '; + cout << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Maximum product subset of an array - GFG/README.md b/Maximum product subset of an array - GFG/README.md new file mode 100644 index 00000000..976db5da --- /dev/null +++ b/Maximum product subset of an array - GFG/README.md @@ -0,0 +1,36 @@ +# Maximum product subset of an array +## Medium +

Given an array A[]. The task is to find the maximum product possible with the subset of elements present in the array. The maximum product can be a single element also.
+Since the product can be large, return it modulo (109 + 7).

+ +

Example 1:

+ +
Input:
+A[] = {-1, -1, -2, 4, 3}
+Output: 24
+Explanation: Maximum product will be ( -2 * -1 * 4 * 3 ) = 24
+
+
+ +

Example 2:

+ +
Input:
+A[] = {-1, 0}
+Output: 0
+
+ +

 

+ +

Your Task:  
+You don't need to read input or print anything. Your task is to complete the function findMaxProduct() which takes an array of size N and returns an integer.

+ +

Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +

 

+ +

Constraints:
+1 <= N <= 2 * 104
+-10 <= A[i] <= 10

+
\ No newline at end of file diff --git a/Maximum product subset of an array - GFG/maximum-product-subset-of-an-array.cpp b/Maximum product subset of an array - GFG/maximum-product-subset-of-an-array.cpp new file mode 100644 index 00000000..55da1d80 --- /dev/null +++ b/Maximum product subset of an array - GFG/maximum-product-subset-of-an-array.cpp @@ -0,0 +1,77 @@ +//{ Driver Code Starts +/* Driver program to test above function */ + +#include +using namespace std; + +// } Driver Code Ends +//User function Template for C++ +class Solution{ + public: + long long int findMaxProduct(vector&a, int n){ + //Write your code here + + + int negCount = 0, zeroCount = 0; + + int maximumMin = INT_MIN; + + if(n == 1) + return a[0]; + + long long int prod = 1; + + const int mod = 1e9+7; + + for(int i = 0; i < n; ++i) + { + if(a[i] == 0) + { + ++zeroCount; + continue; + } + + if(a[i] < 0) + { + ++negCount; + maximumMin = max(maximumMin, a[i]); + } + + prod = (prod * 1LL * a[i]) % mod; + } + + if(negCount == 1 and zeroCount == n-1 or zeroCount == n) + return 0; + + if(negCount & 1) + { + prod /= maximumMin; + } + + return abs(prod); + } +}; + + + +//{ Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin >> n; + vectorarr(n); + for(int i = 0 ; i < n; i++){ + cin >> arr[i]; + } + Solution ob; + long long int ans = ob.findMaxProduct(arr, n); + cout << ans<

Given a string of S as input. Your task is to write a program to delete the minimum number of characters from the string so that the resultant string is a palindrome.
Note: The order of characters in the string should be maintained.

+

Example 1:

+
Input: 
S = "aebcbda" +Output:
2 +Explanation:
Remove characters 'e' and 'd'.
+

Example 2:

+
Input: 
S = "geeksforgeeks" +Output:
8 +Explanation:
One of the possible result string can be "eefee", so answer is 13 - 5 = 8. +
+

Your Task:  
You don't need to read input or print anything. Your task is to complete the function minimumNumberOfDeletions() which takes the string S as inputs and returns the minimum number of deletions required to convert S into a pallindrome.

Expected Time Complexity: O(|S|2)
Expected Auxiliary Space: O(|S|2)

Constraints:
1 ≤ |S| ≤ 103

\ No newline at end of file diff --git a/Minimum Deletions - GFG/minimum-deletions.cpp b/Minimum Deletions - GFG/minimum-deletions.cpp new file mode 100644 index 00000000..82c5f770 --- /dev/null +++ b/Minimum Deletions - GFG/minimum-deletions.cpp @@ -0,0 +1,60 @@ +//{ Driver Code Starts +#include +using namespace std; + + +// } Driver Code Ends +//User function template for C++ + +class Solution{ + public: + + int helper(int i , int j, int n, string& s, string& t, vector>& dp) + { + if(i == n and j == n) + return 0; + + if(i >= n or j >= n) + return 0; + + if(dp[i][j] != -1) + return dp[i][j]; + + if(s[i] == t[j]) + return dp[i][j] = 1 + helper(i+1, j+1, n, s, t, dp); + else + { + return dp[i][j] = max(helper(i+1, j, n, s, t, dp), helper(i, j+1, n, s, t, dp)); + } + } + + int minimumNumberOfDeletions(string S) { + // code here + + int n = S.size(); + + string t = S; + + reverse(t.begin(), t.end()); + + if(t == S) return 0; + + vector> dp(n+1, vector(n+1, -1)); + + return n - helper(0, 0, n, S, t, dp); + } +}; + +//{ Driver Code Starts. +int main(){ + int t; + cin >> t; + while(t--){ + string S; + cin >> S; + Solution obj; + cout << obj.minimumNumberOfDeletions(S) << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Minimum Operations - GFG/README.md b/Minimum Operations - GFG/README.md new file mode 100644 index 00000000..664241f7 --- /dev/null +++ b/Minimum Operations - GFG/README.md @@ -0,0 +1,22 @@ +# Minimum Operations +## Easy +

Given a number N. Find the minimum number of operations required to reach N starting from 0. You have 2 operations available:

+
    +
  • Double the number
  • +
  • Add one to the number
  • +
+

Example 1:

+
Input:
+N = 8
+Output: 4
+Explanation: 
0 + 1 = 1 --> 1 + 1 = 2 --> 2 * 2 = 4 --> 4 * 2 = 8. +
+

Example 2:

+
Input: 
+N = 7
+Output: 5
+Explanation: 
0 + 1 = 1 --> 1 + 1 = 2 --> 1 + 2 = 3 --> 3 * 2 = 6 --> 6 + 1 = 7. +
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function minOperation() which accepts an integer N and return number of minimum operations required to reach N from 0.

+

Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 106

\ No newline at end of file diff --git a/Minimum Operations - GFG/minimum-operations.cpp b/Minimum Operations - GFG/minimum-operations.cpp new file mode 100644 index 00000000..96d6a112 --- /dev/null +++ b/Minimum Operations - GFG/minimum-operations.cpp @@ -0,0 +1,42 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution +{ + public: + int minOperation(int n) + { + //code here. + + int cnt = 0; + + while(n > 0) + { + if(n & 1) + --n; + else + n /= 2; + + ++cnt; + } + + return cnt; + } +}; + +//{ Driver Code Starts. +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + Solution ob; + cout<

Given a Directed Graph, find a Mother Vertex in the Graph (if present). 
A Mother Vertex is a vertex through which we can reach all the other vertices of the Graph.

+

Example 1:

+
Input: 
+
+Output: 0
+Explanation: According to the given edges, all 
+nodes can be reaced from nodes from 0, 1 and 2. 
+But, since 0 is minimum among 0,1 and 2, so 0 
+is the output.
+
+

Example 2:

+
Input: 
+
+Output: -1
+Explanation: According to the given edges, 
+no vertices are there from where we can 
+reach all vertices. So, output is -1.
+
+

Your Task:
You don't need to read or print anything. Your task is to complete the function findMotherVertex() which takes V denoting the number of vertices and adjacency list as imput parameter and returns the verticex from through which we can traverse all other vertices of the graph. If there is more than one possible nodes then returns the node with minimum value.If not possible returns -1.

Expected Time Complexity: O(V + E)
Expected Space Compelxity: O(V)

Constraints:
1 ≤ V ≤ 500

\ No newline at end of file diff --git a/Mother Vertex - GFG/mother-vertex.cpp b/Mother Vertex - GFG/mother-vertex.cpp new file mode 100644 index 00000000..0f9eb0f7 --- /dev/null +++ b/Mother Vertex - GFG/mother-vertex.cpp @@ -0,0 +1,75 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + +class Solution +{ + public: + //Function to find a Mother Vertex in the Graph. + + void dfs(int sv, vector& visited, vector adj[]) + { + visited[sv] = true; + + for(auto& itr : adj[sv]) + { + if(!visited[itr]) + dfs(itr, visited, adj); + } + } + + int findMotherVertex(int V, vectoradj[]) + { + // Code here + + int mv = -1; + + vector visited(V+1, false); + + for(int i = 0; i < V; ++i) + { + if(!visited[i]) + { + dfs(i, visited, adj); + mv = i; + } + } + + for(int i = 0; i < V; ++i) + visited[i] = 0; + + dfs(mv, visited, adj); + + for(int i = 0; i < V; ++i) + { + if(visited[i] == 0) + return -1; + } + + return mv; + } + +}; + +//{ Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int V, E; + cin >> V >> E; + vectoradj[V]; + for(int i = 0; i < E; i++){ + int u, v; + cin >> u >> v; + adj[u].push_back(v); + } + Solution obj; + int ans = obj.findMotherVertex(V, adj); + cout << ans <<"\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Next Smallest Palindrome - GFG/README.md b/Next Smallest Palindrome - GFG/README.md new file mode 100644 index 00000000..0212fed6 --- /dev/null +++ b/Next Smallest Palindrome - GFG/README.md @@ -0,0 +1,22 @@ +# Next Smallest Palindrome +## Hard +

Given a number, in the form of an array Num[] of size N containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome strictly larger than the given number.

+

Example 1:

+
Input:
+N = 11
+Num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2}
+Output: 9 4 1 8 8 0 8 8 1 4 9
+Explanation: Next smallest palindrome is
+9 4 1 8 8 0 8 8 1 4 9
+
+

Example 2:

+
Input:
+N = 5
+Num[] = {2, 3, 5, 4, 5}
+Output: 2 3 6 3 2
+Explanation: Next smallest palindrome is
+2 3 6 3 2
+
+

Your Task:
Complete the function generateNextPalindrome() which takes an array num, and a single integer n, as input parameters and returns an array of integers denoting the answer. You don't to print answer or take inputs.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 105
1 <= Num[i] <= 9

\ No newline at end of file diff --git a/Next Smallest Palindrome - GFG/next-smallest-palindrome.cpp b/Next Smallest Palindrome - GFG/next-smallest-palindrome.cpp new file mode 100644 index 00000000..8637a17b --- /dev/null +++ b/Next Smallest Palindrome - GFG/next-smallest-palindrome.cpp @@ -0,0 +1,70 @@ +//{ Driver Code Starts +#include + +using namespace std; + +// } Driver Code Ends +//User function template for C++ +class Solution{ +public: + vector generateNextPalindrome(int arr[], int n) { + // code here + + vector num(arr,arr+n); + int mid = (n+1)/2; + bool flag = true; + for(int i=mid;inum[n-i-1]) flag = true; + break; + } + if(flag) + { + int carry = 1; + for(int i=mid-1;i>=0 && carry==1;i--) + { + num[i] = (num[i]==9? 0:num[i]+carry--); + } + if(carry){ + vector res; + res.push_back(1); + for(int i=1;i=0;i--) + { + num[n-i-1]=num[i]; + } + return num; + } + +}; + +//{ Driver Code Starts. + + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + int num[n]; + for (int i = 0; i < n; i++) { + cin >> num[i]; + } + Solution ob; + auto ans = ob.generateNextPalindrome(num, n); + for (auto x : ans) { + cout << x << " "; + } + cout << "\n"; + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Non Repeating Character - GFG/README.md b/Non Repeating Character - GFG/README.md new file mode 100644 index 00000000..f54a1bab --- /dev/null +++ b/Non Repeating Character - GFG/README.md @@ -0,0 +1,22 @@ +# Non Repeating Character +## Easy +

Given a string S consisting of lowercase Latin Letters. Return the first non-repeating character in S. If there is no non-repeating character, return '$'.

+

Example 1:

+
Input:
+S = hello
+Output: h
+Explanation: In the given string, the
+first character which is non-repeating
+is h, as it appears first and there is
+no other 'h' in the string.
+

Example 2:

+
Input:
+S = zxvczbtxyzvy
+Output: c
+Explanation: In the given string, 'c' is
+the character which is non-repeating. 
+
+

Your Task:
You only need to complete the function nonrepeatingCharacter() that takes string S as a parameter and returns the character. If there is no non-repeating character then return '$' .

+

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Number of distinct characters).
Note: N = |S|

+

Constraints:
1 <= N <= 105

+

 

\ No newline at end of file diff --git a/Non Repeating Character - GFG/non-repeating-character.cpp b/Non Repeating Character - GFG/non-repeating-character.cpp new file mode 100644 index 00000000..7798d9c9 --- /dev/null +++ b/Non Repeating Character - GFG/non-repeating-character.cpp @@ -0,0 +1,73 @@ +//{ Driver Code Starts +#include +using namespace std; + + +// } Driver Code Ends + +class Solution +{ + public: + //Function to find the first non-repeating character in a string. + char nonrepeatingCharacter(string S) + { + //Your code here + + int n = S.size(); + + vector freq(26, 0); + map mp; + + for(int i = 0; i < n; ++i) + { + ++freq[S[i]-'a']; + + mp[S[i]] = i; + } + + char ch = '#'; + + int idx = INT_MAX; + + for(int i = 0; i < n; ++i) + { + if(freq[S[i] - 'a'] == 1) + { + idx = min(idx, mp[S[i]]); + } + } + + if(idx == INT_MAX) + return '$'; + return S[idx]; + } + +}; + +//{ Driver Code Starts. + +int main() { + + int T; + cin >> T; + + while(T--) + { + + string S; + cin >> S; + Solution obj; + char ans = obj.nonrepeatingCharacter(S); + + if(ans != '$') + cout << ans; + else cout << "-1"; + + cout << endl; + + } + + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Non Repeating Numbers - GFG/README.md b/Non Repeating Numbers - GFG/README.md new file mode 100644 index 00000000..a369ff14 --- /dev/null +++ b/Non Repeating Numbers - GFG/README.md @@ -0,0 +1,23 @@ +# Non Repeating Numbers +## Medium +

Given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order.

+

Example 1:

+
Input: 
+N = 2
+arr[] = {1, 2, 3, 2, 1, 4}
+Output:
+3 4 
+Explanation:
+3 and 4 occur exactly once.
+
+

Example 2:

+
Input:
+N = 1
+arr[] = {2, 1, 3, 2}
+Output:
+1 3
+Explanation:
+1 3 occur exactly once.
+

Your Task:
You do not need to read or print anything. Your task is to complete the function singleNumber() which takes the array as input parameter and returns a list of two numbers which occur exactly once in the array. The list must be in ascending order.

+

Expected Time Complexity: O(N)
Expected Space Complexity: O(1)

+

Constraints:
1 <= length of array <= 10

1 <= Elements in array <= 5 * 106

\ No newline at end of file diff --git a/Non Repeating Numbers - GFG/non-repeating-numbers.cpp b/Non Repeating Numbers - GFG/non-repeating-numbers.cpp new file mode 100644 index 00000000..838fd3ed --- /dev/null +++ b/Non Repeating Numbers - GFG/non-repeating-numbers.cpp @@ -0,0 +1,54 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution +{ +public: + vector singleNumber(vector nums) + { + // Code here. + + unordered_map mp; + + for(auto itr : nums) + { + ++mp[itr]; + } + + vector ans; + + for(auto itr : mp) + { + if(itr.second == 1) + ans.push_back(itr.first); + } + + if(ans[0] > ans[1]) + swap(ans[0], ans[1]); + + return ans; + } +}; + +//{ Driver Code Starts. +int main(){ + int T; + cin >> T; + while(T--) + { + int n; + cin >> n; + vector v(2 * n + 2); + for(int i = 0; i < 2 * n + 2; i++) + cin >> v[i]; + Solution ob; + vector ans = ob.singleNumber(v); + for(auto i: ans) + cout << i << " "; + cout << "\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Normal BST to Balanced BST - GFG/README.md b/Normal BST to Balanced BST - GFG/README.md new file mode 100644 index 00000000..4a51938e --- /dev/null +++ b/Normal BST to Balanced BST - GFG/README.md @@ -0,0 +1,30 @@ +# Normal BST to Balanced BST +## Easy +

Given a Binary Search Tree, modify the given BST such that it is balanced and has minimum possible height. Return the balanced BST.

+

Example1:

+
Input:
+       30
+      /
+     20
+    /
+   10
Output: + 20 + / \ + 10 30 +
+

Example2:

+
Input:
+         4
+        /
+       3
+      /
+     2
+    /
+   1
+Output:
+      3            3           2
+    /  \         /  \        /  \
+   1    4   OR  2    4  OR  1    3   
+    \          /                  \ 
2 1 4
+


Your Task:

The task is to complete the function buildBalancedTree() which takes root as the input argument and returns the root of tree after converting the given BST into a balanced BST with minimum possible height. The driver code will print the height of the updated tree in output itself.

 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Here N denotes total number of nodes in given BST.

+

Constraints:
1 <= N <= 105
1 <= Node data <= 109

\ No newline at end of file diff --git a/Normal BST to Balanced BST - GFG/normal-bst-to-balanced-bst.cpp b/Normal BST to Balanced BST - GFG/normal-bst-to-balanced-bst.cpp new file mode 100644 index 00000000..0a4ca566 --- /dev/null +++ b/Normal BST to Balanced BST - GFG/normal-bst-to-balanced-bst.cpp @@ -0,0 +1,186 @@ +//{ Driver Code Starts +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left; + struct Node *right; + + Node(int x){ + data = x; + left = NULL; + right = NULL; + } +}; + + +// } Driver Code Ends +/*Structure of the Node of the BST is as +struct Node +{ + int data; + Node* left, *right; +}; +*/ + +class Solution{ + + public: + // Your are required to complete this function + // function should return root of the modified BST + + vector inorder; + + void helper(Node* root) + { + if(root) + { + helper(root->left); + inorder.push_back(root->data); + helper(root->right); + } + } + + Node* BST(int start, int end) + { + if(start <= end) + { + int mid = (start + end) >> 1; + + Node* root = new Node(inorder[mid]); + root->left = BST(start, mid-1); + root->right = BST(mid+1, end); + return root; + } + + return nullptr; + } + Node* buildBalancedTree(Node* root) + { + // Code here + + helper(root); + + return BST(0, inorder.size()-1); + + } +}; + + +//{ Driver Code Starts. + +Node* insert(struct Node* node, int key){ + if (node == NULL) return new Node(key); + if (key < node->data) + node->left = insert(node->left, key); + else if (key > node->data) + node->right = insert(node->right, key); + return node; +} + +void preOrder(Node* node) +{ + if (node == NULL)return; + printf("%d ", node->data); + preOrder(node->left); + preOrder(node->right); +} + +int height(struct Node* node) +{ + if (node==NULL) + return 0; + int lDepth = height(node->left); + int rDepth = height(node->right); + if (lDepth > rDepth) + return(lDepth+1); + else + return(rDepth+1); +} +Node *buildTree(string str) { + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + +Node* buildBalancedTree(Node* root); + +int main() +{ + int t; + cin>>t; + getchar(); + while(t--) + { + struct Node *root = NULL; + int n, temp; + string tree; + getline(cin,tree); + root = buildTree(tree); + // cout<

Given a positive integer n, find the nth fibonacci number. Since the answer can be very large, return the answer modulo 1000000007.

Example 1:

+
Input: 
n = 2 +Output: 
1  +Explanation:
1 is the 2nd number of fibonacci series.
+
+

Example 2:

+
Input: 
n = 5 +Output: 
5 +Explanation:
5 is the 5th number of fibonacci series. +
+

Your Task:  
You dont need to read input or print anything. Complete the function nthFibonacci() which takes n as input parameter and returns nth fibonacci number.

+

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)

+

Constraints:
1<= n <=105

\ No newline at end of file diff --git a/Nth Fibonacci Number - GFG/nth-fibonacci-number.cpp b/Nth Fibonacci Number - GFG/nth-fibonacci-number.cpp new file mode 100644 index 00000000..c97e79a5 --- /dev/null +++ b/Nth Fibonacci Number - GFG/nth-fibonacci-number.cpp @@ -0,0 +1,86 @@ +//{ Driver Code Starts +// Initial Template for C++ +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ +class Solution { + + private: + + const int mod = 1e9 + 7; + + vector> matrixMultiplication(vector> mat1, vector> mat2) + { + vector> ans(2, vector(2)); + + for(int i = 0; i < 2; ++i) + { + for(int j = 0; j < 2; ++j) + { + for(int k =0 ; k < 2 ; ++k) + { + ans[i][j] += (long long)(mat1[i][k]%mod * mat2[k][j]%mod)%mod; + ans[i][j] %= mod; + } + } + } + + return ans; + } + + + vector> expo(vector>& mat, int n) + { + + if(n == 1) + return mat; + + vector> temp = mat; + + + while(n > 0) + { + if(n & 1) + { + temp = matrixMultiplication(mat, temp); + } + + mat = matrixMultiplication(mat, mat); + + n >>= 1; + } + + return temp; + } + + public: + int nthFibonacci(int n){ + // code here + + if(n == 0) + return 0; + + vector> mat = {{1,1},{1,0}}; + + vector> ans = expo(mat, n-1); + + return ans[0][1]%mod; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + Solution ob; + cout << ob.nthFibonacci(n) << endl; + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Number Of Enclaves - GFG/README.md b/Number Of Enclaves - GFG/README.md new file mode 100644 index 00000000..37711e95 --- /dev/null +++ b/Number Of Enclaves - GFG/README.md @@ -0,0 +1,45 @@ +# Number Of Enclaves +## Medium +

You are given an n x m binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

+

A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

+

Find the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

+

Example 1:

+
Input:
+grid[][] = {{0, 0, 0, 0},
+            {1, 0, 1, 0},
+            {0, 1, 1, 0},
+            {0, 0, 0, 0}}
+Output:
+3
+Explanation:
+0 0 0 0
+1 0 1 0
+0 1 1 0
+0 0 0 0
+The highlighted cells represents the land cells.
+
+

Example 2:

+
Input:
+grid[][] = {{0, 0, 0, 1},
+            {0, 1, 1, 0},
+            {0, 1, 1, 0},
+            {0, 0, 0, 1},
+            {0, 1, 1, 0}}
+Output:
+4
+Explanation:
+0 0 0 1
+0 1 1 0
+0 1 1 0
+0 0 0 1
+0 1 1 0
+The highlighted cells represents the land cells.
+

Your Task:

+

You don't need to print or input anything. Complete the function numberOfEnclaves() which takes a 2D integer matrix grid as the input parameter and returns an integer, denoting the number of land cells.

+

Expected Time Complexity: O(n * m)

+

Expected Space Complexity: O(n * m)

+

Constraints:

+
    +
  • 1 <= n, m <= 500
  • +
  • grid[i][j] == 0 or 1
  • +
\ No newline at end of file diff --git a/Number Of Enclaves - GFG/number-of-enclaves.cpp b/Number Of Enclaves - GFG/number-of-enclaves.cpp new file mode 100644 index 00000000..e61366c8 --- /dev/null +++ b/Number Of Enclaves - GFG/number-of-enclaves.cpp @@ -0,0 +1,86 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + + +// } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + int numberOfEnclaves(vector> &grid) { + // Code here + + int n = grid.size(); + int m = grid[0].size(); + + int landCell = 0; + + vector dx = {0, +1, 0, -1}; + vector dy = {+1, 0, -1, 0}; + + vector> visited(n, vector(m, false)); + + function dfs = [&](int i, int j){ + + visited[i][j] = true; + + for(int x = 0; x < 4; ++x) + { + int newX = dx[x] + i; + int newY = dy[x] + j; + + if(newX >= 0 and newY >= 0 and newX < n and newY < m and !visited[newX][newY] and grid[newX][newY] == 1) + { + dfs(newX, newY); + } + } + + }; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if((i == 0 or j == 0 or i == n-1 or j == m-1) and (grid[i][j] == 1 and !visited[i][j])) + { + dfs(i,j); + } + } + } + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + if(!visited[i][j] and grid[i][j] == 1) + ++landCell; + } + } + + return landCell; + } +}; + + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int n, m; + cin >> n >> m; + vector> grid(n, vector(m)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + cin >> grid[i][j]; + } + } + Solution obj; + cout << obj.numberOfEnclaves(grid) << endl; + } +} +// } Driver Code Ends \ No newline at end of file diff --git a/Number of paths - GFG/README.md b/Number of paths - GFG/README.md new file mode 100644 index 00000000..bd1a9a3c --- /dev/null +++ b/Number of paths - GFG/README.md @@ -0,0 +1,28 @@ +# Number of paths +## Medium +

The problem is to count all the possible paths from top left to bottom right of an MxN matrix with the constraints that from each cell you can either move to right or down.

+

Return answer modulo 109+7.

+

Example 1:

+
Input:
+M = 3 and N = 3
+Output: 6
+Explanation:
+Let the given input 3*3 matrix is filled 
+as such:
+A B C
+D E F
+G H I
+The possible paths which exists to reach 
+'I' from 'A' following above conditions 
+are as follows:ABCFI, ABEHI, ADGHI, ADEFI, 
+ADEHI, ABEFI
+
+

Example 2:

+
Input:
+M = 1 and N = 4
+Output: 1
+Explanation:
+There is only one direction to go in,
and thus, there is only one path possible.
+

Your Task
You don't need to read input or print anything. Your task is to complete the function numberOfPaths() which takes the integer M and integer N as input parameters and returns an integer, the number of paths.

+

Expected Time Complexity: O(M)
Expected Space Complexity: O(1)

+

Constraints:
1 ≤ N ≤ 108
1 ≤ M ≤ 105

\ No newline at end of file diff --git a/Number of paths - GFG/number-of-paths.cpp b/Number of paths - GFG/number-of-paths.cpp new file mode 100644 index 00000000..4d0291c2 --- /dev/null +++ b/Number of paths - GFG/number-of-paths.cpp @@ -0,0 +1,73 @@ +//{ Driver Code Starts +#include +using namespace std; + + +// } Driver Code Ends +class Solution +{ + public: + + const int mod = 1e9+7; + + long long expo(long long x, long long y, long long mod) + { + long long res = 1; + + while(y > 0) + { + if(y & 1) + { + res = (res * x) % mod; + } + + x = (x * x) % mod; + + y >>= 1; + } + + return res; + } + + long long modInverse(long long x, long long m) + { + return expo(x, m-2, m); + } + + long long numberOfPaths(int M, int N) + { + // Code Here + + int n = M + N - 2; + int r = M-1; + + long long ans = 1; + + for(int i = 1; i <= r; ++i) + { + ans = (ans * (n-i+1)) % mod; + ans = (ans * modInverse(i , mod))%mod; + } + + return ans; + } +}; + + +//{ Driver Code Starts. + + +int main() +{ + int t; + cin>>t; + while(t--) + { + int N, M; + cin>>M>>N; + Solution ob; + cout << ob.numberOfPaths(M, N)<

Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.
For example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.
Note: You need to swap the nodes, not only the data. If only data is swapped then driver will print -1.

+

Example 1:

+
Input:
+LinkedList: 1->2->2->4->5->6->7->8
+Output: 
2 1 4 2 6 5 8 7 +Explanation:
After swapping each pair considering (1,2), (2, 4), (5, 6).. so on as pairs, we get 2, 1, 4, 2, 6, 5, 8, 7 as a new linked list.
+
+

Example 2:

+
Input:
+LinkedList: 1->3->4->7->9->10->1
+Output: 
3 1 7 4 10 9 1 +Explanation:
After swapping each pair considering (1,3), (4, 7), (9, 10).. so on as pairs, we get 3, 1, 7, 4, 10, 9, 1 as a new linked list.
+

Your Task:
The task is to complete the function pairWiseSwap() which takes the head node as the only argument and returns the head of modified linked list.

+

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

+

Constraints:
1 ≤ N ≤ 105

\ No newline at end of file diff --git a/Pairwise swap elements of a linked list - GFG/pairwise-swap-elements-of-a-linked-list.cpp b/Pairwise swap elements of a linked list - GFG/pairwise-swap-elements-of-a-linked-list.cpp new file mode 100644 index 00000000..dc962e68 --- /dev/null +++ b/Pairwise swap elements of a linked list - GFG/pairwise-swap-elements-of-a-linked-list.cpp @@ -0,0 +1,135 @@ +//{ Driver Code Starts +#include +using namespace std; + +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } +}; + + +// } Driver Code Ends +/* + Pairwise swap a linked list + The input list will have at least one element + node is defined as + +struct Node +{ + int data; + struct Node* next; + + Node(int x){ + data = x; + next = NULL; + } + +}*head; +*/ +class Solution +{ + public: + Node* pairWiseSwap(struct Node* head) + { + // The task is to complete this method + + if(!head or !head->next) + return head; + + Node* prev = nullptr, *temp = head, *prevPrev = nullptr; + Node* newHead = nullptr; + + bool ok = false; + + while(temp) + { + if(ok) + { + Node* nextNode = (temp->next ? temp->next : nullptr); + temp->next = prev; + prev->next = nextNode; + + if(prevPrev) + { + prevPrev->next = temp; + } + prevPrev = prev; + + if(!newHead) + newHead = temp; + + temp = prev; + } + + if(!ok) + prev = temp; + + temp = temp->next; + + ok ^= 1; + } + + return newHead; + } +}; + +//{ Driver Code Starts. + +void printList(Node* node) +{ + while (node != NULL) { + cout << node->data <<" "; + node = node->next; + } + cout<<"\n"; +} + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + + int data; + cin>>data; + struct Node *head = new Node(data); + struct Node *tail = head; + map mp; + mp[head] = head->data; + for (int i = 0; i>data; + tail->next = new Node(data); + tail = tail->next; + mp[tail] = tail->data; + } + struct Node *failure = new Node(-1); + Solution ob; + head = ob.pairWiseSwap(head); + int flag = 0; + struct Node *temp = head; + while(temp){ + if(mp[temp] != temp->data){ + flag = 1; + break; + } + temp = temp->next; + } + if(flag) + printList(failure); + else + printList(head); + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Palindrome String - GFG/README.md b/Palindrome String - GFG/README.md new file mode 100644 index 00000000..73716626 --- /dev/null +++ b/Palindrome String - GFG/README.md @@ -0,0 +1,13 @@ +# Palindrome String +## Easy +

Given a string S, check if it is palindrome or not.

+

Example 1:

+
Input: S = "abba"
+Output: 1
+Explanation: S is a palindrome
+

Example 2:

+
Input: S = "abc" 
+Output: 0
+Explanation: S is not a palindrome
+

Your Task:
You don't need to read input or print anything. Complete the function isPalindrome()which accepts string S and returns an integer value 1 or 0.


Expected Time Complexity: O(Length of S)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= Length of S<= 2*105

\ No newline at end of file diff --git a/Palindrome String - GFG/palindrome-string.cpp b/Palindrome String - GFG/palindrome-string.cpp new file mode 100644 index 00000000..c34d071c --- /dev/null +++ b/Palindrome String - GFG/palindrome-string.cpp @@ -0,0 +1,51 @@ +//{ Driver Code Starts + +#include +using namespace std; + + +// } Driver Code Ends +//User function template for C++ +class Solution{ +public: + + + int isPalindrome(string S) + { + // Your code goes here + + int n = S.size(); + + for(int i = 0; i <= n/2; ++i) + { + if(S[i] != S[n-i-1]) + return false; + } + return true; + } + +}; + +//{ Driver Code Starts. + +int main() +{ + ios_base::sync_with_stdio(0); + cin.tie(NULL); + cout.tie(NULL); + + int t; + cin >> t; + while(t--) + { + string s; + cin >> s; + + Solution ob; + + cout << ob.isPalindrome(s) << "\n"; + } + + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Partition Equal Subset Sum - GFG/README.md b/Partition Equal Subset Sum - GFG/README.md new file mode 100644 index 00000000..d31f9fc6 --- /dev/null +++ b/Partition Equal Subset Sum - GFG/README.md @@ -0,0 +1,19 @@ +# Partition Equal Subset Sum +## Medium +

Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.

+

Example 1:

+
Input: N = 4
+arr = {1, 5, 11, 5}
+Output: YES
+Explanation: 
+The two parts are {1, 5, 5} and {11}.
+
+

Example 2:

+
Input: N = 3
+arr = {1, 3, 5}
+Output: NO
+Explanation: This array can never be 
+partitioned into two such parts.
+

Your Task:
You do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0.

+

Expected Time Complexity: O(N*sum of elements)
Expected Auxiliary Space: O(N*sum of elements)

+

Constraints:
1 ≤ N ≤ 100
1 ≤ arr[i] ≤ 1000
N*sum of elements ≤ 5*106

\ No newline at end of file diff --git a/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp b/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp new file mode 100644 index 00000000..ed8e90c6 --- /dev/null +++ b/Partition Equal Subset Sum - GFG/partition-equal-subset-sum.cpp @@ -0,0 +1,71 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ + +class Solution{ + +private: + bool checkEqualPartition(int idx, int n, int sum, int arr[], vector>& dp) + { + if(idx == n) + { + return sum == 0; + } + + if(dp[idx][sum] != -1) + return dp[idx][sum]; + + bool notTake = checkEqualPartition(idx + 1, n, sum, arr, dp); + + bool take = false; + + if(arr[idx] <= sum) + take = checkEqualPartition(idx + 1, n, sum - arr[idx], arr, dp); + + return dp[idx][sum] = take | notTake; + } + + +public: + int equalPartition(int N, int arr[]) + { + // code here + + + int sum = accumulate(arr, arr+N, 0); + + if(sum & 1) + return false; + + vector> dp(N+1, vector((sum/2) + 1, -1)); + + return checkEqualPartition(0, N, sum/2, arr, dp); + } +}; + +//{ Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + int arr[N]; + for(int i = 0;i < N;i++) + cin>>arr[i]; + + Solution ob; + if(ob.equalPartition(N, arr)) + cout<<"YES\n"; + else + cout<<"NO\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Perfect Numbers - GFG/README.md b/Perfect Numbers - GFG/README.md new file mode 100644 index 00000000..126a56c6 --- /dev/null +++ b/Perfect Numbers - GFG/README.md @@ -0,0 +1,26 @@ +# Perfect Numbers +## Easy +

Given a number N, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number. Return 1 if the number is Perfect otherwise return 0.

+

Example 1:

+
Input:
+N = 6
+Output:
+1 
+Explanation:
+Factors of 6 are 1, 2, 3 and 6.
+Excluding 6 their sum is 6 which
+is equal to N itself. So, it's a
+Perfect Number.
+

Example 2:

+
Input:
+N = 10
+Output:
+0
+Explanation:
+Factors of 10 are 1, 2, 5 and 10.
+Excluding 10 their sum is 8 which
+is not equal to N itself. So, it's
+not a Perfect Number.
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function isPerfectNumber() which takes an Integer N as input and returns 1 if N is a Perfect number else returns 0.

+

Expected Time Complexity: O(sqrt(N))
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 1012

\ No newline at end of file diff --git a/Perfect Numbers - GFG/perfect-numbers.cpp b/Perfect Numbers - GFG/perfect-numbers.cpp new file mode 100644 index 00000000..a7ed1d00 --- /dev/null +++ b/Perfect Numbers - GFG/perfect-numbers.cpp @@ -0,0 +1,44 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + int isPerfectNumber(long long N) { + // code here + + if(N == 1) return 0; + + long long sum = 1; + + for(long long i = 2; i * i < N; ++i) + { + if(N % i == 0) + { + sum += i; + + if(i != N/i) + sum += (N/i); + } + } + + return sum == N; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + long long N; + + cin>>N; + + Solution ob; + cout << ob.isPerfectNumber(N) << endl; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Perfect Sum Problem - GFG/README.md b/Perfect Sum Problem - GFG/README.md new file mode 100644 index 00000000..17111478 --- /dev/null +++ b/Perfect Sum Problem - GFG/README.md @@ -0,0 +1,18 @@ +# Perfect Sum Problem +## Medium +

Given an array arr[] of non-negative integers and an integer sum, the task is to count all subsets of the given array with a sum equal to a given sum.

+

Note: Answer can be very large, so, output answer modulo 109+7

+

Example 1:

+
Input: N = 6, arr[] = {2, 3, 5, 6, 8, 10}
+       sum = 10
+Output: 3
+Explanation: {2, 3, 5}, {2, 8}, {10} are 
possible subsets.
+
Example 2:
+
Input: N = 5, arr[] = {1, 2, 3, 4, 5}
+       sum = 10
+Output: 3
+Explanation: {1, 2, 3, 4}, {1, 4, 5}, 
+{2, 3, 5} are possible subsets.
+
Your Task:  
You don't need to read input or print anything. Complete the function perfectSum() which takes N, array arr[] and sum as input parameters and returns an integer value
+

Expected Time Complexity: O(N*sum)
Expected Auxiliary Space: O(N*sum)

Constraints:
1 ≤ N*sum ≤ 106
+
0<=arr[I]<=106
\ No newline at end of file diff --git a/Perfect Sum Problem - GFG/perfect-sum-problem.cpp b/Perfect Sum Problem - GFG/perfect-sum-problem.cpp new file mode 100644 index 00000000..e02ce00c --- /dev/null +++ b/Perfect Sum Problem - GFG/perfect-sum-problem.cpp @@ -0,0 +1,72 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ + + + private: + + const int mod = 1e9+7; + + int helper(int idx, int n, int sum, int arr[], vector>& dp) + { + if(idx == n) + { + return sum == 0; + } + + if(dp[idx][sum] != -1) + return dp[idx][sum]; + + int notTake = helper(idx+1, n, sum, arr, dp); + + int take = 0; + + if(arr[idx] <= sum) + take = helper(idx+1 , n, sum - arr[idx], arr, dp); + + return dp[idx][sum] = (take + notTake) % mod;; + } + + public: + int perfectSum(int arr[], int n, int sum) + { + // Your code goes here + + vector> dp(n+1, vector(sum+1, -1)); + + return helper(0, n, sum, arr, dp); + + } + +}; + +//{ Driver Code Starts. +int main() +{ + + + int t; + cin >> t; + while (t--) + { + int n, sum; + + cin >> n >> sum; + + int a[n]; + for(int i = 0; i < n; i++) + cin >> a[i]; + + + + Solution ob; + cout << ob.perfectSum(a, n, sum) << "\n"; + + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Power Of Numbers - GFG/README.md b/Power Of Numbers - GFG/README.md new file mode 100644 index 00000000..3585c161 --- /dev/null +++ b/Power Of Numbers - GFG/README.md @@ -0,0 +1,17 @@ +# Power Of Numbers +## Medium +

Given a number and its reverse. Find that number raised to the power of its own reverse.
Note: As answers can be very large, print the result modulo 109 + 7.

+

Example 1:

+
Input:
+N = 2, R = 2
+Output: 4
+Explanation: The reverse of 2 is 2 and after raising power of 2 by 2 we get 4 which gives remainder as 4 when divided by 1000000007.
+

Example 2:

+
Input:
+N = 12, R = 21
+Output: 864354781
+Explanation: The reverse of 12 is 21and 1221 when divided by 1000000007 gives remainder as 864354781.
+

Your Task:
You don't need to read input or print anything. You just need to complete the function pow() that takes two parameters N and R denoting the input number and its reverse and returns power of (N to R)mod(109 + 7).

+

Expected Time Complexity: O(LogN).
Expected Auxiliary Space: O(LogN).

+

Constraints:
1 <= N <= 109

+

 

\ No newline at end of file diff --git a/Power Of Numbers - GFG/power-of-numbers.java b/Power Of Numbers - GFG/power-of-numbers.java new file mode 100644 index 00000000..604d85f3 --- /dev/null +++ b/Power Of Numbers - GFG/power-of-numbers.java @@ -0,0 +1,93 @@ +//{ Driver Code Starts +//Initial Template for Java + +/*package whatever //do not write package name here */ + +import java.io.*; +import java.util.*; +class Main { + + // compute reverse of a number + public static long rev(long n) + { + long rev_num = 0; + while(n > 0) + { + rev_num = rev_num*10 + n%10; + n = n/10; + } + return rev_num; + } + + public static void main (String[] args) { + Scanner sc=new Scanner(System.in); + + //testcases + int T=sc.nextInt(); + while(T-->0) + { + Solution obj=new Solution(); + + int N; + + + //input N + N=sc.nextInt(); + int R=0; + + + // reverse the given number n + R=(int)rev(N); + + //power of the number to it's reverse + long ans=(long)obj.power(N,R); + System.out.println(ans); + + + } + + } +} + + +// } Driver Code Ends + + +//User function Template for Java + + +class Solution +{ + + long mod = 1000000007; + + long expo(long x, long y) + { + long res = 1; + + while(y > 0) + { + if(y % 2 == 1) + { + res = (res * x) % mod; + } + + x = (x* x) % mod; + + y >>= 1; + } + + return res; + } + + long power(int N,int R) + { + //Your code here + + long ans = expo(N, R); + + return ans; + + } + +} diff --git a/Power of 2 - GFG/README.md b/Power of 2 - GFG/README.md new file mode 100644 index 00000000..dc4810fa --- /dev/null +++ b/Power of 2 - GFG/README.md @@ -0,0 +1,14 @@ +# Power of 2 +## Easy +

Given a non-negative integer N. The task is to check if N is a power of 2. More formally, check if N can be expressed as 2x for some integer x.

+

Example 1:

+
Input: 
N = 8 +Output:
YES +Explanation:
8 is equal to 2 raised to 3 (23 = 8).
+

Example 2:

+
Input: 
N = 98 +Output:
NO +Explanation:
98 cannot be obtained by any power of 2.
+

Your Task:Your task is to complete the function isPowerofTwo() which takes n as a parameter and returns true or false by checking if the given number can be represented as a power of two or not.

+

Expected Time Complexity:O(log N).
Expected Auxiliary Space:O(1).

+

Constraints:
0 ≤ N ≤1018

\ No newline at end of file diff --git a/Power of 2 - GFG/power-of-2.cpp b/Power of 2 - GFG/power-of-2.cpp new file mode 100644 index 00000000..a31b0eb0 --- /dev/null +++ b/Power of 2 - GFG/power-of-2.cpp @@ -0,0 +1,48 @@ +//{ Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + +// } Driver Code Ends +//User function Template for C++ + +class Solution{ + public: + // Function to check if given number n is a power of two. + bool isPowerofTwo(long long n){ + + // Your code here + + return __builtin_popcountll(n) == 1; + + } +}; + +//{ Driver Code Starts. + +// Driver code +int main() +{ + + int t; + cin>>t;//testcases + + for(int i=0;i>n; + + Solution ob; + if(ob.isPowerofTwo(n))//Now, if log2 produces an integer not decimal then we are sure raising 2 to this value + cout<<"YES"<

Given an undirected graph with nodes and E edges, create and return an adjacency list of the graph. 0-based indexing is followed everywhere.

+

Example 1:

+
Input:
V = 5, E = 7
edges = {(0,1),(0,4),(4,1),(4,3),(1,3),(1,2),(3,2)} + +Output: +{{1,4}, + {0,2,3,4}, + {1,3}, + {1,2,4}, + {0,1,3}} +Explanation: +Node 0 is connected to 1 and 4.
Node 1 is connected to 0,2,3 and 4.
Node 2 is connected to 1 and 3.
Node 3 is connected to 1,2 and 4.
Node 4 is connected to 0,1 and 3.
+
+

Example 2:

+
Input:
V = 4, E = 3
edges = {(0,3),(0,2),(2,1)} + + +Output: +{{2,3} + {2}, + {0,1} + {0}} +Explanation:
Node 0 is connected to 2 and 3.
Node 1 is only connected to 2.
Node 2 is connected to 0 and 1.
Node 3 is only connected to 0.
+

Your task:
You don't need to read input or print anything. Your task is to complete the function printGraph() which takes the integer V denoting the number of vertices and edges as input parameters and returns the list of list denoting the adjacency list.

+

Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V + E)

+

Constraints:
1 ≤ V, E ≤ 105

\ No newline at end of file diff --git a/Print adjacency list - GFG/print-adjacency-list.cpp b/Print adjacency list - GFG/print-adjacency-list.cpp new file mode 100644 index 00000000..88dd70e5 --- /dev/null +++ b/Print adjacency list - GFG/print-adjacency-list.cpp @@ -0,0 +1,52 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + // Function to return the adjacency list for each vertex. + vector> printGraph(int V, vector>edges) { + // Code here + + vector> adj(V+1); + + for(auto& itr : edges) + { + int u = itr.first; + int v = itr.second; + + adj[u].push_back(v); + adj[v].push_back(u); + } + + return adj; + } +}; + +//{ Driver Code Starts. +int main() { + int tc; + cin >> tc; + while (tc--) { + int V, E; + cin >> V >> E; + vector>edges; + for (int i = 0; i < E; i++) { + int u, v; + cin >> u >> v; + edges.push_back({u,v}); + } + Solution obj; + vector> adj = obj.printGraph(V, edges); + for(int i=0;i

Given a number N, find the first N Fibonacci numbers. The first two number of the series are 1 and 1.

+

Example 1:

+
Input:
+N = 5
+Output: 1 1 2 3 5
+
+

Example 2:

+
Input:
+N = 7
+Output: 1 1 2 3 5 8 13
+

Your Task:
Your task is to complete printFibb() which takes single argument N and returns a list of first N Fibonacci numbers.

+

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Note: This space is used to store and return the answer for printing purpose.

+

Constraints:
1<= N <=84

\ No newline at end of file diff --git a/Print first n Fibonacci Numbers - GFG/print-first-n-fibonacci-numbers.cpp b/Print first n Fibonacci Numbers - GFG/print-first-n-fibonacci-numbers.cpp new file mode 100644 index 00000000..68cf1a0c --- /dev/null +++ b/Print first n Fibonacci Numbers - GFG/print-first-n-fibonacci-numbers.cpp @@ -0,0 +1,65 @@ +//{ Driver Code Starts +//Initial function template for C++ + +#include +using namespace std; + +// } Driver Code Ends +//User function template for C++ + + +class Solution +{ + public: + //Function to return list containing first n fibonacci numbers. + vector printFibb(int n) + { + //code here + + vector ans; + + + long long a = 0, b = 1, c; + + if(n>=1) + ans.push_back(b); + + for(int i = 0; i < n-1; ++i) + { + c = a + b; + + a = b; + + b = c; + + ans.push_back(c); + } + + return ans; + + } +}; + +//{ Driver Code Starts. +int main() + { + //taking total testcases + int t; + cin>>t; + while(t--) + { + //taking number of elements + int n; + cin>>n; + Solution obj; + //calling function printFibb() + vector ans = obj.printFibb(n); + + //printing the elements of vector + for(long long i:ans)cout<

Given a Queue Q containing N elements. The task is to reverse the Queue. Your task is to complete the function rev(), that reverses the N elements of the queue.

+

Example 1:

+
Input:
+6
+4 3 1 10 2 6
+Output: 
+6 2 10 1 3 4
+Explanation: 
+After reversing the given elements of the queue , the resultant queue will be 6 2 10 1 3 4.
+
+

Example 2:

+
Input:
+4
+4 3 2 1 
+Output: 
+1 2 3 4
+Explanation: 
+After reversing the given elements of the queue , the resultant queue will be 1 2 3 4.
+

Your Task: You need to complete the function rev that takes a queue as parameter and returns the reversed queue. The printing is done automatically by the driver code.

+

Expected Time Complexity : O(n)
Expected Auxilliary Space : O(n)

+

Constraints:
1 ≤ N ≤ 105
1 ≤ elements of Queue ≤ 105

\ No newline at end of file diff --git a/Queue Reversal - GFG/queue-reversal.cpp b/Queue Reversal - GFG/queue-reversal.cpp new file mode 100644 index 00000000..50acb6ab --- /dev/null +++ b/Queue Reversal - GFG/queue-reversal.cpp @@ -0,0 +1,65 @@ +//{ Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +//function Template for C++ + +//Function to reverse the queue. +class Solution +{ + public: + queue rev(queue q) + { + // add code here. + + // fifo + + stack st; + + while(!q.empty()) + { + st.push(q.front()); + q.pop(); + } + + while(!st.empty()) + { + q.push(st.top()); + st.pop(); + } + + return q; + + } +}; + + +//{ Driver Code Starts. +int main() +{ + int test; + cin>>test; + while(test--) + { + queue q; + int n, var; + cin>>n; + while(n--) + { + cin>>var; + q.push(var); + } + Solution ob; + queue a=ob.rev(q); + while(!a.empty()) + { + cout<

Given a singly linked list consisting of N nodes. The task is to remove duplicates (nodes with duplicate values) from the given list (if exists).
Note: Try not to use extra space. The nodes are arranged in a sorted way.

+

Example 1:

+
Input:
+LinkedList: 2->2->4->5
+Output: 2 4 5
+Explanation: In the given linked list 
+2 ->2 -> 4-> 5, only 2 occurs more 
+than 1 time. So we need to remove it once.
+
+

Example 2:

+
Input:
+LinkedList: 2->2->2->2->2
+Output: 2
+Explanation: In the given linked list 
+2 ->2 ->2 ->2 ->2, 2 is the only element
+and is repeated 5 times. So we need to remove
any four 2.
+

Your Task:
The task is to complete the function removeDuplicates() which takes the head of input linked list as input. The function should remove the duplicates from linked list and return the head of the linkedlist.

+

Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)

+

Constraints:
1 <= Number of nodes <= 105

\ No newline at end of file diff --git a/Remove duplicate element from sorted Linked List - GFG/remove-duplicate-element-from-sorted-linked-list.cpp b/Remove duplicate element from sorted Linked List - GFG/remove-duplicate-element-from-sorted-linked-list.cpp new file mode 100644 index 00000000..7d6681a8 --- /dev/null +++ b/Remove duplicate element from sorted Linked List - GFG/remove-duplicate-element-from-sorted-linked-list.cpp @@ -0,0 +1,92 @@ +//{ Driver Code Starts +#include +using namespace std; + +struct Node { + int data; + struct Node *next; + Node(int x) { + data = x; + next = NULL; + } +}; + + +void print(Node *root) +{ + Node *temp = root; + while(temp!=NULL) + { + cout<data<<" "; + temp=temp->next; + } +} +Node* removeDuplicates(Node *root); +int main() { + // your code goes here + int T; + cin>>T; + + while(T--) + { + int K; + cin>>K; + Node *head = NULL; + Node *temp = head; + + for(int i=0;i>data; + if(head==NULL) + head=temp=new Node(data); + else + { + temp->next = new Node(data); + temp=temp->next; + } + } + + Node *result = removeDuplicates(head); + print(result); + cout<next) + nextNode = temp->next; + + while(nextNode and temp->data == nextNode->data) + { + temp->next = nextNode->next; + nextNode = temp->next; + } + temp = temp->next; + } + + return head; + +} \ No newline at end of file diff --git a/Reverse a Stack - GFG/README.md b/Reverse a Stack - GFG/README.md new file mode 100644 index 00000000..1b0419ff --- /dev/null +++ b/Reverse a Stack - GFG/README.md @@ -0,0 +1,18 @@ +# Reverse a Stack +## Medium +

You are given a stack St. You have to reverse the stack using recursion.

+

Example 1:

+
Input:
+St = {3,2,1,7,6}
+Output:
+{6,7,1,2,3}
Explanation:
Input stack after reversing will look like the stack in the output.
+

Example 2:

+
Input:
+St = {4,3,9,6}
+Output:
+{6,9,3,4}
Explanation:
Input stack after reversing will look like the stack in the output.
+
+

Your Task:

+

You don't need to read input or print anything. Your task is to complete the function Reverse() which takes the stack St as input and reverses the given stack.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

+

Constraints:
1 <= size of the stack <= 104

-109 <= Each element of the stack <= 109
Sum of N over all test cases doesn't exceeds 106
Array may contain duplicate elements. 

\ No newline at end of file diff --git a/Reverse a Stack - GFG/reverse-a-stack.cpp b/Reverse a Stack - GFG/reverse-a-stack.cpp new file mode 100644 index 00000000..40daaa86 --- /dev/null +++ b/Reverse a Stack - GFG/reverse-a-stack.cpp @@ -0,0 +1,72 @@ +//{ Driver Code Starts +//Initial Template for C++ + +#include +using namespace std; + + +// } Driver Code Ends +//User function Template for C++ + +class Solution{ + +private: + void insert(stack& St, int ele) + { + if(St.empty()) + { + St.push(ele); + return; + } + + int cur = St.top(); + St.pop(); + insert(St, ele); + St.push(cur); + } + +public: + void Reverse(stack &St){ + + if(St.empty()) + return; + + int ele = St.top(); + St.pop(); + Reverse(St); + insert(St, ele); + } +}; + +//{ Driver Code Starts. + + +int main(){ + int T; + cin>>T; + while(T--){ + int N; + cin>>N; + stack St; + for(int i=0;i>x; + St.push(x); + } + Solution ob; + ob.Reverse(St); + vectorres; + while(St.size()) + { + res.push_back(St.top()); + St.pop(); + } + for(int i = res.size()-1;i>=0;i--) + { + cout<

Given a linked list, you have to perform the following task:

+
    +
  1. Extract the alternative nodes starting from second node.
  2. +
  3. Reverse the extracted list.
  4. +
  5. Append the extracted list at the end of the original list.
  6. +
+

Note: Try to solve the problem without using any extra memory.

+

Example 1:

+
Input:
+LinkedList = 10->4->9->1->3->5->9->4
+Output: 
10 9 3 9 4 5 1 4 +Explanation:
Alternative nodes in the given linked list are 4,1,5,4. Reversing the alternative nodes from the given list, and then appending them to the end of the list results in a list 10->9->3->9->4->5->1->4. +
+

Example 2:

+
Input:
+LinkedList = 1->2->3->4->5
+Output: 
1 3 5 4 2  +Explanation:
Alternative nodes in the given linked list are 2 and 4. Reversing the alternative nodes from the given list, and then appending them to the end of the list results in a list 1->3->5->4->2.
+

Your Task:
You don't have to read input or print anything. Your task is to complete the function rearrange() which takes the head of the linked list as input and rearranges the list as required.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 105
0 <= Node_value <= 109

\ No newline at end of file diff --git a/Reverse alternate nodes in Link List - GFG/reverse-alternate-nodes-in-link-list.cpp b/Reverse alternate nodes in Link List - GFG/reverse-alternate-nodes-in-link-list.cpp new file mode 100644 index 00000000..13df7d24 --- /dev/null +++ b/Reverse alternate nodes in Link List - GFG/reverse-alternate-nodes-in-link-list.cpp @@ -0,0 +1,150 @@ +//{ Driver Code Starts +#include +#include +#include +using namespace std; +/* A linked list node */ + + +struct Node +{ + int data; + struct Node *next; + + Node(int x){ + data = x; + next = NULL; + } + +}; + +struct Node *start = NULL; + +/* Function to print nodes in a given linked list */ +void printList(struct Node *node) +{ + while (node != NULL) + { + printf("%d ", node->data); + node = node->next; + } + printf("\n"); + +} + +void insert() +{ + int n,value; + cin>>n; + struct Node *temp; + for(int i=0;i>value; + if(i==0) + { + start = new Node(value); + temp = start; + continue; + } + else + { + temp->next = new Node(value); + temp = temp->next; + } + } +} + + +// } Driver Code Ends +/* + reverse alternate nodes and append at the end + The input list will have at least one element + Node is defined as + struct Node + { + int data; + struct Node *next; + + Node(int x){ + data = x; + next = NULL; + } + + }; + +*/ +class Solution +{ + public: + + Node* reverse(struct Node* head) + { + Node* prev = nullptr; + + while(head) + { + Node* nextNode = head->next; + head->next = prev; + prev = head; + head = nextNode; + } + + return prev; + } + + void rearrange(struct Node *odd) + { + //add code here + + Node* dummy = new Node(0), *ptr = dummy; + + Node* temp = odd, *prev = nullptr; + + bool ok = false; + + while(temp) + { + if(ok) + { + prev->next = (temp->next ? temp->next : nullptr); + ptr ->next = temp; + ptr = ptr->next; + } + + if(!ok) + prev = temp; + + temp = temp->next; + + ok ^= 1; + } + + + if(ptr->next) + ptr->next = nullptr; + + Node* rev = reverse(dummy->next); + + + prev->next = rev; + + } +}; + + + +//{ Driver Code Starts. +int main() +{ + int t; + cin>>t; + while (t--) { + insert(); + Solution ob; + ob.rearrange(start); + printList(start); + } + return 0; +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Right View of Binary Tree - GFG/README.md b/Right View of Binary Tree - GFG/README.md new file mode 100644 index 00000000..b73e9ea4 --- /dev/null +++ b/Right View of Binary Tree - GFG/README.md @@ -0,0 +1,44 @@ +# Right View of Binary Tree +## Easy +

Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side.

+ +

Right view of following tree is 1 3 7 8.

+ +

          1
+       /     \
+     2        3
+   /   \      /    \
+  4     5   6    7
+    \
+     8

+ +

Example 1:

+ +
Input:
+       1
+    /    \
+   3      2
+Output: 1 2
+
+ +

Example 2:

+ +
Input:
+     10
+    /   \
+  20     30
+ /   \
+40  60 
+Output: 10 30 60
+
+ +

Your Task:
+Just complete the function rightView() that takes node as parameter and returns the right view as a list. 

+ +

Expected Time Complexity: O(N).
+Expected Auxiliary Space: O(Height of the Tree).

+ +

Constraints:
+1 ≤ Number of nodes ≤ 105
+0 ≤ Data of a node ≤ 105

+
\ No newline at end of file diff --git a/Right View of Binary Tree - GFG/right-view-of-binary-tree.cpp b/Right View of Binary Tree - GFG/right-view-of-binary-tree.cpp new file mode 100644 index 00000000..76622afc --- /dev/null +++ b/Right View of Binary Tree - GFG/right-view-of-binary-tree.cpp @@ -0,0 +1,165 @@ +//{ Driver Code Starts +#include +using namespace std; + +// Tree Node +struct Node +{ + int data; + Node* left; + Node* right; +}; +// Utility function to create a new Tree Node +Node* newNode(int val) +{ + Node* temp = new Node; + temp->data = val; + temp->left = NULL; + temp->right = NULL; + + return temp; +} + + +// } Driver Code Ends +/* A binary tree node has data, pointer to left child + and a pointer to right child +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; */ + +// Should return right view of tree +class Solution +{ + private: + void helper(Node* root, int& maxLevel, int level, vector& ans) + { + if(!root) + return; + + if(level > maxLevel) + { + ans.push_back(root->data); + maxLevel = level; + } + + helper(root->right, maxLevel, level + 1, ans); + helper(root->left, maxLevel, level + 1, ans); + } + + public: + //Function to return list containing elements of right view of binary tree. + vector rightView(Node *root) + { + // Your Code here + + int maxLevel = -1; + + vector ans; + + helper(root, maxLevel, 0, ans); + + return ans; + } +}; + + + +//{ Driver Code Starts. + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = newNode(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = newNode(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +int main() { + int t; + string tc; + getline(cin,tc); + t=stoi(tc); + while(t--) + { + string s; + getline(cin,s); + Node* root = buildTree(s); + + Solution ob; + vector vec = ob.rightView(root); + for(int x : vec){ + cout<

Given a 2D binary matrix A(0-based index) of dimensions NxM. Find the minimum number of steps required to reach from (0,0) to (X, Y).
Note: You can only move left, right, up and down, and only through cells that contain 1.

+

Example 1:

+
Input:
+N=3, M=4
+A=[[1,0,0,0], 
+   [1,1,0,1],
[0,1,1,1]] +X=2, Y=3 +Output: +5 +Explanation: +The shortest path is as follows: +(0,0)->(1,0)->(1,1)->(2,1)->(2,2)->(2,3).
+

Example 2:

+
Input:
+N=3, M=4
+A=[[1,1,1,1],
+   [0,0,0,1],
[0,0,0,1]] +X=0, Y=3 +Output: +3 +Explanation: +The shortest path is as follows: +(0,0)->(0,1)->(0,2)->(0,3).
+

Your Task:
You don't need to read input or print anything. Your task is to complete the function shortestDistance() which takes the integer N, M, X, Y, and the 2D binary matrix A as input parameters and returns the minimum number of steps required to go from (0,0) to (X, Y).If it is impossible to go from (0,0) to (X, Y),then function returns -1. If value of the cell (0,0) is 0 (i.e  A[0][0]=0) then return -1.

+

Expected Time Complexity:O(N*M)
Expected Auxillary Space:O(N*M)

+

Constraints:
1 <= N,M <= 250
0 <= X < N
0 <= Y < M
0 <= A[i][j] <= 1

\ No newline at end of file diff --git a/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.cpp b/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.cpp new file mode 100644 index 00000000..fc61f512 --- /dev/null +++ b/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.cpp @@ -0,0 +1,73 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ + +class Solution { + public: + int shortestDistance(int N, int M, vector> A, int X, int Y) { + // code here + + vector> visited(N, vector(M,false)); + + queue> > q; + + + vector dx = {-1, 0, 0, 1}; + vector dy = {0, -1, +1, 0}; + + q.push({0,{0, 0}}); + + visited[0][0] = true; + + while(!q.empty()) + { + auto curr = q.front(); + q.pop(); + + int step = curr.first; + int x = curr.second.first; + int y = curr.second.second; + + if(x == X and y == Y) + { + return step; + } + + for(int i = 0; i < 4; ++i) + { + int newx = x + dx[i]; + int newy = y + dy[i]; + + if(newx >= 0 and newy >= 0 and newx < N and newy < M and !visited[newx][newy] and A[newx][newy] == 1) + { + visited[newx][newy] = true; + q.push({step+1,{newx,newy}}); + } + } + } + + return -1; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int N, M, x, y; + cin >> N >> M; + vector> v(N, vector(M)); + for (int i = 0; i < N; i++) + for (int j = 0; j < M; j++) cin >> v[i][j]; + cin >> x >> y; + Solution ob; + cout << ob.shortestDistance(N, M, v, x, y) << "\n"; + } +} +// } Driver Code Ends \ No newline at end of file diff --git a/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.java b/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.java new file mode 100644 index 00000000..097c1f65 --- /dev/null +++ b/Shortest Source to Destination Path - GFG/shortest-source-to-destination-path.java @@ -0,0 +1,78 @@ +//{ Driver Code Starts +// Initial Template for Java + +import java.io.*; +import java.util.*; +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader read = + new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(read.readLine()); + while (t-- > 0) { + int N, M, x, y; + String S[] = read.readLine().split(" "); + N = Integer.parseInt(S[0]); + M = Integer.parseInt(S[1]); + int a[][] = new int[N][M]; + for (int i = 0; i < N; i++) { + String s[] = read.readLine().split(" "); + for (int j = 0; j < M; j++) a[i][j] = Integer.parseInt(s[j]); + } + String s1[] = read.readLine().split(" "); + x = Integer.parseInt(s1[0]); + y = Integer.parseInt(s1[1]); + Solution ob = new Solution(); + System.out.println(ob.shortestDistance(N, M, a, x, y)); + } + } +} +// } Driver Code Ends + + +// User function Template for Java + +class Solution { + int shortestDistance(int N, int M, int A[][], int X, int Y) { + // code here + + boolean[][] visited = new boolean[N][M]; + + Queue q = new LinkedList<>(); + + q.add(new int[]{0, 0, 0}); + + visited[0][0] = true; + + int[] dx = {-1, 0, 0, +1}; + int[] dy = {0, -1, +1, 0}; + + while(!q.isEmpty()) + { + int curr[] = q.poll(); + + int step = curr[0]; + int x = curr[1]; + int y = curr[2]; + + // System.out.println(x + " " + step + " " + y); + + if(X == x && Y == y) + return step; + + for(int i = 0; i < 4; ++i) + { + int newx = dx[i] + x; + int newy = dy[i] + y; + + if(newx >= 0 && newy >= 0 && newx < N && newy < M && !visited[newx][newy] && A[newx][newy] == 1) + { + // System.out.println(newx + " " + newy); + visited[newx][newy] = true; + q.add(new int[]{step+1, newx, newy}); + } + } + + } + return -1; + } +}; \ No newline at end of file diff --git a/Shortest path in Directed Acyclic Graph - GFG/README.md b/Shortest path in Directed Acyclic Graph - GFG/README.md new file mode 100644 index 00000000..bff5298e --- /dev/null +++ b/Shortest path in Directed Acyclic Graph - GFG/README.md @@ -0,0 +1,21 @@ +# Shortest path in Directed Acyclic Graph +## Medium +

Given a Directed Acyclic Graph of N vertices from 0 to N-1 and a 2D Integer array(or vector) edges[ ][ ] of length M, where there is a directed edge from edge[i][0] to edge[i][1] with a distance of edge[i][2] for all i.

+

Find the shortest path from src(0) vertex to all the vertices and if it is impossible to reach any vertex, then return -1 for that vertex.

+

Example1:

+
Input:
+N = 4, M = 2
+edge = [[0,1,2],[0,2,1]
+Output:
+0 2 1 -1
Explanation:
Shortest path from 0 to 1 is 0->1 with edge weight 2. 
Shortest path from 0 to 2 is 0->2 with edge weight 1.
There is no way we can reach 3, so it's -1 for 3.
+

Example2:

+
Input:
+N = 6, M = 7
+edge = [[0,1,2],[0,4,1],[4,5,4],[4,2,2],[1,2,3],[2,3,6],[5,3,1]]
+Output:
+0 2 3 6 1 5
Explanation:
Shortest path from 0 to 1 is 0->1 with edge weight 2.
Shortest path from 0 to 2 is 0->4->2 with edge weight 1+2=3.
Shortest path from 0 to 3 is 0->4->5->3 with edge weight 1+4+1=6.
Shortest path from 0 to 4 is 0->4 with edge weight 1.
Shortest path from 0 to 5 is 0->4->5 with edge weight 1+4=5.
+

Your Task:

+

You don't need to print or input anything. Complete the function shortest path() which takes an integer N as number of vertices, an integer M as number of edges and a 2D Integer array(or vector) edges as the input parameters and returns an integer array(or vector), denoting the list of distance from src to all nodes.

+

Expected Time Complexity: O(N+M), where N is the number of nodes and M is edges
Expected Space Complexity: O(N)

+

Constraint:
1 <= N,M <= 100
0 <= edgei,0,edgei,1 < n
0 <= 
edgei,2 <=105

+

 

\ No newline at end of file diff --git a/Shortest path in Directed Acyclic Graph - GFG/shortest-path-in-directed-acyclic-graph.cpp b/Shortest path in Directed Acyclic Graph - GFG/shortest-path-in-directed-acyclic-graph.cpp new file mode 100644 index 00000000..6564fa7f --- /dev/null +++ b/Shortest path in Directed Acyclic Graph - GFG/shortest-path-in-directed-acyclic-graph.cpp @@ -0,0 +1,92 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// User function Template for C++ +class Solution { + public: + vector shortestPath(int N,int M, vector>& edges){ + // code here + + vector> adj[N+1]; + + for(auto& itr : edges) + { + int u = itr[0]; + int v = itr[1]; + int dist = itr[2]; + + adj[u].push_back({v, dist}); + } + + priority_queue, vector>, greater> > pq; + + vector distance(N, 1e9); + + pq.push({0, 0}); + + distance[0] = 0; + + while(!pq.empty()) + { + auto curr = pq.top(); + + pq.pop(); + + int node = curr.second; + int currDist = curr.first; + + for(auto itr : adj[node]) + { + int childNode = itr.first; + int childDist = itr.second; + + if(currDist + childDist < distance[childNode]) + { + distance[childNode] = currDist + childDist; + pq.push({distance[childNode], childNode}); + } + } + } + + for(int i = 0; i < N; ++i) + { + if(distance[i] == 1e9) + distance[i] = -1; + } + + return distance; + + } +}; + + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n, m; + cin >> n >> m; + vector> edges; + for(int i=0; i temp; + for(int j=0; j<3; ++j){ + int x; cin>>x; + temp.push_back(x); + } + edges.push_back(temp); + } + Solution obj; + vector res = obj.shortestPath(n, m, edges); + for (auto x : res) { + cout << x << " "; + } + cout << "\n"; + } +} + +// } Driver Code Ends \ No newline at end of file diff --git a/Solve the Sudoku - GFG/README.md b/Solve the Sudoku - GFG/README.md new file mode 100644 index 00000000..f2ebb406 --- /dev/null +++ b/Solve the Sudoku - GFG/README.md @@ -0,0 +1,50 @@ +# Solve the Sudoku +## Hard +

Given an incomplete Sudoku configuration in terms of a 9 x 9  2-D square matrix (grid[][]), the task is to find a solved Sudoku. For simplicity, you may assume that there will be only one unique solution.

+

A sudoku solution must satisfy all of the following rules:

+
    +
  1. Each of the digits 1-9 must occur exactly once in each row.
  2. +
  3. Each of the digits 1-9 must occur exactly once in each column.
  4. +
  5. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
  6. +
+

Zeros in the grid indicates blanks, which are to be filled with some number between 1-9. You can not replace the element in the cell which is not blank.

+


Sample Sudoku for you to get the logic for its solution:

+

Example 1:

+
Input:
+grid[][] = 
+[[3 0 6 5 0 8 4 0 0],
+[5 2 0 0 0 0 0 0 0],
+[0 8 7 0 0 0 0 3 1 ],
+[0 0 3 0 1 0 0 8 0],
+[9 0 0 8 6 3 0 0 5],
+[0 5 0 0 9 0 6 0 0],
+[1 3 0 0 0 0 2 5 0],
+[0 0 0 0 0 0 0 7 4],
+[0 0 5 2 0 6 3 0 0]]
+Output:
True +3 1 6 5 7 8 4 9 2 +5 2 9 1 3 4 7 6 8 +4 8 7 6 2 9 5 3 1 +2 6 3 4 1 5 9 8 7 +9 7 4 8 6 3 1 2 5 +8 5 1 7 9 2 6 4 3 +1 3 8 9 4 7 2 5 6 +6 9 2 3 5 1 8 7 4 +7 4 5 2 8 6 3 1 9
Explanation:
There exists a valid Sudoku for the input grid, which is shown in output. +
+

Example 2:

+
Input:
+grid[][] = 
+[[3 6 6 5 0 8 4 0 0],
+[5 2 0 0 0 0 0 0 0],
+[0 8 7 0 0 0 0 3 1 ],
+[0 0 3 0 1 0 0 8 0],
+[9 0 0 8 6 3 0 0 5],
+[0 5 0 0 9 0 6 0 0],
+[1 3 0 0 0 0 2 5 0],
+[0 0 0 0 0 0 0 7 4],
+[0 0 5 2 0 6 3 0 0]]
+Output:
False
Explanation:
There does not exists a valid Sudoku for the input grid, since there are two 6s in the first row. Which cannot replaced.
+

Your Task:
You need to complete the two functions:

SolveSudoku(): Takes a grid as its argument and returns true if a solution is possible and false if it is not, on returning false driver will print "No solution exists".

printGrid(): Takes a grid as its argument and prints the 81 numbers of the solved Sudoku in a single line with space separation. Do not give a new line character after printing the grid.

+

Expected Time Complexity: O(9N*N).
Expected Auxiliary Space: O(N*N).

+

Constraints:
0 ≤ grid[i][j] ≤ 9

\ No newline at end of file diff --git a/Solve the Sudoku - GFG/solve-the-sudoku.cpp b/Solve the Sudoku - GFG/solve-the-sudoku.cpp new file mode 100644 index 00000000..46f46b45 --- /dev/null +++ b/Solve the Sudoku - GFG/solve-the-sudoku.cpp @@ -0,0 +1,101 @@ +//{ Driver Code Starts +#include +using namespace std; +// UNASSIGNED is used for empty cells in sudoku grid +#define UNASSIGNED 0 + +// N is used for the size of Sudoku grid. +// Size will be NxN +#define N 9 + + +// } Driver Code Ends +class Solution +{ + private: + + bool isValid(int row, int col, int curr, int matrix[9][9]) + { + for(int i = 0; i < 9; ++i) + { + if(matrix[i][col] == curr) + return false; + if(matrix[row][i] == curr) + return false; + if(matrix[3*(row/3) + i/3][3*(col/3) + i%3] == curr) + return false; + } + return true; + } + + public: + //Function to find a solved Sudoku. + bool SolveSudoku(int grid[N][N]) + { + // Your code here + + for(int i = 0; i < N; ++i) + { + for(int j = 0; j < N; ++j) + { + if(grid[i][j] == 0) + { + for(int k = 1; k <= 9; ++k) + { + if(isValid(i, j, k, grid)) + { + grid[i][j] = k ; + + if(SolveSudoku(grid)) + return true; + else + grid[i][j] = 0; + } + } + return false; + } + + } + } + return true; + } + + //Function to print grids of the Sudoku. + void printGrid (int grid[N][N]) + { + // Your code here + + for(int i = 0; i < N; ++i) + { + for(int j = 0; j < N; ++j) + cout<>t; + while(t--) + { + int grid[N][N]; + + for(int i=0;i<9;i++) + for(int j=0;j<9;j++) + cin>>grid[i][j]; + + Solution ob; + + if (ob.SolveSudoku(grid) == true) + ob.printGrid(grid); + else + cout << "No solution exists"; + + cout<

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.

+ +


+Example 1:

+ +
Input: 
+N = 5
+arr[]= {0 2 1 2 0}
+Output:
+0 0 1 2 2
+Explanation:
+0s 1s and 2s are segregated 
+into ascending order.
+ +

Example 2:

+ +
Input: 
+N = 3
+arr[] = {0 1 0}
+Output:
+0 0 1
+Explanation:
+0s 1s and 2s are segregated 
+into ascending order.
+ +


+Your Task:
+You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place.

+ +


+Expected Time Complexity: O(N)
+Expected Auxiliary Space: O(1)

+ +


+Constraints:
+1 <= N <= 10^6
+0 <= A[i] <= 2

+ \ No newline at end of file diff --git a/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.java b/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.java new file mode 100644 index 00000000..8b6d5f39 --- /dev/null +++ b/Sort an array of 0s, 1s and 2s - GFG/sort-an-array-of-0s-1s-and-2s.java @@ -0,0 +1,71 @@ +//{ Driver Code Starts +//Initial template for Java + +import java.io.*; +import java.util.*; + + +// } Driver Code Ends +//User function template for Java + +class Solution +{ + + public static void swap(int a[], int i, int j) + { + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + + + public static void sort012(int a[], int n) + { + // code here + + int start = 0, end = n-1; + int zero = 0 ; + + while(start <= end) + { + if(a[start] == 2) + { + swap(a, start, end--); + } + else if(a[start] == 0) + { + swap(a, start++, zero++); + } + else + ++start; + } + } +} + +//{ Driver Code Starts. + +class GFG { + + public static void main (String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases + while(t-->0){ + int n = Integer.parseInt(br.readLine().trim()); + int arr[] = new int[n]; + String inputLine[] = br.readLine().trim().split(" "); + for(int i=0; i

Given a string S. The task is to find all permutations (need not be different) of a given string.

+

Example 1:

+
Input:
+S = AAA
+Output: AAA AAA AAA AAA AAA AAA
Explanation: There are total 6 permutations, as given in the output.
+
+

Example 2:

+
Input:
+S = ABSG
+Output: ABGS ABSG AGBS AGSB ASBG ASGB
+BAGS BASG BGAS BGSA BSAG BSGA GABS
+GASB GBAS GBSA GSAB GSBA SABG SAGB
+SBAG SBGA SGAB SGBA
Explanation: There are total 24 permutations, as given in the output.
+

Your Task:
This is a function problem. You only need to complete the function permutation that takes S as parameter and returns the list of permutations in lexicographically increasing order. The newline is automatically added by driver code.

+

Constraints:
1 ≤ size of string ≤ 5

+

Expected Time Complexity: O(N * N!), N = length of string.
Expected Auxiliary Space: O(1)

\ No newline at end of file diff --git a/String Permutations - GFG/string-permutations.cpp b/String Permutations - GFG/string-permutations.cpp new file mode 100644 index 00000000..2e57d4d2 --- /dev/null +++ b/String Permutations - GFG/string-permutations.cpp @@ -0,0 +1,62 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ + + private: + void helper(int idx, string S, vector& ans) + { + if(idx == S.size()) + { + ans.push_back(S); + return; + } + + for(int i = idx; i < S.size(); ++i) + { + swap(S[idx], S[i]); + helper(idx+1, S, ans); + swap(S[idx], S[i]); + } + } + + public: + //Complete this function + + vector permutation(string S) + { + //Your code here + + vector ans; + + helper(0, S, ans); + + sort(ans.begin(), ans.end()); + + return ans; + } +}; + +//{ Driver Code Starts. + +int main() +{ + int T; + cin>>T; + while(T--) + { + string S; + cin>>S; + Solution ob; + vector vec = ob.permutation(S); + for(string s : vec){ + cout<

Given a Directed Graph with V vertices and E edges, Find the members of strongly connected components in the graph.

+


Example 1:

+
Input:
+
+Output:
+0 1 2,3,4,
+Explanation:
+
+We can clearly see that there are 3 Strongly
+Connected Components in the Graph as mentioned
+in the Output.
+
+

Example 2:

+
Input:
+
+Output:
+0 1 2,
+Explanation:
+All of the nodes are connected to each other.
+So, there's only one SCC as shown.
+


Your Task:
You don't need to read input or print anything. Your task is to complete the function tarjans() which takes the number of vertices V and adjacency list of the graph as input parameters and returns a list of list of integers denoting the members of strongly connected components in the given graph.
Note: A single strongly connected component must be represented in the form of a list if integers sorted in the ascending order. The resulting list should consist of a list of all SCCs which must be sorted in a way such that a lexicographically smaller list of integers appears first.

+


Expected Time Complexity: O(V + E).
Expected Auxiliary Space: O(V).

+


Constraints:
1
105
1
105
0
u, v N-1

\ No newline at end of file diff --git a/Strongly connected component (Tarjans's Algo) - GFG/strongly-connected-component-tarjanss-algo.cpp b/Strongly connected component (Tarjans's Algo) - GFG/strongly-connected-component-tarjanss-algo.cpp new file mode 100644 index 00000000..bcc9af87 --- /dev/null +++ b/Strongly connected component (Tarjans's Algo) - GFG/strongly-connected-component-tarjanss-algo.cpp @@ -0,0 +1,139 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +//User function template for C++ + +class Solution +{ + public: + //Function to return a list of lists of integers denoting the members + //of strongly connected components in the given graph. + + void dfs(int sv, vector adj[], vector& tin, vector& low, vector& inStack, stack&st, vector>& res) + { + static int timer = 0; + + tin[sv] = low[sv] = timer; + + ++timer; + + st.push(sv); + + inStack[sv] = true; + + for(auto itr : adj[sv]) + { + if(tin[itr] == -1) + { + dfs(itr, adj, tin, low, inStack, st, res); + low[sv] = min(low[sv], low[itr]); + } + else if(inStack[itr]) + { + // if node is visited and + // if node is present in stack that means it is a back edge and if it is not present in stack + // it is cross edge and we will do not consider cross edges. + + low[sv] = min(low[sv], tin[itr]); + } + } + + // if low[sv] == tin[sv] that means it is head node of the strong connected commonent + + if(low[sv] == tin[sv]) + { + vector scc; + + while(st.top() != sv) + { + scc.push_back(st.top()); + inStack[st.top()] = false; + st.pop(); + } + + scc.push_back(sv); + inStack[st.top()] = false; + st.pop(); + + sort(scc.begin(), scc.end()); + + res.push_back(scc); + } + + } + + vector> TarjansAlgorithm(vector adj[], int n) + { + vector> res; + + vector tin(n,-1), low(n,-1); + + vector inStack(n, false); + + stack st; + + for(int i = 0; i < n; ++i) + { + if(tin[i] == -1) + dfs(i, adj, tin, low, inStack, st, res); + } + + sort(res.begin(), res.end()); + + return res; + } + + vector> tarjans(int V, vector adj[]) + { + //code here + + return TarjansAlgorithm(adj, V); + } +}; + +//{ Driver Code Starts. + + +int main() +{ + + int t; + cin >> t; + while(t--) + { + int V, E; + cin >> V >> E; + + vector adj[V]; + + for(int i = 0; i < E; i++) + { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + } + + Solution obj; + vector> ptr = obj.tarjans(V, adj); + + for(int i=0; i

Given an unsorted array A of size N that contains only positive integers, find a continuous sub-array that adds to a given number and return the left and right index(1-based indexing) of that subarray.

+

In case of multiple subarrays, return the subarray indexes which come first on moving from left to right.

+

Note:- You have to return an ArrayList consisting of two elements left and right. In case no such subarray exists return an array consisting of element -1.

+

Example 1:

+
Input:
+N = 5, S = 12
+A[] = {1,2,3,7,5}
+Output: 2 4
+Explanation: The sum of elements 
+from 2nd position to 4th position 
+is 12.
+

Example 2:

+
Input:
+N = 10, S = 15
+A[] = {1,2,3,4,5,6,7,8,9,10}
+Output: 1 5
+Explanation: The sum of elements 
+from 1st position to 5th position
+is 15.
+
+

Your Task:
You don't need to read input or print anything. The task is to complete the function subarraySum() which takes arr, N, and S as input parameters and returns an ArrayList containing the starting and ending positions of the first such occurring subarray from the left where sum equals to S. The two indexes in the array should be according to 1-based indexing. If no such subarray is found, return an array consisting of only one element that is -1.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 105

1 <= Ai <= 109
0<= S <= 109

\ No newline at end of file diff --git a/Subarray with given sum - GFG/subarray-with-given-sum.cpp b/Subarray with given sum - GFG/subarray-with-given-sum.cpp new file mode 100644 index 00000000..a93489a9 --- /dev/null +++ b/Subarray with given sum - GFG/subarray-with-given-sum.cpp @@ -0,0 +1,70 @@ +//{ Driver Code Starts +#include +using namespace std; + + +// } Driver Code Ends +class Solution +{ + public: + //Function to find a continuous sub-array which adds up to a given number. + vector subarraySum(vectorarr, int n, long long s) + { + // Your code here4 + + if(s == 0) + return {-1}; + + int i = 0, j = 0; + + int sum = 0; + + while(j < n) + { + sum += arr[j]; + + while(sum >= s) + { + if(sum == s) + { + return {i+1, j+1}; + } + sum -= arr[i++]; + } + ++j; + } + + return {-1}; + } +}; + +//{ Driver Code Starts. + +int main() + { + int t; + cin>>t; + while(t--) + { + int n; + long long s; + cin>>n>>s; + vectorarr(n); + // int arr[n]; + const int mx = 1e9; + for(int i=0;i>arr[i]; + } + Solution ob; + vectorres; + res = ob.subarraySum(arr, n, s); + + for(int i = 0;i

Given a positive integer N., The task is to find the value of    \sum_{i=1}^{i=n} F(i)  where function F(i) for the number i is defined as the sum of all divisors of i.

+

Example 1:

+
Input:
+N = 4
+Output:
+15
+Explanation:
+F(1) = 1
+F(2) = 1 + 2 = 3
+F(3) = 1 + 3 = 4
+F(4) = 1 + 2 + 4 = 7
+ans = F(1) + F(2) + F(3) + F(4)
+    = 1 + 3 + 4 + 7
+    = 15
+

Example 2:

+
Input:
+N = 5
+Output:
+21
+Explanation:
+F(1) = 1
+F(2) = 1 + 2 = 3
+F(3) = 1 + 3 = 4
+F(4) = 1 + 2 + 4 = 7
+F(5) = 1 + 5 = 6
+ans = F(1) + F(2) + F(3) + F(4) + F(5)
+    = 1 + 3 + 4 + 7 + 6
+    = 21
+

Your Task:  
You don't need to read input or print anything. Your task is to complete the function sumOfDivisors() which takes an integer N as an input parameter and returns an integer.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

+

Constraints:
1 <= N <= 106

\ No newline at end of file diff --git a/Sum of all divisors from 1 to n - GFG/sum-of-all-divisors-from-1-to-n.cpp b/Sum of all divisors from 1 to n - GFG/sum-of-all-divisors-from-1-to-n.cpp new file mode 100644 index 00000000..324dcc03 --- /dev/null +++ b/Sum of all divisors from 1 to n - GFG/sum-of-all-divisors-from-1-to-n.cpp @@ -0,0 +1,40 @@ +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +//User function Template for C++ +class Solution +{ +public: + long long sumOfDivisors(int N) + { + // Write Your Code here + + long long ans = 0; + + for(int i = 1; i <= N; ++i) + { + ans += (i * (N/i)); + } + + return ans; + } +}; + +//{ Driver Code Starts. +int main() +{ + int t; + cin >> t; + while (t--) + { + int N; + cin>>N; + Solution ob; + long long ans = ob.sumOfDivisors(N); + cout<

Given a matrix of order nxm, composed of only 0's and 1's, find the number of 1's in the matrix that are surrounded by an even number (>0) of 0's. The surrounding of a cell in the matrix is defined as the elements above, below, on left, on right as well as the 4 diagonal elements around the cell of the matrix. Hence, the surrounding of any matrix elements is composed of 8 elements. Find the number of such 1's.

+

Example 1:

+
Input: 
matrix = {{1, 0, 0},
{1, 1, 0}, + {0, 1, 0}} +Output:
1 +Explanation:
1 that occurs in the 1st row and 1st column, has 3 surrounding elements 0,1 and 1. The occurrence of zero is odd.
1 that occurs in 2nd row and 1st column has 5 surrounding elements 1,0,1,1 and 0. The occurrence of zero is even.
1 that occurs in 2nd row and 2nd column has 8 surrounding elements. The occurrence of 0 is odd.
Similarly, for the 1 that occurs in 3rd row and 2nd column, the occurrence of zero in it's 5 surrounding elements is odd. +Hence, the output is 1.
+
+

Example 2:

+
Input: 
matrix = {{1}} +Output:
0 +Explanation:
There is only 1 element in the matrix. Hence, it has no surroundings, so it's count for even 0's is 0 for the whole matrix.
0 is even but we want occurrence of a zero in the surrounding at least once. +Hence, output is 0.
+
+

Your Task:
You don't need to read or print anything. Your task is to complete the function Count() which takes the matrix as input parameter and returns the number of 1's which are surrounded by even number of 0's.

+

Expected Time Complexity: O(n * m)
Expected Space Complexity: O(1)

+

Constraints:
1 <= n, m <= 103

\ No newline at end of file diff --git a/Surround the 1's - GFG/surround-the-1s.cpp b/Surround the 1's - GFG/surround-the-1s.cpp new file mode 100644 index 00000000..aa61aa98 --- /dev/null +++ b/Surround the 1's - GFG/surround-the-1s.cpp @@ -0,0 +1,77 @@ +//{ Driver Code Starts + +#include +using namespace std; + +// } Driver Code Ends + +class Solution { + +private: + int helper(int i, int j, int n, int m, vector>& matrix) + { + vector dx = {-1, -1, -1, 0, +1, +1, +1, 0}; + vector dy = {-1, 0, +1, +1, +1, 0, -1, -1}; + + int ans = 0; + + for(int k = 0; k < 8; ++k) + { + int newX = dx[k] + i; + int newY = dy[k] + j; + + if(newX >= 0 and newY >= 0 and newX < n and newY < m and !matrix[newX][newY]) + { + ++ans; + } + } + + return ans; + } +public: + int Count(vector >& matrix) { + // Code here + + int n = matrix.size(), m = matrix[0].size(); + + int res = 0; + + for(int i = 0; i < n; ++i) + { + for(int j = 0; j < m; ++j) + { + + if(matrix[i][j] == 1) + { + int cnt = helper(i, j, n, m, matrix); + + if(cnt > 0 and cnt % 2 == 0) + ++res; + } + } + } + + return res; + } +}; + +//{ Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n, m; + cin >> n >> m; + vector> matrix(n, vector(m,0)); + for(int i = 0; i < n; i++){ + for(int j = 0; j < m; j++){ + cin >> matrix[i][j]; + } + } + Solution ob; + int ans = ob.Count(matrix); + cout << ans <<"\n"; + } + return 0; +} +// } Driver Code Ends \ No newline at end of file diff --git a/Transitive closure of a Graph - GFG/README.md b/Transitive closure of a Graph - GFG/README.md new file mode 100644 index 00000000..b38a80ce --- /dev/null +++ b/Transitive closure of a Graph - GFG/README.md @@ -0,0 +1,26 @@ +# Transitive closure of a Graph +## Medium +

Given a directed graph, determine whether a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Here, vertex j is reachable from another vertex i means that there is a path from vertex i to j. The reachability matrix is called the transitive closure of a graph. The directed graph is represented by an adjacency matrix where there are N vertices. 

+

Example 1:

+
Input: N = 4
+graph = {{1, 1, 0, 1}, 
+         {0, 1, 1, 0}, 
+         {0, 0, 1, 1}, 
+         {0, 0, 0, 1}}
+Output: {{1, 1, 1, 1}, 
+         {0, 1, 1, 1}, 
+         {0, 0, 1, 1}, 
+         {0, 0, 0, 1}}
+Explanation: 
The output list shows the reachable indexes.
+

Example 2:

+
Input: N = 3
+graph = {{1, 0, 0}, 
+         {0, 1, 0}, 
+         {0, 0, 1}}
+Output: {{1, 0, 0}, 
+         {0, 1, 0}, 
+         {0, 0, 1}}
+Explanation: 
The output list shows the reachable indexes.
+

Your Task:
You do not need to read input or print anything. Your task is to complete the function transitiveClosure() which takes an integer N and a 2D array graph(adjacency matrix of the graph) as input parameters and returns the transitive closure of the graph in the form of 2D array.

+

Expected Time Complexity: O(N3)
Expected Auxiliary Space: O(N2)

+

Constraints:
1 ≤ N ≤ 100  

\ No newline at end of file diff --git a/Transitive closure of a Graph - GFG/transitive-closure-of-a-graph.cpp b/Transitive closure of a Graph - GFG/transitive-closure-of-a-graph.cpp new file mode 100644 index 00000000..84151909 --- /dev/null +++ b/Transitive closure of a Graph - GFG/transitive-closure-of-a-graph.cpp @@ -0,0 +1,75 @@ +//{ Driver Code Starts +// Initial Template for C++ + +#include +using namespace std; + +// } Driver Code Ends +// Back-end complete function Template for C++ + +class Solution{ +public: + + void dfs(int node, int sv, vector adj[], vector& visited, vector>& res) + { + visited[sv] = true; + res[node][sv] = true; + + for(auto& itr : adj[sv]) + { + if(!visited[itr]) + dfs(node, itr, adj, visited, res); + } + } + + vector> transitiveClosure(int N, vector> graph) + { + // code here + + vector adj[N+1]; + + for(int i = 0; i < N; ++i) + { + for(int j = 0; j < N; ++j) + { + if(graph[i][j] == 1) + adj[i].push_back(j); + } + } + + vector> res(N, vector(N, 0)); + + for(int i = 0; i < N; ++i) + { + vector visited(N, false); + dfs(i, i, adj, visited, res); + } + + return res; + + } +}; + +//{ Driver Code Starts. + +int main(){ + int t; + cin>>t; + while(t--){ + int N; + cin>>N; + vector> graph(N, vector(N, -1)); + for(int i = 0;i < N;i++) + for(int j=0;j>graph[i][j]; + + Solution ob; + vector> ans = ob.transitiveClosure(N, graph); + for(int i = 0;i < N;i++) + {for(int j = 0;j < N;j++) + cout<

Given an array arr of N integers, the task is to check whether the frequency of the elements in the array is unique or not. Or in other words, there are no two distinct numbers in array with equal frequency. If all the frequency is unique then return true, else return false.

+

Example 1:

+
Input:
+N = 5
arr = [1, 1, 2, 5, 5] +Output: +false +Explanation:
The array contains 2 (1’s), 1 (2’s) and 2 (5’s), since the number of frequency of 1 and 5 are the same i.e. 2 times. Therefore, this array does not satisfy the condition. +
+

Example 2:

+
Input:
+N = 10
arr = [2, 2, 5, 10, 1, 2, 10, 5, 10, 2] +Output: +true +Explanation: +Number of 1’s -> 1 +Number of 2’s -> 4 +Number of 5’s -> 2 +Number of 10’s -> 3. +Since, the number of occurrences of elements present in the array is unique. Therefore, this array satisfy the condition.
+

Your task:
You don't need to read input or print anything. Your task is to complete the function isFrequencyUnique() which take integer N and array arr of size N as arguments, and returns a boolean.

+

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

+

Constraints:
1 <= N <=105
-109 <= arr[i] <= 109

\ No newline at end of file diff --git a/Unique Number of Occurrences - GFG/unique-number-of-occurrences.java b/Unique Number of Occurrences - GFG/unique-number-of-occurrences.java new file mode 100644 index 00000000..1579aa58 --- /dev/null +++ b/Unique Number of Occurrences - GFG/unique-number-of-occurrences.java @@ -0,0 +1,89 @@ +//{ Driver Code Starts +import java.io.*; +import java.util.*; + + +class IntArray +{ + public static int[] input(BufferedReader br, int n) throws IOException + { + String[] s = br.readLine().trim().split(" "); + int[] a = new int[n]; + for(int i = 0; i < n; i++) + a[i] = Integer.parseInt(s[i]); + + return a; + } + + public static void print(int[] a) + { + for(int e : a) + System.out.print(e + " "); + System.out.println(); + } + + public static void print(ArrayList a) + { + for(int e : a) + System.out.print(e + " "); + System.out.println(); + } +} + +class GFG { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t; + t = Integer.parseInt(br.readLine()); + while(t-- > 0){ + + int n; + n = Integer.parseInt(br.readLine()); + + + int[] arr = IntArray.input(br, n); + + Solution obj = new Solution(); + boolean res = obj.isFrequencyUnique(n, arr); + + int _result_val = (res) ? 1 : 0; + System.out.println(_result_val); + } + } +} + +// } Driver Code Ends + + + +class Solution { + public static boolean isFrequencyUnique(int n, int[] arr) { + // code here + + HashMap mp = new HashMap<>(); + HashSet st = new HashSet<>(); + + for(int i = 0; i < n; ++i) + { + if(mp.containsKey(arr[i])) + { + mp.put(arr[i] , mp.get(arr[i]) + 1); + } + else + { + mp.put(arr[i],1); + } + } + + for(int freq : mp.values()) + { + if(st.contains(freq)) + return false; + else + st.add(freq); + } + + return true; + } +} + diff --git a/Wave Array - GFG/README.md b/Wave Array - GFG/README.md new file mode 100644 index 00000000..dc773438 --- /dev/null +++ b/Wave Array - GFG/README.md @@ -0,0 +1,24 @@ +# Wave Array +## Easy +

Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array(In Place).
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....

+

If there are multiple solutions, find the lexicographically smallest one.

+

Note:The given array is sorted in ascending order, and you don't need to return anything to make changes in the original array itself.

+

Example 1:

+
Input:
+n = 5
+arr[] = {1,2,3,4,5}
+Output: 2 1 4 3 5
+Explanation: Array elements after 
+sorting it in wave form are 
+2 1 4 3 5.
+

Example 2:

+
Input:
+n = 6
+arr[] = {2,4,7,8,9,10}
+Output: 4 2 8 7 10 9
+Explanation: Array elements after 
+sorting it in wave form are 
+4 2 8 7 10 9.
+

Your Task:
The task is to complete the function convertToWave(), which converts the given array to a wave array.

+

Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).

+

Constraints:
1 ≤ n ≤ 106
0 ≤ arr[i] ≤107

\ No newline at end of file diff --git a/Wave Array - GFG/wave-array.cpp b/Wave Array - GFG/wave-array.cpp new file mode 100644 index 00000000..21ee8fe1 --- /dev/null +++ b/Wave Array - GFG/wave-array.cpp @@ -0,0 +1,47 @@ +//{ Driver Code Starts +#include +using namespace std; +// #include + + +// } Driver Code Ends +class Solution{ + public: + // arr: input array + // n: size of array + //Function to sort the array into a wave-like array. + void convertToWave(int n, vector& arr){ + + // Your code here + + for(int i = 0; i < n-1; i += 2) + { + swap(arr[i], arr[i+1]); + } + + } +}; + +//{ Driver Code Starts. + +int main() +{ + int t,n; + cin>>t; //Input testcases + while(t--) //While testcases exist + { + cin>>n; //input size of array + vector a(n); //declare vector of size n + for(int i=0;i>a[i]; //input elements of array + sort(a.begin(),a.end()); + Solution ob; + ob.convertToWave(n, a); + + for(int i=0;i