├── 1518. Water Bottles ├── 2466. Count Ways To Build Good Strings ├── 2579. Count Total Number of Colored Cells ├── 1523-count-odd-numbers-in-an-interval-range ├── 1523-count-odd-numbers-in-an-interval-range.cpp └── README.md ├── 3370. Smallest Number With All Set Bits ├── 3133. Minimum Array End ├── 1780. Check if Number is a Sum of Powers of Three ├── 717. 1-bit and 2-bit Characters ├── 1910. Remove All Occurrences of a Substring ├── 796. Rotate String ├── 2154. Keep Multiplying Found Values by Two ├── 2169. Count Operations to Obtain Zero ├── 7. Reverse Integer ├── 2185. Counting Words With a Given Prefix ├── 2221. Find Triangular Sum of an Array ├── 3432-count-partitions-with-even-sum-difference ├── 3432-count-partitions-with-even-sum-difference.cpp └── README.md ├── 3190. Find Minimum Operations to Make All Elements Divisible by Three ├── 2490. Circular Sentence ├── 1018-binary-prefix-divisible-by-5 ├── 1018-binary-prefix-divisible-by-5.cpp └── README.md ├── 11. Container With Most Water ├── 120. Triangle ├── 2914. Minimum Number of Changes to Make Binary String Beautiful ├── 3100. Water Bottles II ├── 1752. Check if Array Is Sorted and Rotated ├── 1957. Delete Characters to Make Fancy String ├── 1346. Check If N and Its Double Exist ├── 1716. Calculate Money in Leetcode Bank ├── 3151. Special Array I ├── 1015-smallest-integer-divisible-by-k ├── 1015-smallest-integer-divisible-by-k.cpp └── README.md ├── 1925-count-square-sum-triples ├── 1925-count-square-sum-triples.cpp └── README.md ├── 2109. Adding Spaces to a String ├── 2938. Separate Black and White Balls ├── 976. Largest Perimeter Triangle ├── 14. Longest Common Prefix ├── 3396. Minimum Number of Operations to Make Elements in Array Distinct ├── 2529. Maximum Count of Positive Integer and Negative Integer ├── 3289. The Two Sneaky Numbers of Digitville ├── 3289 copy. The Two Sneaky Numbers of Digitville ├── 1578. Minimum Time to Make Rope Colorful ├── 1611. Minimum One Bit Operations to Make Integers Zero ├── 2558. Take Gifts From the Richest Pile ├── 2270. Number of Ways to Split Array ├── 9. Palindrome Number ├── 1922. Count Good Numbers ├── 1545. Find Kth Bit in Nth Binary String ├── 1128. Number of Equivalent Domino Pairs ├── 2275. Largest Combination With Bitwise AND Greater Than Zero ├── 2530. Maximal Score After Applying K Operations ├── 2598. Smallest Missing Non-negative Integer After Operations ├── 1526. Minimum Number of Increments on Subarrays to Form a Target Array ├── 2379. Minimum Recolors to Get K Consecutive Black Blocks ├── 2554. Maximum Number of Integers to Choose From a Range I ├── 1400. Construct K Palindrome Strings ├── 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence ├── 2570. Merge Two 2D Arrays by Summing Values ├── 3174. Clear Digits ├── 3461. Check If Digits Are Equal in String After Operations I ├── 1829. Maximum XOR for Each Query ├── 3542. Minimum Operations to Convert All Elements to Zero ├── 2044. Count Number of Maximum Bitwise-OR Subsets ├── 2364. Count Number of Bad Pairs ├── 3228. Maximum Number of Operations to Move Ones to the End ├── 2017. Grid Game ├── 2110-number-of-smooth-descent-periods-of-a-stock ├── 2110-number-of-smooth-descent-periods-of-a-stock.cpp └── README.md ├── 611. Valid Triangle Number ├── 2375. Construct Smallest Number From DI String ├── 2406. Divide Intervals Into Minimum Number of Groups ├── 3381. Maximum Subarray Sum With Length Divisible by K ├── 2125. Number of Laser Beams in a Bank ├── 3350. Adjacent Increasing Subarrays Detection II ├── 1980. Find Unique Binary String ├── 1261. Find Elements in a Contaminated Binary Tree ├── 1524. Number of Sub-arrays With Odd Sum ├── 1800. Maximum Ascending Subarray Sum ├── 2563. Count the Number of Fair Pairs ├── 1233. Remove Sub-Folders from the Filesystem ├── 2762. Continuous Subarrays ├── 2551. Put Marbles in Bags ├── 2780. Minimum Index of a Valid Split ├── 1408. String Matching in an Array ├── 1769. Minimum Number of Operations to Move All Balls to Each Box ├── 2300. Successful Pairs of Spells and Potions ├── 3229. Minimum Operations to Make Array Equal to Target ├── 1726. Tuple with Same Product ├── 3254. Find the Power of K-Size Subarrays I ├── 763. Partition Labels ├── 165. Compare Version Numbers ├── 2965. Find Missing and Repeated Values ├── 3397. Maximum Number of Distinct Elements After Operations ├── 2501. Longest Square Streak in an Array ├── 3169. Count Days Without Meetings ├── 2054. Two Best Non-Overlapping Events ├── 2425. Bitwise XOR of All Pairings ├── 670.Mazximum Swap ├── 2683. Neighboring Bitwise XOR ├── 3264. Final Array State After K Multiplication Operations I ├── 1352. Product of the Last K Numbers ├── 1072. Flip Columns For Maximum Number of Equal Rows ├── 1475. Final Prices With a Special Discount in a Shop ├── 2825. Make String a Subsequence Using Cyclic Increments ├── 1039. Minimum Score Triangulation of Polygon ├── 2033. Minimum Operations to Make a Uni-Value Grid ├── 2537. Count the Number of Good Subarrays ├── 1652. Defuse the Bomb ├── 3494. Find the Minimum Amount of Time to Brew Potions ├── 3223. Minimum Length of String After Operations ├── 812. Largest Triangle Area ├── 2461. Maximum Sum of Distinct Subarrays With Length K ├── 1358. Number of Substrings Containing All Three Characters ├── 2342. Max Sum of a Pair With Equal Sum of Digits ├── 3349. Adjacent Increasing Subarrays Detection I ├── 3005. Count Elements With Maximum Frequency ├── 3066. Minimum Operations to Exceed Threshold Value II ├── 2843. Count Symmetric Integers ├── 1267. Count Servers that Communicate ├── 2226. Maximum Candies Allocated to K Children ├── 1079. Letter Tile Possibilities ├── 3105. Longest Strictly Increasing or Strictly Decreasing Subarray ├── 2560. House Robber IV ├── 3354. Make Array Elements Equal to Zero ├── 1593. Split a String Into the Max Number of Unique Substrings ├── 1760. Minimum Limit of Balls in a Bag ├── 3011. Find if Array Can Be Sorted ├── 3163. String Compression III ├── 2594. Minimum Time to Repair Cars ├── 1930. Unique Length-3 Palindromic Subsequences ├── 2779. Maximum Beauty of an Array After Applying Operation ├── 2273. Find Resultant Array After Removing Anagrams ├── 3160. Find the Number of Distinct Colors Among the Balls ├── 2583. Kth Largest Sum in a Binary Tree ├── 1262-greatest-sum-divisible-by-three ├── 1262-greatest-sum-divisible-by-three.cpp └── README.md ├── 983. Minimum Cost For Tickets ├── 2661. First Completely Painted Row or Column ├── 3531-count-covered-buildings └── 3531-count-covered-buildings.cpp ├── 0047-permutations-ii ├── README.md └── 0047-permutations-ii.cpp ├── 951. Flip Equivalent Binary Trees ├── 2872. Maximum Number of K-Divisible Components ├── 916. Word Subsets ├── 2381. Shifting Letters II ├── 416. Partition Equal Subset Sum ├── 2601. Prime Subtraction Operation ├── 1930. Unique Length-3 Palindromic Subsequences1 ├── 1277. Count Square Submatrices with All Ones ├── 757. Set Intersection Size At Least Two ├── 1671. Minimum Number of Removals to Make Mountain Array ├── 2559. Count Vowel Strings in Ranges ├── 3318. Find X-Sum of All K-Long Subarrays I ├── 873. Length of Longest Fibonacci Subsequence ├── 2349. Design a Number Container System ├── 1861. Rotating the Box ├── 2536. Increment Submatrices by One ├── 1415. The k-th Lexicographical String of All Happy Strings of Length n ├── 2593. Find Score of an Array After Marking All Elements ├── 494. Target Sum ├── 166. Fraction to Recurring Decimal ├── 515. Find Largest Value in Each Tree Row ├── 2290. Minimum Obstacle Removal to Reach Corner ├── 1405. Longest Happy String ├── 2211-count-collisions-on-a-road ├── 2211-count-collisions-on-a-road.cpp └── README.md ├── 2429. Minimize XOR ├── 3356. Zero Array Transformation II ├── 802. Find Eventual Safe States ├── 2043. Simple Bank System ├── 2658. Maximum Number of Fish in a Grid ├── 632. Smallest Range Covering Elements from K Lists ├── 2048. Next Greater Numerically Balanced Number ├── 2182. Construct String With Repeat Limit ├── 2528. Maximize the Minimum Powered City ├── 2657. Find the Prefix Common Array of Two Arrays Solved Medium Topics Companies Hint ├── 3208. Alternating Groups II ├── 862. Shortest Subarray with Sum at Least K ├── 1765. Map of Highest Peak ├── 1792. Maximum Average Pass Ratio ├── 1462. Course Schedule IV ├── 2684. Maximum Number of Moves in a Grid ├── 3578-count-partitions-with-max-min-difference-at-most-k ├── 3578-count-partitions-with-max-min-difference-at-most-k.cpp └── README.md ├── 1106. Parsing A Boolean Expression ├── 2463. Minimum Total Distance Traveled ├── 1942_The Number of the Smallest Unoccupied Chair ├── 1639. Number of Ways to Form a Target String Given a Dictionary ├── 2948. Make Lexicographically Smallest Array by Swapping ├── 3097. Shortest Subarray With OR at Least K II ├── 2415. Reverse Odd Levels of Binary Tree ├── 684. Redundant Connection ├── 2116. Check if a Parentheses String Can Be Valid ├── 2097. Valid Arrangement of Pairs ├── 3152. Special Array II ├── 3203. Find Minimum Diameter After Merging Two Trees ├── 208. Implement Trie (Prefix Tree) ├── 2471. Minimum Number of Operations to Sort a Binary Tree by Level ├── 417. Pacific Atlantic Water Flow ├── 2257. Count Unguarded Cells in the Grid ├── 2577. Minimum Time to Visit a Cell In a Grid ├── 1408. String Matching in an Array(kmp) ├── 3243. Shortest Distance After Road Addition Queries I ├── 2641. Cousins in Binary Tree II ├── 1092. Shortest Common Supersequence ├── 2685. Count the Number of Complete Components ├── 3508. Implement Router ├── 2940. Find Building Where Alice and Bob Can Meet ├── 3306. Count of Substrings Containing Every Vowel and K Consonants II ├── stats.json ├── 1976. Number of Ways to Arrive at Destination ├── 2337. Move Pieces to Obtain a String ├── 3321. Find X-Sum of All K-Long Subarrays II ├── 3347. Maximum Frequency of an Element After Performing Operations II ├── 2127. Maximum Employees to Be Invited to a Meeting └── 3539. Find Sum of Array Product of Magical Sequences /1518. Water Bottles: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWaterBottles(int b,int n) { 4 | return b+(b-1)/(n-1); 5 | } 6 | }; -------------------------------------------------------------------------------- /2466. Count Ways To Build Good Strings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countGoodStrings(int low, int high, int zero, int one) { 4 | 5 | } 6 | }; -------------------------------------------------------------------------------- /2579. Count Total Number of Colored Cells: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long coloredCells(int n) { 4 | return 1+(long long)n*(n-1)*2; 5 | } 6 | }; -------------------------------------------------------------------------------- /1523-count-odd-numbers-in-an-interval-range/1523-count-odd-numbers-in-an-interval-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOdds(int low, int high) { 4 | return (high+1)/2-(low/2); 5 | } 6 | }; -------------------------------------------------------------------------------- /3370. Smallest Number With All Set Bits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestNumber(int n) { 4 | int x=1; 5 | while(x0) { 5 | if (n % 3 == 2) return false; 6 | n /= 3; 7 | } 8 | return true; 9 | } 10 | }; -------------------------------------------------------------------------------- /717. 1-bit and 2-bit Characters: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isOneBitCharacter(vector& bits) { 4 | int n=bits.size(); 5 | int i=0; 6 | while(i& nums, int original) { 4 | unordered_sets(nums.begin(),nums.end()); 5 | 6 | while(s.count(original)){ 7 | original*=2; 8 | } 9 | return original; 10 | } 11 | }; -------------------------------------------------------------------------------- /2169. Count Operations to Obtain Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOperations(int num1, int num2) { 4 | int res=0; 5 | while(num1 && num2){ 6 | res+=num1/num2; 7 | num1%=num2; 8 | swap(num1,num2); 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /7. Reverse Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | 5 | long sum=0; 6 | while(x){ 7 | int rem=x%10; 8 | sum=sum*10+rem; 9 | x=x/10; 10 | } 11 | if(sum>INT_MAX || sum& words, string pref) { 4 | int count=0; 5 | for(int i=0;i& nums) { 4 | for (int i = 1; i < nums.size(); i++) { 5 | for (int j = 0; j < nums.size() - i; j++) { 6 | nums[j] = (nums[j] + nums[j+1]) % 10; 7 | } 8 | } 9 | return nums[0]; 10 | } 11 | }; -------------------------------------------------------------------------------- /3432-count-partitions-with-even-sum-difference/3432-count-partitions-with-even-sum-difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPartitions(vector& nums) { 4 | int totalSum = 0; 5 | for (int x : nums) { 6 | totalSum += x; 7 | } 8 | return totalSum % 2 == 0 ? nums.size() - 1 : 0; 9 | } 10 | }; -------------------------------------------------------------------------------- /3190. Find Minimum Operations to Make All Elements Divisible by Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOperations(vector& nums) { 4 | int count=0; 5 | for(int num:nums){ 6 | int r=num%3; 7 | 8 | if(r==0)continue; 9 | count+=min(r,3-r); 10 | } 11 | return count; 12 | } 13 | }; -------------------------------------------------------------------------------- /2490. Circular Sentence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isCircularSentence(string sentence) { 4 | for(int i=0;i prefixesDivBy5(vector& nums) { 4 | vectorans; 5 | int val=0; 6 | 7 | for(int num:nums){ 8 | val=(val*2+num)%5; 9 | 10 | ans.push_back(val==0); 11 | } 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /11. Container With Most Water: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int i=0,j=height.size()-1; 5 | int res=0; 6 | while(i>& triangle) { 4 | int n=triangle.size(); 5 | for (int i =n- 2; i >= 0; i--) 6 | for (int j = 0; j < triangle[i].size(); j++) 7 | triangle[i][j] +=min(triangle[i + 1][j], triangle[i + 1][j + 1]); 8 | 9 | return triangle[0][0]; 10 | } 11 | }; -------------------------------------------------------------------------------- /2914. Minimum Number of Changes to Make Binary String Beautiful: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minChanges(string s) { 4 | int count = 0; 5 | for(int i = 0; i < s.size(); i += 2) { 6 | if (s.substr(i, 2) == "10" || s.substr(i, 2) == "01") { 7 | count++; 8 | } 9 | } 10 | return count; 11 | } 12 | }; -------------------------------------------------------------------------------- /3100. Water Bottles II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxBottlesDrunk(int numBottles, int numExchange) { 4 | int a = 1; 5 | int b = 2 * numExchange - 3; 6 | int c = -2 * numBottles; 7 | double delta = (double)b * b - 4.0 * a * c; 8 | int t = (int)ceil((-b + sqrt(delta)) / (2.0 * a)); 9 | return numBottles + t - 1; 10 | } 11 | }; -------------------------------------------------------------------------------- /1752. Check if Array Is Sorted and Rotated: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(vector& arr) { 4 | int n=arr.size(); 5 | 6 | int count=0; 7 | 8 | for(int i=1;iarr[0])count++; 15 | 16 | return count<=1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /1957. Delete Characters to Make Fancy String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeFancyString(string s) { 4 | if(s.size()<3)return s; 5 | int j=2; 6 | for(int i=2;i& arr) { 4 | unordered_set s; 5 | for (int num : arr) { 6 | if (s.count(2 * num) || (num % 2 == 0 && s.count(num / 2))) { 7 | return true; 8 | } 9 | s.insert(num); 10 | } 11 | 12 | return false; 13 | } 14 | }; -------------------------------------------------------------------------------- /1716. Calculate Money in Leetcode Bank: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalMoney(int n) { 4 | int ans=0; 5 | int monday=1; 6 | 7 | while(n>0){ 8 | for(int day=0;day& nums) { 4 | int n = nums.size(); 5 | if (n == 1) return true; 6 | 7 | for (int i = 0; i < n - 1; i++) { 8 | if (nums[i] % 2 == nums[i+1] % 2 ) { 9 | 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /1015-smallest-integer-divisible-by-k/1015-smallest-integer-divisible-by-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestRepunitDivByK(int k) { 4 | int remainder=0; 5 | 6 | for(int len=1;len<=k;len++){ 7 | remainder=(remainder*10+1)%k; 8 | 9 | if(remainder==0){ 10 | return len; 11 | } 12 | } 13 | return -1; 14 | } 15 | }; -------------------------------------------------------------------------------- /1925-count-square-sum-triples/1925-count-square-sum-triples.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countTriples(int n) { 4 | int count=0; 5 | 6 | for(int a=1;a<=n;a++){ 7 | for(int b=1;b<=n;b++){ 8 | int c=int(sqrt(a*a+b*b+1.0)); 9 | 10 | if(c<=n && c*c==a*a+b*b)count++; 11 | } 12 | } 13 | return count; 14 | } 15 | }; -------------------------------------------------------------------------------- /2109. Adding Spaces to a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addSpaces(string s, vector& spaces) { 4 | stringstream result; 5 | int j=0; 6 | for(int i=0;i& nums) { 4 | int maxi=0; 5 | int n=nums.size(); 6 | sort(nums.begin(),nums.end()); 7 | 8 | for(int i=n-1;i>=2;i--){ 9 | if(nums[i-1]+nums[i-2]>nums[i]){ 10 | return nums[i]+nums[i-1]+nums[i-2]; 11 | } 12 | } 13 | return 0; 14 | } 15 | }; -------------------------------------------------------------------------------- /14. Longest Common Prefix: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | string ans; 5 | sort(strs.begin(),strs.end()); 6 | string start=strs[0],end=strs[strs.size()-1]; 7 | for(int i=0;i& nums) { 4 | int n=nums.size(); 5 | vectorseen(128); 6 | for(int i=n-1;i>=0;i--){ 7 | if(seen[nums[i]]){ 8 | return i/3+1; 9 | } 10 | seen[nums[i]]=true; 11 | } 12 | return 0; 13 | } 14 | }; -------------------------------------------------------------------------------- /2529. Maximum Count of Positive Integer and Negative Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumCount(vector& nums) { 4 | int pos=0,neg=0; 5 | 6 | for(int i=0;i0){ 11 | pos++; 12 | } 13 | } 14 | return max(pos,neg); 15 | } 16 | }; -------------------------------------------------------------------------------- /3289. The Two Sneaky Numbers of Digitville: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getSneakyNumbers(vector& nums) { 4 | vectorresult; 5 | 6 | unordered_mapmp; 7 | 8 | for(int num:nums){ 9 | mp[num]++; 10 | } 11 | 12 | for(auto it:mp){ 13 | if(it.second>1)result.push_back(it.first); 14 | 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /3289 copy. The Two Sneaky Numbers of Digitville: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getSneakyNumbers(vector& nums) { 4 | vectorresult; 5 | 6 | unordered_mapmp; 7 | 8 | for(int num:nums){ 9 | mp[num]++; 10 | } 11 | 12 | for(auto it:mp){ 13 | if(it.second>1)result.push_back(it.first); 14 | 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /1578. Minimum Time to Make Rope Colorful: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(string colors, vector& neededTime) { 4 | int total=0,currmax=0; 5 | 6 | for(int i=0;i0 && colors[i]!=colors[i-1]){ 8 | currmax=0; 9 | } 10 | 11 | total+=min(currmax,neededTime[i]); 12 | currmax=max(currmax,neededTime[i]); 13 | } 14 | return total; 15 | } 16 | }; -------------------------------------------------------------------------------- /1611. Minimum One Bit Operations to Make Integers Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOneBitOperations(int n) { 4 | if (n == 0) { 5 | return 0; 6 | } 7 | 8 | int k = 0; 9 | int curr = 1; 10 | while (curr * 2 <= n) { 11 | curr *= 2; 12 | k++; 13 | } 14 | 15 | return (1 << (k + 1)) - 1 - minimumOneBitOperations(n ^ curr); 16 | } 17 | }; -------------------------------------------------------------------------------- /2558. Take Gifts From the Richest Pile: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long pickGifts(vector& gifts, int k) { 4 | priority_queueq; 5 | long long ans=0; 6 | for(int i:gifts){q.push(i);ans+=i;} 7 | while(k--) 8 | { 9 | int v=q.top(); 10 | ans-=(v-sqrt(v)); 11 | q.pop(); 12 | q.push(sqrt(v)); 13 | } 14 | return ans; 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /2270. Number of Ways to Split Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int waysToSplitArray(vector& nums) { 4 | long long leftsum = 0, rightsum = accumulate(nums.begin(), nums.end(), 0LL); 5 | int count = 0; 6 | 7 | for (int i = 0; i < nums.size() - 1; i++) { 8 | leftsum += nums[i]; 9 | rightsum-=nums[i]; 10 | if (leftsum>=rightsum) count++; 11 | } 12 | 13 | return count; 14 | } 15 | }; -------------------------------------------------------------------------------- /9. Palindrome Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | int n=x; 5 | long long sum=0; 6 | if(x<0) 7 | return false; 8 | 9 | 10 | while(n!=0){ 11 | int rem=n%10; 12 | sum=sum*10+rem; 13 | n=n/10; 14 | } 15 | if(x==sum) 16 | return true; 17 | 18 | 19 | return false; 20 | 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /1922. Count Good Numbers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | typedef long long ll; 4 | ll mod=1e9+7; 5 | ll pow(ll n,ll e){ 6 | if(e==0)return 1; 7 | 8 | ll ans=pow(n,e/2); 9 | ans*=ans; 10 | ans%=mod; 11 | 12 | if(e%2) ans=(ans * n) % mod; 13 | return ans; 14 | } 15 | int countGoodNumbers(long long n) { 16 | ll odd=(n+1)/2; 17 | ll even=n/2; 18 | 19 | return (pow(5,odd)*pow(4,even))%mod; 20 | } 21 | }; -------------------------------------------------------------------------------- /1545. Find Kth Bit in Nth Binary String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findKthBit(int n, int k) { 4 | int positionInSection = k & -k; 5 | bool isInInvertedPart = ((k / positionInSection) >> 1 & 1) == 1; 6 | bool originalBitIsOne = (k & 1) == 0; 7 | 8 | if (isInInvertedPart) { 9 | return originalBitIsOne ? '0' : '1'; 10 | } else { 11 | 12 | return originalBitIsOne ? '1' : '0'; 13 | } 14 | } 15 | }; -------------------------------------------------------------------------------- /1128. Number of Equivalent Domino Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numEquivDominoPairs(vector>& dominoes) { 4 | 5 | int count=0; 6 | vectorres(100); 7 | for(auto& d:dominoes){ 8 | if(d[0]>d[1]){ 9 | swap(d[0],d[1]); 10 | } 11 | int num=10*d[0]+d[1]; 12 | count+=res[num]; 13 | res[num]++; 14 | } 15 | return count; 16 | 17 | } 18 | }; -------------------------------------------------------------------------------- /2275. Largest Combination With Bitwise AND Greater Than Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestCombination(vector& candidates) { 4 | int maxcount=0; 5 | for(int i=0;i<24;i++){ 6 | int count=0; 7 | for(int num:candidates){ 8 | if((num&(1<& nums, int k) { 4 | priority_queueq; 5 | for(int i=0;i& nums, int value) { 4 | unordered_mapmp; 5 | 6 | for(int &num:nums){ 7 | int r=((num%value)+value)%value; 8 | mp[r]++; 9 | } 10 | 11 | int MEX=0; 12 | 13 | while(mp[MEX%value]>0){ 14 | mp[(MEX%value)]--; 15 | MEX++; 16 | } 17 | return MEX; 18 | } 19 | }; -------------------------------------------------------------------------------- /1526. Minimum Number of Increments on Subarrays to Form a Target Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minNumberOperations(vector& target) { 4 | int n=target.size(); 5 | int prev=0,curr=0; 6 | long long result=0; 7 | for(int i=0;iabs(prev)){ 11 | result+=abs(curr-prev); 12 | } 13 | 14 | prev=curr; 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /2379. Minimum Recolors to Get K Consecutive Black Blocks: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumRecolors(string blocks, int k) { 4 | int i=0,countw=0,mini=INT_MAX; 5 | int n=blocks.size(); 6 | for(int j=0;j& banned, int n, int maxSum) { 4 | unordered_set bannedSet(banned.begin(), banned.end()); 5 | int count = 0; 6 | for (int num = 1; num <= n; num++) { 7 | if (bannedSet.count(num)) continue; 8 | if (maxSum - num < 0) return count; 9 | maxSum -= num; 10 | count++; 11 | } 12 | return count; 13 | } 14 | }; -------------------------------------------------------------------------------- /1400. Construct K Palindrome Strings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string s, int k) { 4 | if(s.length()freq(26); 8 | int oddcount=0; 9 | 10 | for(int i=0;i>word){ 10 | if(word.length()>=searchWord.length() && word.compare(0,searchWord.length(),searchWord)==0){ 11 | return i; 12 | } 13 | i++; 14 | } 15 | return -1; 16 | } 17 | }; -------------------------------------------------------------------------------- /2570. Merge Two 2D Arrays by Summing Values: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> mergeArrays(vector>& nums1, vector>& nums2) { 4 | mapmp; 5 | vector>ans; 6 | for(auto i:nums1){ 7 | mp[i[0]]=i[1]; 8 | } 9 | for(auto i:nums2){ 10 | mp[i[0]]+=i[1]; 11 | } 12 | 13 | for(auto i:mp){ 14 | ans.push_back({i.first,i.second}); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /3174. Clear Digits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string clearDigits(string s) { 4 | int i=0,j=0; 5 | 6 | int n=s.size(); 7 | 8 | while(i2 && i getMaximumXor(vector& nums, int maximumBit) { 4 | int n=nums.size(); 5 | vectorresult; 6 | int Xor=0; 7 | for(int i=0;i& nums) { 4 | vectors; 5 | int res=0; 6 | for (int a : nums) { 7 | while (!s.empty() && s.back()>a) { 8 | s.pop_back(); 9 | } 10 | if (a==0) continue; 11 | if (s.empty() || s.back()& nums) { 4 | int max = 0; 5 | vector dp(1 << 17, 0); 6 | 7 | 8 | dp[0] = 1; 9 | 10 | for (int num : nums) { 11 | for (int i = max; i >= 0; i--) { 12 | 13 | dp[i | num] += dp[i]; 14 | } 15 | 16 | max |= num; 17 | } 18 | 19 | return dp[max]; 20 | } 21 | };1545. Find Kth Bit in Nth Binary String -------------------------------------------------------------------------------- /2364. Count Number of Bad Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countBadPairs(vector& nums) { 4 | long long n=nums.size(); 5 | long long totalpair=n*(n-1)/2; 6 | 7 | unordered_mapmp; 8 | long long goodpair=0; 9 | 10 | for(int i=0;i>& grid) { 4 | long long firstrowsum=accumulate(grid[0].begin(),grid[0].end(),0LL); 5 | 6 | long long secondrowsum=0; 7 | long long mini=LONG_LONG_MAX; 8 | for(int col=0;col& prices) { 4 | long long ans=1; 5 | long long len=1; 6 | 7 | for(int i=1;i& nums) { 4 | int count=0; 5 | int n=nums.size(); 6 | 7 | sort(nums.begin(), nums.end()); 8 | for(int i=0;i nums[k]) 12 | k++; 13 | count += k-j-1; 14 | } 15 | } 16 | return count; 17 | } 18 | }; -------------------------------------------------------------------------------- /2375. Construct Smallest Number From DI String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string smallestNumber(string pattern) { 4 | int n=pattern.size(); 5 | 6 | stackst; 7 | string num=""; 8 | for(int i=0;i<=n;i++){ 9 | st.push(i+1); 10 | 11 | if(i==n || pattern[i]=='I'){ 12 | while(!st.empty()){ 13 | num+=to_string(st.top()); 14 | st.pop(); 15 | } 16 | } 17 | } 18 | return num; 19 | } 20 | }; -------------------------------------------------------------------------------- /2406. Divide Intervals Into Minimum Number of Groups: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minGroups(vector>& intervals) { 4 | sort(intervals.begin(),intervals.end()); 5 | priority_queue,greater>pq; 6 | for (const auto& interval : intervals){ 7 | int start = interval[0], end = interval[1]; 8 | if(!pq.empty() && pq.top()& nums, int k) { 4 | long long maxsum=LONG_LONG_MIN,prefixsum=0; 5 | int n=nums.size(); 6 | vector prefix(k, LLONG_MAX/2); 7 | prefix[k-1]=0; 8 | 9 | for(int i=0;i& bank) { 4 | int prev = 0, ans = 0; 5 | 6 | for (string s : bank) { 7 | int count = 0; 8 | for (char c : s) { 9 | if (c == '1') { 10 | count++; 11 | } 12 | } 13 | if (count != 0) { 14 | ans += (prev * count); 15 | prev = count; 16 | } 17 | } 18 | 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /3350. Adjacent Increasing Subarrays Detection II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIncreasingSubarrays(vector& nums) { 4 | 5 | int n=nums.size(); 6 | 7 | int cnt=1,prev=0,ans=0; 8 | 9 | for(int i=1;inums[i-1]){ 11 | cnt++; 12 | } 13 | else{ 14 | prev=cnt; 15 | cnt=1; 16 | } 17 | ans=max(ans,min(prev,cnt)); 18 | ans=max(ans,cnt/2); 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /1980. Find Unique Binary String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string findDifferentBinaryString(vector& nums) { 4 | unordered_set integers; 5 | for (string num : nums) { 6 | integers.insert(stoi(num, 0, 2)); 7 | } 8 | 9 | int ans = stoi(nums[0], 0, 2); 10 | int n = nums.size(); 11 | 12 | while (integers.find(ans) != integers.end()) { 13 | ans = rand() % (int) pow(2, n); 14 | } 15 | 16 | return bitset<16>(ans).to_string().substr(16 - n); 17 | } 18 | }; -------------------------------------------------------------------------------- /1261. Find Elements in a Contaminated Binary Tree: -------------------------------------------------------------------------------- 1 | class FindElements { 2 | public: 3 | FindElements(TreeNode* root) { dfs(root, 0); } 4 | 5 | bool find(int target) { return seen.count(target) > 0; } 6 | 7 | private: 8 | unordered_set seen; 9 | 10 | void dfs(TreeNode* currentNode, int currentValue) { 11 | if (!currentNode) return; 12 | // visit current node by adding its value to seen 13 | seen.insert(currentValue); 14 | dfs(currentNode->left, currentValue * 2 + 1); 15 | dfs(currentNode->right, currentValue * 2 + 2); 16 | } 17 | }; -------------------------------------------------------------------------------- /1524. Number of Sub-arrays With Odd Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mod=1e9+7; 4 | int numOfSubarrays(vector& arr) { 5 | int count=0,prefixsum=0; 6 | 7 | int odd=0,even=1; 8 | 9 | for(int num:arr){ 10 | prefixsum+=num; 11 | 12 | if(prefixsum%2==0){ 13 | count+=odd; 14 | even++; 15 | } 16 | else{ 17 | count+=even; 18 | odd++; 19 | } 20 | count=count%mod; 21 | } 22 | return count; 23 | } 24 | }; -------------------------------------------------------------------------------- /1800. Maximum Ascending Subarray Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAscendingSum(vector& nums) { 4 | int n=nums.size(); 5 | if(n==1)return nums[0]; 6 | 7 | int sum=nums[0],maxsum=nums[0]; 8 | for(int i=1;inums[i-1]){ 10 | sum+=nums[i]; 11 | maxsum=max(maxsum,sum); 12 | } 13 | else{ 14 | sum=nums[i]; 15 | } 16 | 17 | 18 | } 19 | 20 | 21 | return maxsum; 22 | } 23 | }; -------------------------------------------------------------------------------- /2563. Count the Number of Fair Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countFairPairs(vector& nums, int lower, int upper) { 4 | int n=nums.size(); 5 | sort(nums.begin(),nums.end()); 6 | long long result=0; 7 | for(int i=0;i removeSubfolders(vector& folder) { 4 | sort(folder.begin(), folder.end()); 5 | vector result; 6 | result.push_back(folder[0]); 7 | for (int i = 1; i < folder.size(); i++) { 8 | string lastFolder = result.back(); 9 | lastFolder += '/'; 10 | if (folder[i].compare(0, lastFolder.size(), lastFolder) != 0) { 11 | result.push_back(folder[i]); 12 | } 13 | } 14 | return result; 15 | } 16 | }; -------------------------------------------------------------------------------- /2762. Continuous Subarrays: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long continuousSubarrays(vector& nums) { 4 | mapmp; 5 | int i=0,j=0,n=nums.size(); 6 | long long count=0; 7 | while(jfirst-mp.rbegin()->first)>2){ 11 | mp[nums[i]]--; 12 | if(mp[nums[i]]==0){ 13 | mp.erase(nums[i]); 14 | } 15 | i++; 16 | } 17 | count+=j-i+1; 18 | j++; 19 | } 20 | return count; 21 | } 22 | }; -------------------------------------------------------------------------------- /2551. Put Marbles in Bags: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long putMarbles(vector& weights, int k) { 4 | int n=weights.size(); 5 | int m=n-1; 6 | vectorpairsum(m,0); 7 | 8 | for(int i=0;i& nums) { 4 | unordered_mapmp1,mp2; 5 | int n=nums.size(); 6 | for(int num:nums){ 7 | mp2[num]++; 8 | } 9 | 10 | for(int i=0;in1 && mp2[num]*2>n2){ 19 | return i; 20 | } 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /1408. String Matching in an Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector stringMatching(vector& words) { 4 | vector str; 5 | 6 | for (int i = 0; i < words.size(); i++) { 7 | for (int j = 0; j < words.size(); j++) { 8 | if (i != j) { 9 | auto found = words[j].find(words[i]); 10 | if (found != string::npos) { 11 | str.push_back(words[i]); 12 | break; 13 | } 14 | } 15 | } 16 | } 17 | return str; 18 | } 19 | }; -------------------------------------------------------------------------------- /1769. Minimum Number of Operations to Move All Balls to Each Box: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector minOperations(string boxes) { 4 | vector answer(boxes.length()); 5 | for (int currentBox = 0; currentBox < boxes.length(); currentBox++) { 6 | 7 | if (boxes[currentBox] == '1') { 8 | for (int newPosition = 0; newPosition < boxes.length(); 9 | newPosition++) { 10 | answer[newPosition] += abs(newPosition - currentBox); 11 | } 12 | } 13 | } 14 | return answer; 15 | } 16 | }; -------------------------------------------------------------------------------- /2300. Successful Pairs of Spells and Potions: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector successfulPairs(vector& spells, vector& potions, long long success) { 4 | sort(potions.begin(), potions.end()); 5 | int n = spells.size(), m = potions.size(); 6 | vector ans(n); 7 | 8 | for (int i = 0; i < n; i++) { 9 | long long minPotion = (success + spells[i] - 1) / spells[i]; 10 | int idx = lower_bound(potions.begin(), potions.end(), minPotion) - potions.begin(); 11 | ans[i] = m - idx; 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /3229. Minimum Operations to Make Array Equal to Target: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long minimumOperations(vector& nums, vector& target) { 4 | int n=nums.size(); 5 | long long result=0; 6 | int curr=0,prev=0; 7 | for(int i=0;i0 && prev<0 || curr<0 && prev>0){ 11 | result+=abs(curr); 12 | } 13 | else if(abs(curr)>abs(prev)){ 14 | result+=abs(curr-prev); 15 | } 16 | prev=curr; 17 | } 18 | return result; 19 | } 20 | }; -------------------------------------------------------------------------------- /1726. Tuple with Same Product: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tupleSameProduct(vector& nums) { 4 | int n=nums.size(); 5 | unordered_mapmp; 6 | 7 | 8 | for(int i=0;i resultsArray(vector& nums, int k) { 4 | if(k==1){ 5 | return nums; 6 | } 7 | int n=nums.size(); 8 | vectorresult(n-k+1,-1); 9 | int count=1; 10 | for(int i=0;i=k){ 19 | result[i-k+2]=nums[i+1]; 20 | } 21 | } 22 | return result; 23 | } 24 | }; -------------------------------------------------------------------------------- /763. Partition Labels: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector partitionLabels(string s) { 4 | int n=s.size(); 5 | vectorlast(26,-1); 6 | 7 | for(int i=0;iresult; 15 | while(ix2) return 1; 15 | x1=0; 16 | x2=0; 17 | } 18 | return 0; 19 | } 20 | }; -------------------------------------------------------------------------------- /2965. Find Missing and Repeated Values: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMissingAndRepeatedValues(vector>& grid) { 4 | unordered_mapmp; 5 | int n=grid.size(); 6 | int miss=-1,repeat=-1; 7 | 8 | for(auto& row:grid){ 9 | for(int num:row){ 10 | mp[num]++; 11 | } 12 | } 13 | 14 | for(int i=1;i<=n*n;i++){ 15 | if(!mp.count(i)){ 16 | miss=i; 17 | } 18 | else if(mp[i]==2){ 19 | repeat=i; 20 | } 21 | } 22 | return {repeat,miss}; 23 | } 24 | }; -------------------------------------------------------------------------------- /3397. Maximum Number of Distinct Elements After Operations: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDistinctElements(vector& nums, int k) { 4 | int n=nums.size(); 5 | 6 | sort(nums.begin(),nums.end()); 7 | int count=0; 8 | int prev=INT_MIN; 9 | 10 | for(int i=0;i& nums) { 4 | sort(nums.begin(),nums.end()); 5 | unordered_mapmp; 6 | int maxstreak=0; 7 | for(int i=0;i>& meetings) { 4 | int freeDays = 0, latestEnd = 0; 5 | 6 | sort(meetings.begin(), meetings.end()); 7 | 8 | for (auto& meeting : meetings) { 9 | int start = meeting[0], end = meeting[1]; 10 | 11 | 12 | if (start > latestEnd + 1) { 13 | freeDays += start - latestEnd - 1; 14 | } 15 | 16 | 17 | latestEnd = max(latestEnd, end); 18 | } 19 | 20 | freeDays += days - latestEnd; 21 | 22 | return freeDays; 23 | } 24 | }; -------------------------------------------------------------------------------- /2054. Two Best Non-Overlapping Events: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxTwoEvents(vector>& events) { 4 | sort(events.begin(),events.end()); 5 | priority_queue,vector>,greater>>pq; 6 | 7 | int maxval=0,maxsum=0; 8 | 9 | for(auto& event:events){ 10 | while(!pq.empty() && pq.top().first& nums1, vector& nums2) { 4 | 5 | int len1 = nums1.size(); 6 | int len2 = nums2.size(); 7 | 8 | 9 | unordered_map freq; 10 | 11 | for (int num : nums1) { 12 | freq[num] += len2; 13 | } 14 | for (int num : nums2) { 15 | freq[num] += len1; 16 | } 17 | int ans = 0; 18 | for (auto& [num, count] : freq) { 19 | if (count % 2 == 1) { 20 | ans ^= num; 21 | } 22 | } 23 | 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /670.Mazximum Swap: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumSwap(int num) { 4 | string numStr = to_string(num); 5 | int n = numStr.size(); 6 | vector lastSeen(10,-1); 7 | for (int i = 0; i < n; ++i) { 8 | lastSeen[numStr[i] - '0'] = i; 9 | } 10 | for (int i = 0; i < n; ++i) { 11 | for (int d = 9; d > numStr[i] - '0'; --d) { 12 | if (lastSeen[d] > i) { 13 | swap(numStr[i], numStr[lastSeen[d]]); 14 | return stoi(numStr); 15 | } 16 | } 17 | } 18 | 19 | return num; 20 | } 21 | }; -------------------------------------------------------------------------------- /2683. Neighboring Bitwise XOR: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool doesValidArrayExist(vector& derived) { 4 | vector original = {0}; 5 | for (int i = 0; i < derived.size(); i++) { 6 | original.push_back((derived[i] ^ original[i])); 7 | } 8 | bool checkForZero = (original[0] == original[original.size() - 1]); 9 | original = {1}; 10 | for (int i = 0; i < derived.size(); i++) { 11 | original.push_back((derived[i] ^ original[i])); 12 | } 13 | bool checkForOne = (original[0] == original[original.size() - 1]); 14 | 15 | return checkForZero | checkForOne; 16 | } 17 | }; -------------------------------------------------------------------------------- /3264. Final Array State After K Multiplication Operations I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getFinalState(vector& nums, int k, int multiplier) { 4 | priority_queue,vector>,greater>>pq; 5 | for(int i=0;ivec; 4 | ProductOfNumbers() { 5 | 6 | } 7 | 8 | void add(int num) { 9 | vec.push_back(num); 10 | } 11 | 12 | int getProduct(int k) { 13 | int product=1; 14 | int i=vec.size()-1; 15 | while(k--){ 16 | product*=vec[i]; 17 | i--; 18 | } 19 | return product; 20 | } 21 | }; 22 | 23 | /** 24 | * Your ProductOfNumbers object will be instantiated and called as such: 25 | * ProductOfNumbers* obj = new ProductOfNumbers(); 26 | * obj->add(num); 27 | * int param_2 = obj->getProduct(k); 28 | */ -------------------------------------------------------------------------------- /1072. Flip Columns For Maximum Number of Equal Rows: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxEqualRowsAfterFlips(vector>& matrix) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | unordered_mapmp; 7 | for(auto& row:matrix){ 8 | string result=""; 9 | int firstrow=row[0]; 10 | for(int col=1;col finalPrices(vector& prices) { 4 | stacks; 5 | vectorresult; 6 | int n=prices.size(); 7 | for(int i=n-1;i>=0;i--){ 8 | while(!s.empty() && s.top()>prices[i]){ 9 | s.pop(); 10 | } 11 | if(!s.empty()){ 12 | int top=s.top(); 13 | result.push_back(prices[i]-top); 14 | } 15 | else{ 16 | result.push_back(prices[i]); 17 | } 18 | 19 | s.push(prices[i]); 20 | } 21 | reverse(result.begin(),result.end()); 22 | return result; 23 | } 24 | }; -------------------------------------------------------------------------------- /2825. Make String a Subsequence Using Cyclic Increments: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMakeSubsequence(string str1, string str2) { 4 | int str2Index = 0; 5 | int lengthStr1 = str1.size(), lengthStr2 = str2.size(); 6 | for (int str1Index = 0; 7 | str1Index < lengthStr1 && str2Index < lengthStr2; ++str1Index) { 8 | if (str1[str1Index] == str2[str2Index] || 9 | (str1[str1Index] + 1 == str2[str2Index]) || 10 | (str1[str1Index] - 25 == str2[str2Index])) { 11 | 12 | str2Index++; 13 | } 14 | } 15 | 16 | return str2Index == lengthStr2; 17 | } 18 | }; -------------------------------------------------------------------------------- /1039. Minimum Score Triangulation of Polygon: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mini(vector& v,int i,int j,vector>& dp){ 4 | if(j-i<=1)return 0; 5 | if(j-i==2)return v[i]*v[i+1]*v[j]; 6 | if(dp[i][j]!=-1)return dp[i][j]; 7 | int res=INT_MAX; 8 | for(int k=i+1;k<=j-1;k++){ 9 | res = min(res, mini(v, i, k, dp) + v[i] * v[j] * v[k] + mini(v, k, j, dp)); 10 | 11 | } 12 | dp[i][j]=res; 13 | return res; 14 | } 15 | int minScoreTriangulation(vector& values) { 16 | int n=values.size(); 17 | vector>dp(n,vector(n,-1)); 18 | return mini(values,0,n-1,dp); 19 | } 20 | }; -------------------------------------------------------------------------------- /2033. Minimum Operations to Make a Uni-Value Grid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector>& grid, int x) { 4 | vectorarr; 5 | int result=0; 6 | for(int i=0;i& nums, int k) { 4 | unordered_map freq; 5 | int left = 0; 6 | long long pairCount = 0, goodSubarrays = 0; 7 | 8 | for (int right = 0; right < nums.size(); ++right) { 9 | pairCount += freq[nums[right]]; 10 | freq[nums[right]]++; 11 | 12 | while (pairCount >= k) { 13 | goodSubarrays += nums.size() - right; 14 | freq[nums[left]]--; 15 | pairCount -= freq[nums[left]]; 16 | left++; 17 | } 18 | } 19 | 20 | return goodSubarrays; 21 | } 22 | }; -------------------------------------------------------------------------------- /1652. Defuse the Bomb: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector decrypt(vector& code, int k) { 4 | vector result(code.size(), 0); 5 | if (k == 0) return result; 6 | int start = 1, end = k, sum = 0; 7 | if (k < 0) { 8 | start = code.size() - abs(k); 9 | end = code.size() - 1; 10 | } 11 | for (int i = start; i <= end; i++) sum += code[i]; 12 | for (int i = 0; i < code.size(); i++) { 13 | result[i] = sum; 14 | sum -= code[start % code.size()]; 15 | sum += code[(end + 1) % code.size()]; 16 | start++; 17 | end++; 18 | } 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /3494. Find the Minimum Amount of Time to Brew Potions: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | using ll = long long; 4 | long long minTime(vector& skill, vector& mana) { 5 | int n = skill.size(), m = mana.size(); 6 | vector times(n); 7 | for (int j = 0; j < m; j++) { 8 | ll cur_time = 0; 9 | for (int i = 0; i < n; i++) { 10 | cur_time = max(cur_time, times[i]) + skill[i] * mana[j]; 11 | } 12 | times[n - 1] = cur_time; 13 | for (int i = n - 2; i >= 0; i--) { 14 | times[i] = times[i + 1] - skill[i + 1] * mana[j]; 15 | } 16 | } 17 | return times[n - 1]; 18 | } 19 | }; -------------------------------------------------------------------------------- /3223. Minimum Length of String After Operations: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumLength(string s) { 4 | 5 | unordered_map charFrequencyMap; 6 | for (char currentChar : s) { 7 | charFrequencyMap[currentChar]++; 8 | } 9 | 10 | int deleteCount = 0; 11 | for (auto& pair : charFrequencyMap) { 12 | int frequency = pair.second; 13 | if (frequency % 2 == 1) { 14 | 15 | deleteCount += frequency - 1; 16 | } else { 17 | 18 | deleteCount += frequency - 2; 19 | } 20 | } 21 | 22 | 23 | return s.length() - deleteCount; 24 | } 25 | }; -------------------------------------------------------------------------------- /812. Largest Triangle Area: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double area(vector& P, vector& Q, vector& R) { 4 | return 0.5 * abs(P[0]*Q[1] + Q[0]*R[1] + R[0]*P[1] 5 | - P[1]*Q[0] - Q[1]*R[0] - R[1]*P[0]); 6 | } 7 | double largestTriangleArea(vector>& points) { 8 | int n = points.size(); 9 | double ans = 0.0; 10 | for (int i = 0; i < n; ++i) { 11 | for (int j = i + 1; j < n; ++j) { 12 | for (int k = j + 1; k < n; ++k) { 13 | ans = max(ans, area(points[i], points[j], points[k])); 14 | } 15 | } 16 | } 17 | return ans; 18 | 19 | } 20 | }; -------------------------------------------------------------------------------- /2461. Maximum Sum of Distinct Subarrays With Length K: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maximumSubarraySum(vector& nums, int k) { 4 | long long i=0,j=0; 5 | long long sum=0,maxsum=0; 6 | int n=nums.size(); 7 | mapmp; 8 | for(j=0;jmp; 6 | int uniquecount=0,count=0; 7 | for(int j=0;j0){ 6 | int rem=n%10; 7 | s+=rem; 8 | n/=10; 9 | } 10 | return s; 11 | } 12 | int maximumSum(vector& nums) { 13 | int maxsum=-1; 14 | unordered_mapmp; 15 | for(int i=0;i& nums,int s,int e){ 5 | for(int i=s+1;i& nums, int k) { 13 | int n=nums.size(); 14 | 15 | for(int start=0;start+2*k<=n;start++){ 16 | bool first=isIncreasing(nums,start,start+k); 17 | bool second=isIncreasing(nums,start+k,start+2*k); 18 | 19 | if(first && second){ 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; -------------------------------------------------------------------------------- /3005. Count Elements With Maximum Frequency: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxFrequencyElements(vector& nums) { 4 | unordered_mapfreq; 5 | 6 | for(int num:nums){ 7 | freq[num]++; 8 | } 9 | 10 | 11 | int maxifreq=0; 12 | 13 | for(auto it:freq){ 14 | int num=it.first; 15 | int fre=it.second; 16 | 17 | if(fre>maxifreq){ 18 | maxifreq=fre; 19 | } 20 | } 21 | 22 | int count=0; 23 | 24 | for(auto it:freq){ 25 | int num=it.first; 26 | int fre=it.second; 27 | 28 | if(fre==maxifreq)count++; 29 | } 30 | return count*maxifreq; 31 | } 32 | }; -------------------------------------------------------------------------------- /3066. Minimum Operations to Exceed Threshold Value II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int k) { 4 | priority_queue,greater>pq(nums.begin(),nums.end()); 5 | 6 | // for(int num:nums){ 7 | // pq.push(num); 8 | // } 9 | int opr=0; 10 | while(pq.size()>=2){ 11 | long long first=pq.top(); 12 | pq.pop(); 13 | if(first>=k){ 14 | break; 15 | } 16 | long long second=pq.top(); 17 | pq.pop(); 18 | 19 | long long num=first*2+second; 20 | pq.push(num); 21 | opr++; 22 | } 23 | return opr; 24 | } 25 | }; -------------------------------------------------------------------------------- /2843. Count Symmetric Integers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSymmetricIntegers(int low, int high) { 4 | int res=0; 5 | for(int num=low;num<=high;num++){ 6 | if((num>=10 && num<=99) && (num%11==0)){ 7 | res++; 8 | } 9 | if(num>=1000 && num<=9999){ 10 | int first=num/1000; 11 | int second=(num/100)%10; 12 | int sum1=first+second; 13 | int third=(num/10)%10; 14 | int four=num%10; 15 | int sum2=third+four; 16 | 17 | if(sum1==sum2){ 18 | res++; 19 | } 20 | 21 | } 22 | } 23 | return res; 24 | } 25 | }; -------------------------------------------------------------------------------- /1267. Count Servers that Communicate: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countServers(vector>& grid) { 4 | int n=grid.size(); 5 | int m=grid[0].size(); 6 | vectorrowc(n,0); 7 | vectorcolc(m,0); 8 | 9 | for(int i=0;i1 || colc[j]>1)){ 21 | ans++; 22 | } 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /2226. Maximum Candies Allocated to K Children: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(vector& candies, long long k,int num){ 4 | long long count=0; 5 | for(int i=0;i=k; 9 | } 10 | int maximumCandies(vector& candies, long long k) { 11 | 12 | int l=1,r=*max_element(candies.begin(),candies.end()); 13 | int ans=0; 14 | while(l<=r){ 15 | int mid=l+(r-l)/2; 16 | 17 | if(possible(candies,k,mid)){ 18 | ans=mid; 19 | l=mid+1; 20 | } 21 | else{ 22 | r=mid-1; 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /1079. Letter Tile Possibilities: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solve(string& tiles,string& res,vector& used,unordered_set& seq){ 4 | seq.insert(res); 5 | 6 | for(int i=0;iused(tiles.length(),false); 20 | 21 | unordered_setseq; 22 | string res=""; 23 | solve(tiles,res,used,seq); 24 | 25 | return seq.size()-1; 26 | 27 | } 28 | }; -------------------------------------------------------------------------------- /3105. Longest Strictly Increasing or Strictly Decreasing Subarray: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestMonotonicSubarray(vector& nums) { 4 | 5 | int n=nums.size(); 6 | 7 | if(n==1)return 1; 8 | int maxcount=0,count=1; 9 | 10 | 11 | for(int i=0;inums[i+1]){ 13 | count++; 14 | } 15 | else{ 16 | count=1; 17 | } 18 | maxcount=max(maxcount,count); 19 | } 20 | count=1; 21 | for(int i=0;i& nums,int k,int mid){ 4 | int count=0; 5 | for(int i=0;i=k; 12 | } 13 | int minCapability(vector& nums, int k) { 14 | int n=nums.size(); 15 | int l=1,r=*max_element(nums.begin(),nums.end()); 16 | int ans=-1; 17 | while(l<=r){ 18 | int mid=l+(r-l)/2; 19 | 20 | if(possible(nums,k,mid)){ 21 | ans=mid; 22 | r=mid-1; 23 | } 24 | else{ 25 | l=mid+1; 26 | } 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /3354. Make Array Elements Equal to Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countValidSelections(vector& nums) { 4 | int n = nums.size(); 5 | int ans = 0; 6 | int sum = accumulate(nums.begin(), nums.end(), 0); 7 | int leftSum = 0; 8 | int rightSum = sum; 9 | for (int i = 0; i < n; i++) { 10 | if (nums[i] == 0) { 11 | if (leftSum - rightSum >= 0 && leftSum - rightSum <= 1) { 12 | ans++; 13 | } 14 | if (rightSum - leftSum >= 0 && rightSum - leftSum <= 1) { 15 | ans++; 16 | } 17 | } else { 18 | leftSum += nums[i]; 19 | rightSum -= nums[i]; 20 | } 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /1593. Split a String Into the Max Number of Unique Substrings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUniqueSplit(string s) { 4 | unordered_set seen; 5 | return backtrack(s, 0, seen); 6 | } 7 | 8 | private: 9 | int backtrack(const string& s, int start, unordered_set& seen) { 10 | if (start == s.size()) return 0; 11 | 12 | int maxCount = 0; 13 | for (int end = start + 1; end <= s.size(); ++end) { 14 | string substring = s.substr(start, end - start); 15 | if (seen.find(substring) == seen.end()) { 16 | seen.insert(substring); 17 | maxCount = max(maxCount, 1 + backtrack(s, end, seen)); 18 | seen.erase(substring); 19 | } 20 | } 21 | return maxCount; 22 | } 23 | }; -------------------------------------------------------------------------------- /1760. Minimum Limit of Balls in a Bag: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumSize(vector& v, int m) { 4 | int i,j,n=v.size(); 5 | j=1; 6 | for(i=0;im){ 21 | break; 22 | } 23 | } 24 | 25 | if(x<=m){ 26 | j=mid; 27 | }else{ 28 | i=mid+1; 29 | } 30 | } 31 | return j; 32 | } 33 | }; -------------------------------------------------------------------------------- /3011. Find if Array Can Be Sorted: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canSortArray(vector& nums) { 4 | vector>mm; 5 | mm.push_back({nums[0],nums[0]}); 6 | for(int i = 1 ; i < nums.size() ;i++) 7 | { 8 | int cur = __builtin_popcount(nums[i]); 9 | int prev = __builtin_popcount(nums[i-1]); 10 | if(cur != prev) 11 | { 12 | mm.push_back({nums[i],nums[i]}); 13 | } 14 | mm.back().first = min(mm.back().first,nums[i]); 15 | mm.back().second = max(mm.back().second,nums[i]); 16 | } 17 | for(int i = 1 ; i < mm.size() ; i++) 18 | { 19 | if(mm[i-1].second > mm[i].first) 20 | return false; 21 | } 22 | return true; 23 | } 24 | }; -------------------------------------------------------------------------------- /3163. String Compression III: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string compressedString(string word) { 4 | string temp; 5 | char last=word[0]; 6 | int cnt=1; 7 | for(int i=1; i& ranks,int cars,ll mid){ 5 | ll count=0; 6 | 7 | for(int i=0;i=cars; 11 | } 12 | long long repairCars(vector& ranks, int cars) { 13 | 14 | ll l=1; 15 | int maxi=*max_element(ranks.begin(),ranks.end()); 16 | ll r=1LL*maxi*cars*cars; 17 | ll ans=-1; 18 | while(l<=r){ 19 | ll mid=l+(r-l)/2; 20 | 21 | if(possible(ranks,cars,mid)){ 22 | ans=mid; 23 | r=mid-1; 24 | } 25 | else{ 26 | l=mid+1; 27 | } 28 | } 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /1930. Unique Length-3 Palindromic Subsequences: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPalindromicSubsequence(string s) { 4 | 5 | vector>v(26,{-1,-1}); 6 | for(int i=0;ist; 22 | for(int middle=fistind+1;middle 3 | public: 4 | int maximumBeauty(vector& nums, int k) { 5 | sort(nums.begin(),nums.end()); 6 | 7 | 8 | int max_count=0; 9 | int win_count=0; 10 | int left=0,right=0; 11 | int n=nums.size(); 12 | while(right2*k){ 23 | win_count--; 24 | left++; 25 | } 26 | } 27 | return max_count; 28 | } 29 | }; -------------------------------------------------------------------------------- /2273. Find Resultant Array After Removing Anagrams: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool compare(string word1,string word2){ 4 | vector freq(26, 0); 5 | 6 | for (char ch : word1) { 7 | ++freq[ch - 'a']; 8 | } 9 | for (char ch : word2) { 10 | --freq[ch - 'a']; 11 | } 12 | 13 | 14 | for (int x : freq) { 15 | if (x != 0) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | 21 | } 22 | vector removeAnagrams(vector& words) { 23 | vectorres; 24 | res.push_back(words[0]); 25 | 26 | for(int i=1;i queryResults(int limit, vector>& queries) { 4 | int n=queries.size(); 5 | vectorans(n); 6 | unordered_mapmp; 7 | unordered_mapfreq; 8 | int uniquecount=0; 9 | for(int i=0;iq; 5 | priority_queuepq; 6 | q.push(root); 7 | while(!q.empty()){ 8 | long size=q.size(); 9 | long sum=0; 10 | for(int i=0;ival; 14 | if(node->left!=NULL){ 15 | q.push(node->left); 16 | } 17 | if(node->right!=NULL){ 18 | q.push(node->right); 19 | } 20 | } 21 | pq.push(sum); 22 | } 23 | if(pq.size()& nums,int i,int rem,vector>& dp){ 5 | int n=nums.size(); 6 | if(i==n){ 7 | return (rem==0)?0:NEG; 8 | 9 | } 10 | 11 | if(dp[i][rem]!=INT_MIN)return dp[i][rem]; 12 | 13 | int ans=maxsum(nums,i+1,rem,dp); 14 | 15 | int newrem=(rem+nums[i]%3)%3; 16 | int take=maxsum(nums,i+1,newrem,dp); 17 | 18 | if(take>NEG)ans=max(ans,take+nums[i]); 19 | 20 | dp[i][rem]=ans; 21 | return ans; 22 | } 23 | int maxSumDivThree(vector& nums) { 24 | int n=nums.size(); 25 | 26 | vector> dp(n,vector(3,INT_MIN)); 27 | 28 | int res=maxsum(nums,0,0,dp); 29 | return max(0,res); 30 | } 31 | }; -------------------------------------------------------------------------------- /983. Minimum Cost For Tickets: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_sets; 4 | int solve(vector&dp,vector& days, vector& costs,int curr){ 5 | if(curr>days[days.size()-1])return 0; 6 | 7 | if(s.find(curr)==s.end())return solve(dp,days,costs,curr+1); 8 | 9 | if(dp[curr]!=-1)return dp[curr]; 10 | 11 | int one=costs[0]+solve(dp,days,costs,curr+1); 12 | int seven=costs[1]+solve(dp,days,costs,curr+7); 13 | int thirty=costs[2]+solve(dp,days,costs,curr+30); 14 | 15 | return dp[curr]=min(one,min(seven,thirty)); 16 | } 17 | int mincostTickets(vector& days, vector& costs) { 18 | int n=days.size(); 19 | int last=days[n-1]; 20 | vectordp(last+1,-1); 21 | for(int d:days){ 22 | s.insert(d); 23 | } 24 | return solve(dp,days,costs,1); 25 | } 26 | }; -------------------------------------------------------------------------------- /2661. First Completely Painted Row or Column: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstCompleteIndex(vector& arr, vector>& mat) { 4 | int n=mat.size(),m=mat[0].size(); 5 | unordered_map>mp; 6 | 7 | vectorrowCount(n),colCount(m); 8 | 9 | for(int row=0;rowcurr=mp[num]; 21 | 22 | int row=curr.first; 23 | int col=curr.second; 24 | 25 | rowCount[row]++; 26 | colCount[col]++; 27 | 28 | 29 | if(rowCount[row]==m || colCount[col]==n)return i; 30 | } 31 | return -1; 32 | } 33 | }; -------------------------------------------------------------------------------- /3531-count-covered-buildings/3531-count-covered-buildings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countCoveredBuildings(int n, vector>& buildings) { 4 | unordered_mapminY,minX,maxY,maxX; 5 | 6 | const int INF=1e9; 7 | 8 | for(auto &b:buildings){ 9 | int x=b[0],y=b[1]; 10 | if(!minY.count(x))minY[x]=INF; 11 | if (!maxY.count(x)) maxY[x] =-INF; 12 | if (!minX.count(y)) minX[y] =INF; 13 | if (!maxX.count(y)) maxX[y] =-INF; 14 | minY[x] = min(minY[x], y); 15 | maxY[x] = max(maxY[x], y); 16 | minX[y] = min(minX[y], x); 17 | maxX[y] = max(maxX[y], x); 18 | 19 | } 20 | int ans=0; 21 | for (auto &b:buildings) { 22 | int x=b[0], y=b[1]; 23 | if(minY[x] < y && y < maxY[x] && minX[y] < x && x < maxX[y]) ans++; 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /0047-permutations-ii/README.md: -------------------------------------------------------------------------------- 1 |

47. Permutations II

Medium


Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,1,2]
 8 | Output:
 9 | [[1,1,2],
10 |  [1,2,1],
11 |  [2,1,1]]
12 | 
13 | 14 |

Example 2:

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

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= nums.length <= 8
  • 26 |
  • -10 <= nums[i] <= 10
  • 27 |
28 | -------------------------------------------------------------------------------- /951. Flip Equivalent Binary Trees: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 15 | if(root1==NULL && root2==NULL)return true; 16 | if(root1==NULL || root2==NULL)return false; 17 | if(root1->val!=root2->val)return false; 18 | 19 | bool noswap=flipEquiv(root1->left,root2->left) && flipEquiv(root1->right,root2->right); 20 | bool swap=flipEquiv(root1->left,root2->right) && flipEquiv(root1->right,root2->left); 21 | 22 | return swap||noswap; 23 | } 24 | }; -------------------------------------------------------------------------------- /2872. Maximum Number of K-Divisible Components: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int count = 0; 4 | vector> tree; 5 | vector v; 6 | 7 | long long int dfs(int u, int p, int k ){ 8 | 9 | long long int sum = v[u]; 10 | for(int v:tree[u]){ 11 | if(v!=p){ 12 | sum += dfs(v, u, k); 13 | } 14 | } 15 | 16 | if(sum%k==0){ 17 | count++; 18 | return 0; 19 | } 20 | return sum; 21 | } 22 | 23 | int maxKDivisibleComponents(int n, vector>& edges, vector& values, int k) { 24 | tree.resize(n); 25 | v = values; 26 | 27 | for(int i=0;iresult,vectortemp){ 4 | for(int i=0;i<26;i++){ 5 | if(temp[i] wordSubsets(vector& words1, vector& words2) { 10 | vectorresult; 11 | vectorfreq(26); 12 | 13 | for(string& s:words2){ 14 | int temp[26]={0}; 15 | for(char ch:s){ 16 | temp[ch-'a']++; 17 | freq[ch-'a']=max(freq[ch-'a'],temp[ch-'a']); 18 | } 19 | } 20 | 21 | for(string& s:words1){ 22 | vectortemp(26,0); 23 | for(char ch:s){ 24 | temp[ch-'a']++; 25 | } 26 | if(issubet(freq,temp)){ 27 | result.push_back(s); 28 | } 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /2381. Shifting Letters II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shiftingLetters(string s, vector>& shifts) { 4 | int n = s.size(); 5 | vector vec(n + 1, 0); 6 | 7 | for (auto& it : shifts) { 8 | int first = it[0]; 9 | int second = it[1]; 10 | int dir = it[2]; 11 | if (dir == 0) { 12 | vec[first] -= 1; 13 | if (second + 1 < n) vec[second + 1] += 1; 14 | } else { 15 | vec[first] += 1; 16 | if (second + 1 < n) vec[second + 1] -= 1; 17 | } 18 | } 19 | 20 | int current_shift = 0; 21 | string result(n, ' '); 22 | for (int i = 0; i < n; ++i) { 23 | current_shift += vec[i]; 24 | 25 | result[i] = 'a' + (s[i] - 'a' + (current_shift % 26) + 26) % 26; 26 | } 27 | 28 | return result; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /416. Partition Equal Subset Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool solve(int i,vector& nums,int target,vector>& dp){ 4 | if(target==0)return true; 5 | 6 | if(i==0){ 7 | return nums[0]==target; 8 | } 9 | 10 | if(dp[i][target]!=-1)return dp[i][target]; 11 | 12 | bool nottaken=solve(i-1,nums,target,dp); 13 | 14 | bool taken=false; 15 | if(nums[i]<=target){ 16 | taken=solve(i-1,nums,target-nums[i],dp); 17 | } 18 | return dp[i][target]=taken|| nottaken; 19 | } 20 | bool canPartition(vector& nums) { 21 | int n=nums.size(); 22 | int sum=accumulate(nums.begin(),nums.end(),0); 23 | 24 | if(sum%2==0){ 25 | int target=sum/2; 26 | vector>dp(n,vector(target+1,-1)); 27 | return solve(n-1,nums,target,dp); 28 | } 29 | else{ 30 | return false; 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /2601. Prime Subtraction Operation: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPrime(int x) { 4 | for (int i = 2; i <= sqrt(x); i++) { 5 | if (x % i == 0) { 6 | return 0; 7 | } 8 | } 9 | return 1; 10 | } 11 | bool primeSubOperation(vector& nums) { 12 | for (int i = 0; i < nums.size(); i++) { 13 | int bound; 14 | if (i == 0) { 15 | bound = nums[0]; 16 | } else { 17 | bound = nums[i] - nums[i - 1]; 18 | } 19 | if (bound <= 0) { 20 | return 0; 21 | } 22 | int largestPrime = 0; 23 | for (int j = bound - 1; j >= 2; j--) { 24 | if (checkPrime(j)) { 25 | largestPrime = j; 26 | break; 27 | } 28 | } 29 | nums[i] = nums[i] - largestPrime; 30 | } 31 | return 1; 32 | } 33 | }; -------------------------------------------------------------------------------- /1930. Unique Length-3 Palindromic Subsequences1: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPalindromicSubsequence(string s) { 4 | unordered_set letters; 5 | for (char c : s) { 6 | letters.insert(c); 7 | } 8 | 9 | int ans = 0; 10 | for (char letter : letters) { 11 | int i = -1; 12 | int j = 0; 13 | 14 | for (int k = 0; k < s.size(); k++) { 15 | if (s[k] == letter) { 16 | if (i == -1) { 17 | i = k; 18 | } 19 | 20 | j = k; 21 | } 22 | } 23 | 24 | unordered_set between; 25 | for (int k = i + 1; k < j; k++) { 26 | between.insert(s[k]); 27 | } 28 | 29 | ans += between.size(); 30 | } 31 | 32 | return ans; 33 | } 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /1277. Count Square Submatrices with All Ones: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int m,n; 4 | int solve(int i,int j,vector>& matrix,vector>&t){ 5 | if(i>=m || j>=n){ 6 | return 0; 7 | } 8 | if(matrix[i][j]==0){ 9 | return 0; 10 | } 11 | if(t[i][j]!=-1)return t[i][j]; 12 | int right=solve(i,j+1,matrix,t); 13 | int diagonal=solve(i+1,j+1,matrix,t); 14 | int below=solve(i+1,j,matrix,t); 15 | 16 | return t[i][j]=1+min({right,diagonal,below}); 17 | } 18 | int countSquares(vector>& matrix) { 19 | m=matrix.size(); 20 | n=matrix[0].size(); 21 | int result=0; 22 | vector>t(m+1,vector(n+1,-1)); 23 | for(int i=0;i a,vector b){ 4 | if(a[1]==b[1]){ 5 | return a[0]>b[0]; 6 | } 7 | return a[1]>& intervals) { 10 | int count=2; 11 | 12 | sort(intervals.begin(),intervals.end(),check); 13 | 14 | vectormaxi(2,0); 15 | maxi[0]=intervals[0][1]-1; 16 | maxi[1]=intervals[0][1]; 17 | int n=intervals.size(); 18 | 19 | for(int i=1;i& nums) { 4 | int n = nums.size(); 5 | 6 | vector lis(n,1); 7 | vector lds(n,1); 8 | for (int i = 0; i < n; i++) { 9 | for (int j = i-1; j >= 0; j--) { 10 | if (nums[i] > nums[j]) { 11 | lis[i] = max(lis[i], lis[j] + 1); 12 | } 13 | } 14 | } 15 | for (int i = n-1; i>= 0; i--) { 16 | for (int j =i+1; j nums[j]) { 18 | lds[i] = max(lds[i], lds[j] + 1); 19 | } 20 | } 21 | } 22 | 23 | int minRemovals=INT_MAX; 24 | for (int i=0; i1 && lds[i]>1) { 26 | minRemovals=min(minRemovals, n-lis[i]-lds[i] + 1); 27 | } 28 | } 29 | 30 | return minRemovals; 31 | } 32 | }; -------------------------------------------------------------------------------- /2559. Count Vowel Strings in Ranges: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector vowelStrings(vector& words, vector>& queries) { 4 | int n=words.size(); 5 | vectorprefix(n,0); 6 | for(int i=0;iresult; 18 | 19 | for(auto& q:queries){ 20 | int L=q[0]; 21 | int R=q[1]; 22 | 23 | int sum=prefix[R]; 24 | if(L>0){ 25 | sum-=prefix[L-1]; 26 | } 27 | result.push_back(sum); 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /0047-permutations-ii/0047-permutations-ii.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 2 | class Solution { 3 | public: 4 | vector> permuteUnique(vector& nums) { 5 | vector> results; 6 | unordered_map counter; 7 | for (int num : nums) counter[num]++; 8 | vector comb; 9 | backtrack(counter, comb, nums.size(), results); 10 | return results; 11 | } 12 | void backtrack(unordered_map& counter, vector& comb, int N, 13 | vector>& results) { 14 | if (comb.size() == N) { 15 | results.push_back(comb); 16 | return; 17 | } 18 | for (auto& item : counter) { 19 | int num = item.first; 20 | int count = item.second; 21 | if (count == 0) continue; 22 | comb.push_back(num); 23 | counter[num]--; 24 | backtrack(counter, comb, N, results); 25 | comb.pop_back(); 26 | counter[num]++; 27 | } 28 | } 29 | }; -------------------------------------------------------------------------------- /3318. Find X-Sum of All K-Long Subarrays I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findXSum(vector& nums, int k, int x) { 4 | unordered_mapmp; 5 | int i=0; 6 | int n=nums.size(); 7 | vectorans; 8 | for(int j=0;j>pq; 13 | for(auto it:mp){ 14 | pq.push({it.second,it.first}); 15 | } 16 | int sum=0,count = x;; 17 | while(!pq.empty() && count--){ 18 | auto top=pq.top(); 19 | pq.pop(); 20 | sum+=top.second*top.first; 21 | } 22 | ans.push_back(sum); 23 | mp[nums[i]]--; 24 | if (mp[nums[i]] == 0) { 25 | mp.erase(nums[i]); 26 | } 27 | i++; 28 | 29 | } 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /873. Length of Longest Fibonacci Subsequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(int j,int k,vector& arr,unordered_map& mp,vector>& dp){ 4 | if(dp[j][k]!=-1)return dp[j][k]; 5 | 6 | int target=arr[k]-arr[j]; 7 | if(mp.count(target) && mp[target]& arr) { 14 | int n=arr.size(); 15 | 16 | unordered_mapmp; 17 | 18 | for(int i=0;i>dp(n,vector(n,-1)); 23 | 24 | for(int j=1;j=3){ 28 | maxlen=max(maxlen,len); 29 | } 30 | } 31 | } 32 | return maxlen; 33 | } 34 | }; -------------------------------------------------------------------------------- /2349. Design a Number Container System: -------------------------------------------------------------------------------- 1 | class NumberContainers { 2 | public: 3 | unordered_map,greater>>pq; 4 | unordered_mapmp; 5 | 6 | NumberContainers() { 7 | 8 | } 9 | 10 | void change(int index, int number) { 11 | mp[index]=number; 12 | pq[number].push(index); 13 | } 14 | 15 | int find(int number) { 16 | if(pq.find(number)==pq.end()){ 17 | return -1; 18 | } 19 | 20 | auto& minheap=pq[number]; 21 | 22 | while(!minheap.empty()){ 23 | int node=minheap.top(); 24 | 25 | if(mp[node]==number){ 26 | return node; 27 | } 28 | 29 | minheap.pop(); 30 | } 31 | 32 | return -1; 33 | } 34 | 35 | }; 36 | 37 | /** 38 | * Your NumberContainers object will be instantiated and called as such: 39 | * NumberContainers* obj = new NumberContainers(); 40 | * obj->change(index,number); 41 | * int param_2 = obj->find(number); 42 | */ -------------------------------------------------------------------------------- /1861. Rotating the Box: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> rotateTheBox(vector>& box) { 4 | int row=box.size(); 5 | int col=box[0].size(); 6 | vector>result(col,vector(row)); 7 | for(int i=0;i&rows:result){ 13 | reverse(rows.begin(),rows.end()); 14 | } 15 | 16 | for(int j=0;j=0;i--){ 19 | 20 | if(result[i][j]=='*'){ 21 | spacebottom=i-1; 22 | 23 | } 24 | if(result[i][j]=='#'){ 25 | result[i][j]='.'; 26 | result[spacebottom][j]='#'; 27 | spacebottom--; 28 | } 29 | } 30 | } 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /2536. Increment Submatrices by One: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> rangeAddQueries(int n, vector>& queries) { 4 | vector> diff(n+1, vector(n+1, 0)); 5 | 6 | for (auto &q : queries) { 7 | int r1 =q[0], c1 = q[1], r2 = q[2], c2 = q[3]; 8 | 9 | diff[r1][c1] += 1; 10 | if (c2 + 1 < n) diff[r1][c2 + 1] -= 1; 11 | if (r2 + 1 < n) diff[r2 + 1][c1] -= 1; 12 | if (r2 + 1 < n && c2 + 1 < n) diff[r2 + 1][c2 + 1] += 1; 13 | } 14 | 15 | 16 | vector> mat(n, vector(n, 0)); 17 | 18 | for (int i = 0; i < n; i++) { 19 | for (int j = 0; j < n; j++) { 20 | int up = (i > 0) ? mat[i - 1][j] : 0; 21 | int left = (j > 0) ? mat[i][j - 1] : 0; 22 | int diag = (i > 0 && j > 0) ? mat[i - 1][j - 1] : 0; 23 | 24 | mat[i][j] = diff[i][j] + up + left - diag; 25 | } 26 | } 27 | 28 | return mat; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /1415. The k-th Lexicographical String of All Happy Strings of Length n: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getHappyString(int n, int k) { 4 | string currentString = ""; 5 | vector happyStrings; 6 | 7 | generateHappyStrings(n, currentString, happyStrings); 8 | 9 | if (happyStrings.size() < k) return ""; 10 | 11 | sort(happyStrings.begin(), happyStrings.end()); 12 | 13 | return happyStrings[k - 1]; 14 | } 15 | 16 | private: 17 | void generateHappyStrings(int n, string currentString,vector &happyStrings) { 18 | 19 | if (currentString.size() == n) { 20 | happyStrings.push_back(currentString); 21 | return; 22 | } 23 | 24 | for (char currentChar = 'a'; currentChar <= 'c'; currentChar++) { 25 | 26 | if (currentString.size() > 0 && currentString.back() == currentChar) 27 | continue; 28 | 29 | 30 | generateHappyStrings(n, currentString + currentChar, happyStrings); 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /1523-count-odd-numbers-in-an-interval-range/README.md: -------------------------------------------------------------------------------- 1 |

1630. Count Odd Numbers in an Interval Range

Easy


Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: low = 3, high = 7
 8 | Output: 3
 9 | Explanation: The odd numbers between 3 and 7 are [3,5,7].
10 | 11 |

Example 2:

12 | 13 |
14 | Input: low = 8, high = 10
15 | Output: 1
16 | Explanation: The odd numbers between 8 and 10 are [9].
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 0 <= low <= high <= 10^9
  • 23 |
-------------------------------------------------------------------------------- /2593. Find Score of an Array After Marking All Elements: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long findScore(vector& nums) { 4 | long long res=0; 5 | vectormarked(nums.size(),false); 6 | 7 | auto cmp=[](pair& pair1,pair& pair2){ 8 | if(pair1.first!=pair2.first)return pair1.first>pair2.first; 9 | return pair1.second>pair2.second; 10 | }; 11 | priority_queue,vector>, decltype(cmp)> pq(cmp); 12 | 13 | for(int i=0;itop=pq.top(); 18 | pq.pop(); 19 | int num=top.first; 20 | int ind=top.second; 21 | if(!marked[ind]){ 22 | res+=num; 23 | marked[ind]=true; 24 | if(ind-1>=0){ 25 | marked[ind-1]=true; 26 | } 27 | if(ind+1& nums, vector>& dp, int offset) { 4 | if (i == nums.size()) { 5 | return target == 0 ? 1 : 0; 6 | } 7 | 8 | if (target + offset < 0 || target + offset >= dp[0].size()) { 9 | return 0; 10 | } 11 | 12 | if (dp[i][target + offset] != -1) { 13 | return dp[i][target + offset]; 14 | } 15 | 16 | int add = count(i + 1, target - nums[i], nums, dp, offset); 17 | int subtract = count(i + 1, target + nums[i], nums, dp, offset); 18 | 19 | return dp[i][target + offset] = add + subtract; 20 | } 21 | 22 | int findTargetSumWays(vector& nums, int target) { 23 | int n = nums.size(); 24 | int sum = accumulate(nums.begin(), nums.end(), 0); 25 | if (abs(target) > sum) { 26 | return 0; 27 | } 28 | int offset = sum; 29 | vector> dp(n, vector(2 * sum + 1, -1)); 30 | return count(0, target, nums, dp, offset); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /166. Fraction to Recurring Decimal: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string fractionToDecimal(int numerator, int denominator) { 4 | if(numerator==0) return "0"; 5 | 6 | string ans = ""; 7 | 8 | 9 | if((numerator < 0) ^ (denominator < 0)) { 10 | ans += "-"; 11 | } 12 | 13 | 14 | long long n = llabs((long long)numerator); 15 | long long d = llabs((long long)denominator); 16 | 17 | 18 | long long q=n/d; 19 | long long r=n%d; 20 | ans+= to_string(q); 21 | 22 | if (r== 0) return ans; 23 | 24 | ans += "."; 25 | unordered_map mp; 26 | 27 | while (r != 0) { 28 | if (mp.find(r) != mp.end()) { 29 | int pos = mp[r]; 30 | ans.insert(pos, "("); 31 | ans += ")"; 32 | break; 33 | } 34 | 35 | mp[r]=ans.length(); 36 | r*= 10; 37 | q= r / d; 38 | r%= d; 39 | ans+= to_string(q); 40 | } 41 | 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /515. Find Largest Value in Each Tree Row: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector largestValues(TreeNode* root) { 15 | if(root==NULL)return {}; 16 | queueq; 17 | q.push(root); 18 | vectorresult; 19 | while(!q.empty()){ 20 | int maxi=INT_MIN; 21 | int n=q.size(); 22 | for(int i=0;ival); 26 | if(node->left!=NULL)q.push(node->left); 27 | if(node->right!=NULL)q.push(node->right); 28 | } 29 | 30 | result.push_back(maxi); 31 | } 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /2290. Minimum Obstacle Removal to Reach Corner: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | #define P pair> 4 | vector>directions={{0,1},{0,-1},{1,0},{-1,0}}; 5 | int minimumObstacles(vector>& grid) { 6 | int m=grid.size(); 7 | int n=grid[0].size(); 8 | vector>result(m,vector(n,INT_MAX)); 9 | 10 | result[0][0]=0; 11 | priority_queue,greater

>pq; 12 | 13 | pq.push({0,{0,0}}); 14 | 15 | while(!pq.empty()) 16 | { 17 | auto curr=pq.top(); 18 | pq.pop(); 19 | 20 | int d=curr.first; 21 | int i=curr.second.first; 22 | int j=curr.second.second; 23 | 24 | for(auto &dir:directions){ 25 | int x=i+dir[0]; 26 | int y=j+dir[1]; 27 | if(x<0 || x>=m || y<0 || y>=n)continue; 28 | int wt=(grid[x][y]==1)?1:0; 29 | 30 | if(d+wt= b and a >= c and curra != 2) or(a > 0 and (currb == 2 or currc == 2))) { 10 | 11 | ans += 'a'; 12 | a--; 13 | curra++; 14 | currb = 0; 15 | currc = 0; 16 | } else if ((b >= a and b >= c and currb != 2) or(b > 0 and (currc == 2 or curra == 2))) { 17 | 18 | ans += 'b'; 19 | b--; 20 | currb++; 21 | curra = 0; 22 | currc = 0; 23 | } else if ((c >= a and c >= b and currc != 2) or(c > 0 and (curra == 2 or currb == 2))) { 24 | ans += 'c'; 25 | c--; 26 | currc++; 27 | curra = 0; 28 | currb = 0; 29 | } 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /1925-count-square-sum-triples/README.md: -------------------------------------------------------------------------------- 1 |

2037. Count Square Sum Triples

Easy


A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.

2 | 3 |

Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: n = 5
10 | Output: 2
11 | Explanation: The square triples are (3,4,5) and (4,3,5).
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: n = 10
18 | Output: 4
19 | Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= n <= 250
  • 27 |
28 | -------------------------------------------------------------------------------- /2211-count-collisions-on-a-road/2211-count-collisions-on-a-road.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countCollisions(string directions) { 4 | stackst; 5 | int count=0; 6 | 7 | 8 | for(char c:directions){ 9 | if(c=='L'){ 10 | if(!st.empty() && st.top()=='R'){ 11 | st.pop(); 12 | count+=2; 13 | c='S'; 14 | 15 | 16 | while(!st.empty() && st.top()=='R'){ 17 | st.pop(); 18 | count+=1; 19 | } 20 | } 21 | else if(!st.empty() && st.top()=='S'){ 22 | count+=1; 23 | c='S'; 24 | } 25 | else{ 26 | continue; 27 | } 28 | } 29 | else if(c=='S'){ 30 | while(!st.empty() && st.top()=='R'){ 31 | st.pop(); 32 | count+=1; 33 | } 34 | } 35 | if(c=='R' || c=='S'){ 36 | st.push(c); 37 | } 38 | } 39 | return count; 40 | } 41 | }; -------------------------------------------------------------------------------- /2429. Minimize XOR: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimizeXor(int num1, int num2) { 4 | 5 | int result = num1; 6 | 7 | int targetSetBitsCount = __builtin_popcount(num2); 8 | int setBitsCount = __builtin_popcount(result); 9 | 10 | 11 | int currentBit = 0; 12 | 13 | 14 | while (setBitsCount < targetSetBitsCount) { 15 | 16 | if (!isSet(result, currentBit)) { 17 | setBit(result, currentBit); 18 | setBitsCount++; 19 | } 20 | 21 | currentBit++; 22 | } 23 | 24 | 25 | while (setBitsCount > targetSetBitsCount) { 26 | 27 | if (isSet(result, currentBit)) { 28 | unsetBit(result, currentBit); 29 | setBitsCount--; 30 | } 31 | 32 | currentBit++; 33 | } 34 | 35 | return result; 36 | } 37 | 38 | private: 39 | 40 | bool isSet(int x, int bit) { return x & (1 << bit); } 41 | 42 | 43 | void setBit(int &x, int bit) { x |= (1 << bit); } 44 | 45 | 46 | void unsetBit(int &x, int bit) { x &= ~(1 << bit); } 47 | }; -------------------------------------------------------------------------------- /3356. Zero Array Transformation II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(vector nums, vector>& queries, int k) { 4 | int n=nums.size(); 5 | vectordiff(n,0); 6 | 7 | for(int i=0;i0){ 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | int minZeroArray(vector& nums, vector>& queries) { 30 | int l=0, r=queries.size(), ans = -1; 31 | 32 | while(l<=r) { 33 | int mid=l+(r-l)/2; 34 | 35 | if (possible(nums,queries,mid)) { 36 | ans=mid; 37 | r=mid-1; 38 | } 39 | else { 40 | l=mid+1; 41 | } 42 | } 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /802. Find Eventual Safe States: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector eventualSafeNodes(vector>& graph) { 4 | int n=graph.size(); 5 | vectorindegree(n); 6 | vector>adj(n); 7 | 8 | for(int i=0;iq; 16 | 17 | for(int i=0;isafe(n,false); 24 | 25 | while(!q.empty()){ 26 | int node=q.front(); 27 | q.pop(); 28 | safe[node]=true; 29 | 30 | for(auto nbr:adj[node]){ 31 | indegree[nbr]--; 32 | if(indegree[nbr]==0){ 33 | q.push(nbr); 34 | } 35 | } 36 | 37 | } 38 | vectorans; 39 | 40 | for(int i=0;ibalance; 4 | public: 5 | Bank(vector& balance):balance(balance) {} 6 | 7 | bool transfer(int account1, int account2, long long money) { 8 | if(account1>balance.size() || account2>balance.size() || balance[account1-1]balance.size())return false; 19 | 20 | balance[account-1]+=money; 21 | return true; 22 | } 23 | 24 | bool withdraw(int account, long long money) { 25 | if(account>balance.size() || money>balance[account-1])return false; 26 | 27 | balance[account-1]-=money; 28 | return true; 29 | } 30 | }; 31 | 32 | /** 33 | * Your Bank object will be instantiated and called as such: 34 | * Bank* obj = new Bank(balance); 35 | * bool param_1 = obj->transfer(account1,account2,money); 36 | * bool param_2 = obj->deposit(account,money); 37 | * bool param_3 = obj->withdraw(account,money); 38 | */ -------------------------------------------------------------------------------- /2658. Maximum Number of Fish in a Grid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dfs(int x,int y,int row,int col, vector>& visited,vector>& grid){ 4 | visited[x][y]=1; 5 | 6 | int dx[4]={0,0,1,-1}; 7 | int dy[4]={1,-1,0,0}; 8 | int fish=grid[x][y]; 9 | for(int i=0;i<4;i++){ 10 | int newx=x+dx[i]; 11 | int newy=y+dy[i]; 12 | 13 | if(newx>=0 && newx=0 && newy0){ 14 | 15 | fish+= dfs(newx,newy,row,col,visited,grid); 16 | } 17 | } 18 | return fish; 19 | } 20 | int findMaxFish(vector>& grid) { 21 | int row=grid.size(); 22 | int col=grid[0].size(); 23 | 24 | vector>visited(row,vector(col,0)); 25 | int maxFish=0; 26 | 27 | for(int i=0;i0){ 30 | int count= dfs(i,j,row,col,visited,grid); 31 | maxFish=max(maxFish,count); 32 | } 33 | } 34 | } 35 | return maxFish; 36 | } 37 | }; -------------------------------------------------------------------------------- /632. Smallest Range Covering Elements from K Lists: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector smallestRange(vector>& nums) { 4 | int n=nums.size(); 5 | priority_queue,vector>,greater>>pq; 6 | 7 | int maxele=INT_MIN; 8 | for(int i=0;iresultrange={-1000000,1000000}; 13 | 14 | while(!pq.empty()){ 15 | vectorcurr=pq.top(); 16 | pq.pop(); 17 | 18 | 19 | int minele=curr[0]; 20 | int listidx=curr[1]; 21 | int idx=curr[2]; 22 | 23 | if(maxele-minele balance{ 4 | 1, 22, 122, 212, 221, 333, 1333, 3133, 3313, 5 | 3331, 4444, 14444, 22333, 23233, 23323, 23332, 32233, 32323, 6 | 32332, 33223, 33232, 33322, 41444, 44144, 44414, 44441, 55555, 7 | 122333, 123233, 123323, 123332, 132233, 132323, 132332, 133223, 133232, 8 | 133322, 155555, 212333, 213233, 213323, 213332, 221333, 223133, 223313, 9 | 223331, 224444, 231233, 231323, 231332, 232133, 232313, 232331, 233123, 10 | 233132, 233213, 233231, 233312, 233321, 242444, 244244, 244424, 244442, 11 | 312233, 312323, 312332, 313223, 313232, 313322, 321233, 321323, 321332, 12 | 322133, 322313, 322331, 323123, 323132, 323213, 323231, 323312, 323321, 13 | 331223, 331232, 331322, 332123, 332132, 332213, 332231, 332312, 332321, 14 | 333122, 333212, 333221, 422444, 424244, 424424, 424442, 442244, 442424, 15 | 442442, 444224, 444242, 444422, 515555, 551555, 555155, 555515, 555551, 16 | 666666, 1224444}; 17 | 18 | int nextBeautifulNumber(int n) { 19 | return *upper_bound(balance.begin(), balance.end(), n); 20 | } 21 | }; -------------------------------------------------------------------------------- /2182. Construct String With Repeat Limit: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string repeatLimitedString(string s, int repeatLimit) { 4 | vector freq(26, 0); 5 | for (char ch : s) { 6 | freq[ch - 'a']++; 7 | } 8 | 9 | string result; 10 | int currentCharIndex = 25; 11 | while (currentCharIndex >= 0) { 12 | if (freq[currentCharIndex] == 0) { 13 | currentCharIndex--; 14 | continue; 15 | } 16 | 17 | int use = min(freq[currentCharIndex], repeatLimit); 18 | result.append(use, 'a' + currentCharIndex); 19 | freq[currentCharIndex] -= use; 20 | 21 | if (freq[currentCharIndex] > 22 | 0) { 23 | int smallerCharIndex = currentCharIndex - 1; 24 | while (smallerCharIndex >= 0 && freq[smallerCharIndex] == 0) { 25 | smallerCharIndex--; 26 | } 27 | if (smallerCharIndex < 0) { 28 | break; 29 | } 30 | result.push_back('a' + smallerCharIndex); 31 | freq[smallerCharIndex]--; 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /2528. Maximize the Minimum Powered City: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maxPower(vector& stations, int r, int k) { 4 | long left = ranges::min(stations); 5 | long right = accumulate(stations.begin(), stations.end(), 0L) + k + 1; 6 | while (left < right) { 7 | const long mid = (left + right) / 2; 8 | if (check(stations, r, k, mid)) 9 | left = mid + 1; 10 | else 11 | right = mid; 12 | } 13 | return left - 1; 14 | } 15 | 16 | private: 17 | bool check(vector stations, int r, int additionalStations, 18 | long minPower) { 19 | const int n = stations.size(); 20 | long power = accumulate(stations.begin(), stations.begin() + r, 0L); 21 | 22 | for (int i = 0; i < n; ++i) { 23 | if (i + r < n) 24 | power += stations[i + r]; 25 | if (power < minPower) { 26 | const long requiredPower = minPower - power; 27 | if (requiredPower > additionalStations) 28 | return false; 29 | stations[min(n - 1, i + r)] += requiredPower; 30 | additionalStations -= requiredPower; 31 | power += requiredPower; 32 | } 33 | if (i - r >= 0) 34 | power -= stations[i - r]; 35 | } 36 | return true; 37 | } 38 | }; -------------------------------------------------------------------------------- /2657. Find the Prefix Common Array of Two Arrays Solved Medium Topics Companies Hint: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findThePrefixCommonArray(vector& A, vector& B) { 4 | int n = A.size(); 5 | vector prefixCommonArray(n); 6 | 7 | // Loop through each index to calculate common elements for each prefix 8 | for (int currentIndex = 0; currentIndex < n; ++currentIndex) { 9 | int commonCount = 0; 10 | 11 | // Compare elements in A and B within the range of current prefix 12 | for (int aIndex = 0; aIndex <= currentIndex; ++aIndex) { 13 | for (int bIndex = 0; bIndex <= currentIndex; ++bIndex) { 14 | // Check if elements match, and count if they do 15 | if (A[aIndex] == B[bIndex]) { 16 | ++commonCount; 17 | break; 18 | } 19 | } 20 | } 21 | 22 | // Store the count of common elements for the current prefix 23 | prefixCommonArray[currentIndex] = commonCount; 24 | } 25 | 26 | // Return the final array with counts of common elements in each prefix 27 | return prefixCommonArray; 28 | } 29 | }; -------------------------------------------------------------------------------- /3208. Alternating Groups II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfAlternatingGroups(vector& colors, int k) { 4 | // Extend the array to handle circular sequences 5 | for (int i = 0; i < k - 1; i++) { 6 | colors.push_back(colors[i]); 7 | } 8 | 9 | int length = colors.size(); 10 | int result = 0; 11 | // Initialize the bounds of the sliding window 12 | int left = 0; 13 | int right = 1; 14 | 15 | while (right < length) { 16 | // Check if the current color is the same as the last one 17 | if (colors[right] == colors[right - 1]) { 18 | // Pattern breaks, reset window from the current position 19 | left = right; 20 | right++; 21 | continue; 22 | } 23 | 24 | // Expand the window to the right 25 | right++; 26 | 27 | // Skip counting sequence if its length is less than k 28 | if (right - left < k) continue; 29 | 30 | // Record a valid sequence and shrink window from the left to search 31 | // for more 32 | result++; 33 | left++; 34 | } 35 | 36 | return result; 37 | } 38 | }; -------------------------------------------------------------------------------- /862. Shortest Subarray with Sum at Least K: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int shortestSubarray(vector& nums, int targetSum) { 4 | int n = nums.size(); 5 | 6 | 7 | vector prefixSums(n + 1, 0); 8 | 9 | for (int i = 1; i <= n; i++) { 10 | prefixSums[i] = prefixSums[i - 1] + nums[i - 1]; 11 | } 12 | 13 | deque candidateIndices; 14 | 15 | int shortestSubarrayLength = INT_MAX; 16 | 17 | for (int i = 0; i <= n; i++) { 18 | 19 | while (!candidateIndices.empty() && 20 | prefixSums[i] - prefixSums[candidateIndices.front()] >= 21 | targetSum) { 22 | 23 | shortestSubarrayLength = 24 | min(shortestSubarrayLength, i - candidateIndices.front()); 25 | candidateIndices.pop_front(); 26 | } 27 | 28 | 29 | while (!candidateIndices.empty() && 30 | prefixSums[i] <= prefixSums[candidateIndices.back()]) { 31 | candidateIndices.pop_back(); 32 | } 33 | 34 | 35 | candidateIndices.push_back(i); 36 | } 37 | 38 | return shortestSubarrayLength == INT_MAX ? -1 : shortestSubarrayLength; 39 | } 40 | }; -------------------------------------------------------------------------------- /1765. Map of Highest Peak: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> highestPeak(vector>& isWater) { 4 | int n=isWater.size(); 5 | int m=isWater[0].size(); 6 | vector>ans(n,vector(m,0)); 7 | vector>visited(n,vector(m,0)); 8 | 9 | queue,int>>q; 10 | 11 | for(int i=0;i,int>p=q.front(); 27 | int x=p.first.first; 28 | int y=p.first.second; 29 | int height=p.second; 30 | q.pop(); 31 | ans[x][y]=height; 32 | 33 | for(int i=0;i<4;i++){ 34 | int newx=x+dx[i]; 35 | int newy=y+dy[i]; 36 | if(newx>=0 && newx=0 && newy>& classes, int extraStudents) { 4 | 5 | auto calculateGain = [](int passes, int totalStudents) { 6 | return (double)(passes + 1) / (totalStudents + 1) - 7 | (double)passes / totalStudents; 8 | }; 9 | 10 | priority_queue>> maxHeap; 11 | for (const auto& singleClass : classes) { 12 | maxHeap.push({calculateGain(singleClass[0], singleClass[1]), 13 | {singleClass[0], singleClass[1]}}); 14 | } 15 | 16 | while (extraStudents--) { 17 | auto [currentGain, classInfo] = maxHeap.top(); 18 | maxHeap.pop(); 19 | int passes = classInfo.first; 20 | int totalStudents = classInfo.second; 21 | maxHeap.push({calculateGain(passes + 1, totalStudents + 1),{passes + 1, totalStudents + 1}}); 22 | } 23 | 24 | double totalPassRatio = 0; 25 | while (!maxHeap.empty()) { 26 | auto [_, classInfo] = maxHeap.top(); 27 | maxHeap.pop(); 28 | totalPassRatio += (double)classInfo.first / classInfo.second; 29 | } 30 | 31 | return totalPassRatio / classes.size(); 32 | } 33 | }; -------------------------------------------------------------------------------- /1462. Course Schedule IV: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { 4 | vector>adj(n); 5 | vectorinDegree(n,0); 6 | 7 | for(auto edge:prerequisites){ 8 | int u=edge[0]; 9 | int v=edge[1]; 10 | 11 | adj[u].push_back(v); 12 | inDegree[v]++; 13 | } 14 | 15 | queueq; 16 | 17 | for(int i=0;i>pre; 22 | 23 | while(!q.empty()){ 24 | int node=q.front(); 25 | q.pop(); 26 | 27 | for(auto ad:adj[node]){ 28 | pre[ad].insert(node); 29 | for(auto p:pre[node]){ 30 | pre[ad].insert(p); 31 | } 32 | 33 | inDegree[ad]--; 34 | if(inDegree[ad]==0){ 35 | q.push(ad); 36 | } 37 | } 38 | } 39 | 40 | vectorans; 41 | 42 | for(auto q:queries){ 43 | int u=q[0]; 44 | int v=q[1]; 45 | 46 | ans.push_back(pre[v].contains(u)); 47 | } 48 | return ans; 49 | } 50 | }; -------------------------------------------------------------------------------- /2684. Maximum Number of Moves in a Grid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int dirs[3] = {-1, 0, 1}; 4 | 5 | int maxMoves(vector>& grid) { 6 | int M = grid.size(), N = grid[0].size(); 7 | 8 | queue> q; 9 | vector> vis(M, vector(N, 0)); 10 | for (int i = 0; i < M; i++) { 11 | vis[i][0] = 1; 12 | q.push({i, 0, 0}); 13 | } 14 | 15 | int maxMoves = 0; 16 | while (!q.empty()) { 17 | int sz = q.size(); 18 | 19 | while (sz--) { 20 | vector v = q.front(); 21 | q.pop(); 22 | int row = v[0], col = v[1], count = v[2]; 23 | 24 | maxMoves = max(maxMoves, count); 25 | 26 | for (int dir : dirs) { 27 | int newRow = row + dir, newCol = col + 1; 28 | if (newRow >= 0 && newCol >= 0 && newRow < M && 29 | newCol < N && !vis[newRow][newCol] && 30 | grid[row][col] < grid[newRow][newCol]) { 31 | vis[newRow][newCol] = 1; 32 | q.push({newRow, newCol, count + 1}); 33 | } 34 | } 35 | } 36 | } 37 | 38 | return maxMoves; 39 | } 40 | }; -------------------------------------------------------------------------------- /1262-greatest-sum-divisible-by-three/README.md: -------------------------------------------------------------------------------- 1 |

1388. Greatest Sum Divisible by Three

Medium


Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [3,6,5,1,8]
 8 | Output: 18
 9 | Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
10 | 11 |

Example 2:

12 | 13 |
14 | Input: nums = [4]
15 | Output: 0
16 | Explanation: Since 4 is not divisible by 3, do not pick any number.
17 | 
18 | 19 |

Example 3:

20 | 21 |
22 | Input: nums = [1,2,3,4,4]
23 | Output: 12
24 | Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • 1 <= nums.length <= 4 * 104
  • 32 |
  • 1 <= nums[i] <= 104
  • 33 |
34 | -------------------------------------------------------------------------------- /3578-count-partitions-with-max-min-difference-at-most-k/3578-count-partitions-with-max-min-difference-at-most-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long mod=1e9+7; 4 | int countPartitions(vector& nums, int k) { 5 | int n=nums.size(); 6 | vectordp(n+1); 7 | vectorprefix(n+1); 8 | 9 | dequeminq,maxq; 10 | 11 | dp[0]=1,prefix[0]=1; 12 | 13 | int left=0; 14 | 15 | for(int right=0;right=nums[right]){ 21 | minq.pop_back(); 22 | } 23 | minq.push_back(right); 24 | 25 | while(!maxq.empty() && !minq.empty() && nums[maxq.front()]-nums[minq.front()]>k){ 26 | if(maxq.front()==left)maxq.pop_front(); 27 | if(minq.front()==left)minq.pop_front(); 28 | 29 | left++; 30 | } 31 | 32 | long ways=prefix[right]; 33 | 34 | if(left>0) ways=(ways-prefix[left-1]+mod)%mod; 35 | 36 | dp[right+1]=ways; 37 | prefix[right+1]=(prefix[right]+dp[right+1])%mod; 38 | } 39 | 40 | return (int)dp[n]; 41 | } 42 | }; -------------------------------------------------------------------------------- /1106. Parsing A Boolean Expression: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool parseBoolExpr(string expression) { 4 | stack st; 5 | 6 | // Traverse the entire expression 7 | for (char currChar : expression) { 8 | if (currChar == ')') { 9 | vector values; 10 | while (st.top() != '(') { 11 | values.push_back(st.top()); 12 | st.pop(); 13 | } 14 | st.pop(); 15 | char op = st.top(); 16 | st.pop(); 17 | char result = evaluateSubExpr(op, values); 18 | st.push(result); 19 | } else if (currChar != ',') { 20 | st.push(currChar); 21 | } 22 | } 23 | return st.top() == 't'; 24 | } 25 | 26 | private: 27 | char evaluateSubExpr(char op, vector& values) { 28 | if (op == '!') return values[0] == 't' ? 'f' : 't'; 29 | if (op == '&') { 30 | for (char value : values) { 31 | if (value == 'f') return 'f'; 32 | } 33 | return 't'; 34 | } 35 | 36 | if (op == '|') { 37 | for (char value : values) { 38 | if (value == 't') return 't'; 39 | } 40 | return 'f'; 41 | } 42 | return 'f'; 43 | } 44 | }; -------------------------------------------------------------------------------- /2463. Minimum Total Distance Traveled: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long minimumTotalDistance(vector& robot,vector>& factory) { 4 | 5 | sort(robot.begin(), robot.end()); 6 | sort(factory.begin(), factory.end()); 7 | vector factoryPositions; 8 | for (auto& f : factory) 9 | for (int i = 0; i < f[1]; i++) factoryPositions.push_back(f[0]); 10 | 11 | int robotCount = robot.size(), factoryCount = factoryPositions.size(); 12 | vector> memo(robotCount, vector(factoryCount, -1)); 13 | return calculateMinDistance(0, 0, robot, factoryPositions, memo); 14 | } 15 | 16 | long long calculateMinDistance(int robotIdx, int factoryIdx,vector& robot,vector& factoryPositions,vector>& memo) { 17 | if (robotIdx == robot.size()) return 0; 18 | if (factoryIdx == factoryPositions.size()) return 1e12; 19 | if (memo[robotIdx][factoryIdx] != -1) return memo[robotIdx][factoryIdx]; 20 | long long assign = abs(robot[robotIdx] - factoryPositions[factoryIdx]) +calculateMinDistance(robotIdx + 1, factoryIdx + 1,robot, factoryPositions, memo); 21 | long long skip = calculateMinDistance(robotIdx, factoryIdx + 1, robot,factoryPositions, memo); 22 | 23 | return memo[robotIdx][factoryIdx] =min(assign, skip); 24 | } 25 | }; -------------------------------------------------------------------------------- /1942_The Number of the Smallest Unoccupied Chair: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestChair(vector>& times, int targetFriend) { 4 | int n = times.size(); 5 | priority_queue, vector>, 6 | greater>> 7 | occChair; 8 | priority_queue, greater> freeChair; 9 | 10 | int tar = times[targetFriend][0]; 11 | sort(times.begin(), times.end()); 12 | 13 | int chair = 0; 14 | 15 | for (int i = 0; i < n; i++) { 16 | int arr = times[i][0]; 17 | int dep = times[i][1]; 18 | 19 | while (!occChair.empty() && occChair.top().first <= arr) { 20 | freeChair.push(occChair.top().second); 21 | occChair.pop(); 22 | } 23 | 24 | if (freeChair.empty()) { 25 | occChair.push({dep, chair}); 26 | if (arr == tar) { 27 | return chair; 28 | } 29 | chair++; 30 | } else { 31 | int minChair = freeChair.top(); 32 | freeChair.pop(); 33 | if (arr == tar) { 34 | return minChair; 35 | } 36 | occChair.push({dep, minChair}); 37 | } 38 | } 39 | return -1; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /1639. Number of Ways to Form a Target String Given a Dictionary: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWays(vector& words, string target) { 4 | int wordLength = words[0].size(); 5 | int targetLength = target.size(); 6 | const int MOD = 1000000007; 7 | vector> charFrequency(wordLength, vector(26, 0)); 8 | for (const string& word : words) { 9 | for (int j = 0; j < wordLength; ++j) { 10 | charFrequency[j][word[j] - 'a']++; 11 | } 12 | } 13 | 14 | 15 | vector> dp(wordLength + 1,vector(targetLength + 1, 0)); 16 | for (int currWord = 0; currWord <= wordLength; ++currWord) { 17 | dp[currWord][0] = 1; 18 | } 19 | for (int currWord = 1; currWord <= wordLength; ++currWord) { 20 | for (int currTarget = 1; currTarget <= targetLength; ++currTarget) { 21 | dp[currWord][currTarget] = dp[currWord - 1][currTarget]; 22 | int curPos = target[currTarget - 1] - 'a'; 23 | dp[currWord][currTarget] += 24 | (charFrequency[currWord - 1][curPos] * 25 | dp[currWord - 1][currTarget - 1]) % 26 | MOD; 27 | dp[currWord][currTarget] %= MOD; 28 | } 29 | } 30 | 31 | return dp[wordLength][targetLength]; 32 | } 33 | }; -------------------------------------------------------------------------------- /2948. Make Lexicographically Smallest Array by Swapping: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector lexicographicallySmallestArray(vector& nums, int limit) { 4 | vector numsSorted(nums); 5 | sort(numsSorted.begin(), numsSorted.end()); 6 | 7 | int currGroup = 0; 8 | unordered_map numToGroup; 9 | numToGroup.insert(pair(numsSorted[0], currGroup)); 10 | 11 | unordered_map> groupToList; 12 | groupToList.insert( 13 | pair>(currGroup, list(1, numsSorted[0]))); 14 | 15 | for (int i = 1; i < nums.size(); i++) { 16 | if (abs(numsSorted[i] - numsSorted[i - 1]) > limit) { 17 | 18 | currGroup++; 19 | } 20 | 21 | 22 | numToGroup.insert(pair(numsSorted[i], currGroup)); 23 | 24 | 25 | if (groupToList.find(currGroup) == groupToList.end()) { 26 | groupToList[currGroup] = list(); 27 | } 28 | groupToList[currGroup].push_back(numsSorted[i]); 29 | } 30 | 31 | 32 | for (int i = 0; i < nums.size(); i++) { 33 | int num = nums[i]; 34 | int group = numToGroup[num]; 35 | nums[i] = *groupToList[group].begin(); 36 | groupToList[group].pop_front(); 37 | } 38 | 39 | return nums; 40 | } 41 | }; -------------------------------------------------------------------------------- /3097. Shortest Subarray With OR at Least K II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumSubarrayLength(vector& nums, int k) { 4 | int minLength = INT_MAX; 5 | int windowStart = 0; 6 | int windowEnd = 0; 7 | vector bitCounts(32,0); 8 | while (windowEnd < nums.size()) { 9 | updateBitCounts(bitCounts, nums[windowEnd], 1); 10 | while (windowStart <= windowEnd && convertBitCountsToNumber(bitCounts) >= k) { 11 | minLength = min(minLength, windowEnd - windowStart + 1); 12 | updateBitCounts(bitCounts, nums[windowStart], -1); 13 | windowStart++; 14 | } 15 | 16 | windowEnd++; 17 | } 18 | 19 | return minLength == INT_MAX ? -1 : minLength; 20 | } 21 | 22 | private: 23 | void updateBitCounts(vector& bitCounts, int number, int delta) { 24 | for (int bitPosition = 0; bitPosition < 32; bitPosition++) { 25 | if ((number >> bitPosition) & 1) { 26 | bitCounts[bitPosition] += delta; 27 | } 28 | } 29 | } 30 | int convertBitCountsToNumber(const vector& bitCounts) { 31 | int result = 0; 32 | for (int bitPosition = 0; bitPosition < 32; bitPosition++) { 33 | if (bitCounts[bitPosition] != 0) { 34 | result |= 1 << bitPosition; 35 | } 36 | } 37 | return result; 38 | } 39 | }; -------------------------------------------------------------------------------- /2415. Reverse Odd Levels of Binary Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | #include 13 | #include 14 | 15 | class Solution { 16 | public: 17 | TreeNode* reverseOddLevels(TreeNode* root) { 18 | queue q; 19 | if (root) q.push(root); 20 | int level = 0; 21 | vector cur_level; 22 | while (q.size()) { 23 | int q_len = q.size(); 24 | for (int i = 0; i < q_len; i++) { 25 | auto* cur_node = q.front(); 26 | q.pop(); 27 | if (level % 2) { 28 | cur_level.push_back(cur_node); 29 | } 30 | if (cur_node->left) q.push(cur_node->left); 31 | if (cur_node->right) q.push(cur_node->right); 32 | } 33 | if (level%2) { 34 | for (int i = 0; i < cur_level.size() / 2 ; i++) { 35 | swap(cur_level[i]->val, cur_level[cur_level.size()-i-1]->val); 36 | } 37 | } 38 | cur_level.clear(); 39 | level++; 40 | } 41 | return root; 42 | } 43 | }; -------------------------------------------------------------------------------- /684. Redundant Connection: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int src, vector>& adjList,vector& visited,vector& parent,vector& cycle){ 4 | visited[src]=true; 5 | 6 | for(int adj:adjList[src]){ 7 | if(!visited[adj]){ 8 | parent[adj]=src; 9 | dfs(adj,adjList,visited,parent,cycle); 10 | } 11 | else if(parent[src]!=adj && !cycle[src]){ 12 | int node=src; 13 | while(node!=adj){ 14 | cycle[node]=true; 15 | node=parent[node]; 16 | } 17 | cycle[adj]=true; 18 | cycle[src]=true; 19 | } 20 | } 21 | } 22 | vector findRedundantConnection(vector>& edges) { 23 | int n=edges.size(); 24 | 25 | vector> adjList(n); 26 | 27 | 28 | for(auto edge:edges){ 29 | int u=edge[0]-1; 30 | int v=edge[1]-1; 31 | adjList[u].push_back(v); 32 | adjList[v].push_back(u); 33 | } 34 | 35 | vectorvisited(n,false); 36 | vectorparent(n,-1); 37 | vectorcycle(n,false); 38 | 39 | 40 | dfs(0,adjList,visited,parent,cycle); 41 | 42 | for(int i=n-1;i>=0;i--){ 43 | if(cycle[edges[i][0]-1] && cycle[edges[i][1]-1] ){ 44 | return edges[i]; 45 | } 46 | } 47 | return {}; 48 | 49 | } 50 | }; -------------------------------------------------------------------------------- /1015-smallest-integer-divisible-by-k/README.md: -------------------------------------------------------------------------------- 1 |

1064. Smallest Integer Divisible by K

Medium


Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.

2 | 3 |

Return the length of n. If there is no such n, return -1.

4 | 5 |

Note: n may not fit in a 64-bit signed integer.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: k = 1
12 | Output: 1
13 | Explanation: The smallest answer is n = 1, which has length 1.
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: k = 2
20 | Output: -1
21 | Explanation: There is no such positive integer n divisible by 2.
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: k = 3
28 | Output: 3
29 | Explanation: The smallest answer is n = 111, which has length 3.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= k <= 105
  • 37 |
38 | -------------------------------------------------------------------------------- /2116. Check if a Parentheses String Can Be Valid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canBeValid(string s, string locked) { 4 | int length = s.size(); 5 | 6 | if (length % 2 == 1) { 7 | return false; 8 | } 9 | int openBrackets = 0, unlocked = 0; 10 | 11 | for (int i = 0; i < length; i++) { 12 | if (locked[i] == '0') { 13 | unlocked++; 14 | } else if (s[i] == '(') { 15 | openBrackets++; 16 | } else if (s[i] == ')') { 17 | if (openBrackets > 0) { 18 | openBrackets--; 19 | } else if (unlocked > 0) { 20 | unlocked--; 21 | } else { 22 | return false; 23 | } 24 | } 25 | } 26 | 27 | int balance = 0; 28 | for (int i = length - 1; i >= 0; i--) { 29 | if (locked[i] == '0') { 30 | balance--; 31 | unlocked--; 32 | } else if (s[i] == '(') { 33 | balance++; 34 | openBrackets--; 35 | } else if (s[i] == ')') { 36 | balance--; 37 | } 38 | if (balance > 0) { 39 | return false; 40 | } 41 | if (unlocked == 0 and openBrackets == 0) { 42 | break; 43 | } 44 | } 45 | 46 | if (openBrackets > 0) { 47 | return false; 48 | } 49 | 50 | return true; 51 | } 52 | }; -------------------------------------------------------------------------------- /1018-binary-prefix-divisible-by-5/README.md: -------------------------------------------------------------------------------- 1 |

1071. Binary Prefix Divisible By 5

Easy


You are given a binary array nums (0-indexed).

2 | 3 |

We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).

4 | 5 |
    6 |
  • For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.
  • 7 |
8 | 9 |

Return an array of booleans answer where answer[i] is true if xi is divisible by 5.

10 | 11 |

 

12 |

Example 1:

13 | 14 |
15 | Input: nums = [0,1,1]
16 | Output: [true,false,false]
17 | Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
18 | Only the first number is divisible by 5, so answer[0] is true.
19 | 
20 | 21 |

Example 2:

22 | 23 |
24 | Input: nums = [1,1,1]
25 | Output: [false,false,false]
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • 1 <= nums.length <= 105
  • 33 |
  • nums[i] is either 0 or 1.
  • 34 |
35 | -------------------------------------------------------------------------------- /2097. Valid Arrangement of Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> validArrangement(vector>& pairs) { 4 | unordered_map> adjacencyMatrix; 5 | unordered_map inDegree, outDegree; 6 | 7 | for (const auto& pair : pairs) { 8 | int start = pair[0], end = pair[1]; 9 | adjacencyMatrix[start].push_back(end); 10 | outDegree[start]++; 11 | inDegree[end]++; 12 | } 13 | 14 | vector result; 15 | 16 | 17 | function visit = [&](int node) { 18 | while (!adjacencyMatrix[node].empty()) { 19 | int nextNode = adjacencyMatrix[node].front(); 20 | adjacencyMatrix[node].pop_front(); 21 | visit(nextNode); 22 | } 23 | result.push_back(node); 24 | }; 25 | 26 | 27 | int startNode = -1; 28 | for (const auto& entry : outDegree) { 29 | int node = entry.first; 30 | if (outDegree[node] == inDegree[node] + 1) { 31 | startNode = node; 32 | break; 33 | } 34 | } 35 | 36 | 37 | if (startNode == -1) { 38 | startNode = pairs[0][0]; 39 | } 40 | 41 | 42 | visit(startNode); 43 | 44 | 45 | reverse(result.begin(), result.end()); 46 | 47 | 48 | vector> pairedResult; 49 | for (int i = 1; i < result.size(); ++i) { 50 | pairedResult.push_back({result[i - 1], result[i]}); 51 | } 52 | 53 | return pairedResult; 54 | } 55 | }; -------------------------------------------------------------------------------- /3152. Special Array II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector isArraySpecial(vector& nums, 4 | vector>& queries) { 5 | vector ans(queries.size()); 6 | vector violatingIndices; 7 | 8 | for (int i = 1; i < nums.size(); i++) { 9 | 10 | if (nums[i] % 2 == nums[i - 1] % 2) { 11 | violatingIndices.push_back(i); 12 | } 13 | } 14 | 15 | for (int i = 0; i < queries.size(); i++) { 16 | vector query = queries[i]; 17 | int start = query[0]; 18 | int end = query[1]; 19 | 20 | bool foundViolatingIndex = 21 | binarySearch(start + 1, end, violatingIndices); 22 | 23 | if (foundViolatingIndex) { 24 | ans[i] = false; 25 | } else { 26 | ans[i] = true; 27 | } 28 | } 29 | 30 | return ans; 31 | } 32 | 33 | private: 34 | bool binarySearch(int start, int end, vector& violatingIndices) { 35 | int left = 0; 36 | int right = violatingIndices.size() - 1; 37 | while (left <= right) { 38 | int mid = left + (right - left) / 2; 39 | int violatingIndex = violatingIndices[mid]; 40 | 41 | if (violatingIndex < start) { 42 | 43 | left = mid + 1; 44 | } else if (violatingIndex > end) { 45 | 46 | right = mid - 1; 47 | } else { 48 | 49 | return true; 50 | } 51 | } 52 | 53 | return false; 54 | } 55 | }; -------------------------------------------------------------------------------- /3203. Find Minimum Diameter After Merging Two Trees: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | 5 | int diameter(int root, int parent, vector> &graph, int &ans){ 6 | 7 | int mx1 = -1, mx2 = -1; 8 | for(auto &child: graph[root]){ 9 | if(child != parent){ 10 | int m = diameter(child, root, graph, ans); 11 | if(m >= mx1){ 12 | mx2 = mx1; 13 | mx1 = m; 14 | } 15 | else if(m > mx2) mx2 = m; 16 | } 17 | } 18 | 19 | if(mx2 != -1) ans = max(ans, 2 + mx1 + mx2); 20 | if(mx1 != -1) ans = max(ans, 1 + mx1); 21 | 22 | if(mx1 != -1){ 23 | return 1 + mx1; 24 | } 25 | return 0; 26 | 27 | } 28 | 29 | int minimumDiameterAfterMerge(vector>& edges1, vector>& edges2) { 30 | 31 | int m = edges1.size() + 1; 32 | int n = edges2.size() + 1; 33 | 34 | vector> graph1(m), graph2(n); 35 | 36 | for(auto &edge: edges1){ 37 | graph1[edge[0]].push_back(edge[1]); 38 | graph1[edge[1]].push_back(edge[0]); 39 | } 40 | for(auto &edge: edges2){ 41 | graph2[edge[0]].push_back(edge[1]); 42 | graph2[edge[1]].push_back(edge[0]); 43 | } 44 | 45 | int dia1 = 0, dia2 = 0; 46 | diameter(0, -1, graph1, dia1); 47 | diameter(0, -1, graph2, dia2); 48 | cout<containskey(c)){ 33 | node->put(c,new Node()); 34 | } 35 | node=node->get(c); 36 | } 37 | 38 | node->setend(); 39 | } 40 | 41 | bool search(string word) { 42 | Node* node=root; 43 | for(char c:word){ 44 | if(!node->containskey(c)){ 45 | return false; 46 | } 47 | node=node->get(c); 48 | } 49 | return node->isend(); 50 | } 51 | 52 | bool startsWith(string prefix) { 53 | Node* node=root; 54 | for(char c:prefix){ 55 | if(!node->containskey(c)){ 56 | return false; 57 | } 58 | node=node->get(c); 59 | } 60 | return true; 61 | } 62 | }; 63 | 64 | /** 65 | * Your Trie object will be instantiated and called as such: 66 | * Trie* obj = new Trie(); 67 | * obj->insert(word); 68 | * bool param_2 = obj->search(word); 69 | * bool param_3 = obj->startsWith(prefix); 70 | */ -------------------------------------------------------------------------------- /2471. Minimum Number of Operations to Sort a Binary Tree by Level: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int getswap(vector& vec){ 15 | vectorsortedvec(vec.begin(),vec.end()); 16 | sort(sortedvec.begin(),sortedvec.end()); 17 | int swaps=0; 18 | unordered_mapmp; 19 | 20 | for(int i=0;iq; 37 | q.push(root); 38 | int swaps=0; 39 | while(!q.empty()){ 40 | int n=q.size(); 41 | vectorvec(n); 42 | for(int i=0;ival; 46 | if(node->left!=NULL)q.push(node->left); 47 | if(node->right!=NULL)q.push(node->right); 48 | } 49 | swaps+=getswap(vec); 50 | } 51 | return swaps; 52 | } 53 | }; -------------------------------------------------------------------------------- /417. Pacific Atlantic Water Flow: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int m, n; 4 | vector> dirs{{1,0},{-1,0},{0,1},{0,-1}}; 5 | 6 | void bfs(vector>& h, queue>& q, vector>& vis) { 7 | while(!q.empty()) { 8 | auto [i, j] = q.front(); 9 | q.pop(); 10 | 11 | for(auto &d : dirs) { 12 | int x = i + d[0], y = j + d[1]; 13 | if(x >= 0 && y >= 0 && x < m && y < n && !vis[x][y] && h[x][y] >= h[i][j]) { 14 | vis[x][y] = true; 15 | q.push({x, y}); 16 | } 17 | } 18 | } 19 | } 20 | 21 | vector> pacificAtlantic(vector>& heights) { 22 | m = heights.size(); 23 | n = heights[0].size(); 24 | 25 | vector> pac(m, vector(n, false)); 26 | vector> atl(m, vector(n, false)); 27 | queue> pq, aq; 28 | 29 | for(int i = 0; i < m; i++) { 30 | pq.push({i, 0}); 31 | aq.push({i, n - 1}); 32 | pac[i][0] = true; 33 | atl[i][n - 1] = true; 34 | } 35 | 36 | for(int j = 0; j < n; j++) { 37 | pq.push({0, j}); 38 | aq.push({m - 1, j}); 39 | pac[0][j] = true; 40 | atl[m - 1][j] = true; 41 | } 42 | 43 | bfs(heights, pq, pac); 44 | bfs(heights, aq, atl); 45 | 46 | vector> res; 47 | for(int i = 0; i < m; i++) { 48 | for(int j = 0; j < n; j++) { 49 | if(pac[i][j] && atl[i][j]) { 50 | res.push_back({i, j}); 51 | } 52 | } 53 | } 54 | return res; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /2257. Count Unguarded Cells in the Grid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void maxcount(int row,int col,vector>& grid){ 4 | // up 5 | for(int i=row-1;i>=0;i--){ 6 | if(grid[i][col]==2 || grid[i][col]==3){ 7 | break; 8 | } 9 | grid[i][col]=1; 10 | } 11 | // down 12 | for(int i=row+1;i=0;i--){ 20 | if(grid[row][i]==2 || grid[row][i]==3){ 21 | break; 22 | } 23 | grid[row][i]=1; 24 | } 25 | // right 26 | for(int i=col+1;i>& guards, vector>& walls) { 34 | vector>grid(m,vector(n,0)); 35 | for(vector&vec:guards){ 36 | int i=vec[0]; 37 | int j=vec[1]; 38 | grid[i][j]=2; 39 | } 40 | for(vector&vec:walls){ 41 | int i=vec[0]; 42 | int j=vec[1]; 43 | grid[i][j]=3; 44 | } 45 | for(vector&vec:guards){ 46 | int i=vec[0]; 47 | int j=vec[1]; 48 | maxcount(i,j,grid); 49 | } 50 | int count=0; 51 | for(int i=0;i>& grid) { 4 | 5 | if (grid[0][1] > 1 && grid[1][0] > 1) { 6 | return -1; 7 | } 8 | 9 | int rows = grid.size(), cols = grid[0].size(); 10 | 11 | vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 12 | vector> visited(rows, vector(cols, false)); 13 | 14 | 15 | priority_queue, vector>, greater<>> pq; 16 | pq.push({grid[0][0], 0, 0}); 17 | 18 | while (!pq.empty()) { 19 | auto curr = pq.top(); 20 | pq.pop(); 21 | int time = curr[0], row = curr[1], col = curr[2]; 22 | 23 | 24 | if (row == rows - 1 && col == cols - 1) { 25 | return time; 26 | } 27 | 28 | if (visited[row][col]) { 29 | continue; 30 | } 31 | visited[row][col] = true; 32 | 33 | 34 | for (auto& d : directions) { 35 | int nextRow = row + d[0], nextCol = col + d[1]; 36 | if (!isValid(visited, nextRow, nextCol)) { 37 | continue; 38 | } 39 | 40 | 41 | int waitTime = 42 | ((grid[nextRow][nextCol] - time) % 2 == 0) ? 1 : 0; 43 | int nextTime = max(grid[nextRow][nextCol] + waitTime, time + 1); 44 | pq.push({nextTime, nextRow, nextCol}); 45 | } 46 | } 47 | return -1; 48 | } 49 | 50 | private: 51 | 52 | bool isValid(vector>& visited, int row, int col) { 53 | return row >= 0 && col >= 0 && row < visited.size() && 54 | col < visited[0].size() && !visited[row][col]; 55 | } 56 | }; -------------------------------------------------------------------------------- /1408. String Matching in an Array(kmp): -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void computelps(vector& lps,string& pat){ 4 | int m=pat.size(); 5 | int length=0; 6 | lps[0]=0; 7 | int i=1; 8 | while(ilps(m,0); 29 | 30 | computelps(lps,pat); 31 | int i=0; 32 | int j=0; 33 | 34 | while(i stringMatching(vector& words) { 54 | int n=words.size(); 55 | vectorresult; 56 | for(int i=0;i>& adjList) { 5 | vector visited(n, false); 6 | queue nodeQueue; 7 | 8 | nodeQueue.push(0); 9 | visited[0] = true; 10 | 11 | 12 | int currentLayerNodeCount = 1; 13 | int nextLayerNodeCount = 0; 14 | 15 | int layersExplored = 0; 16 | while (!nodeQueue.empty()) { 17 | 18 | for (int i = 0; i < currentLayerNodeCount; ++i) { 19 | int currentNode = nodeQueue.front(); 20 | nodeQueue.pop(); 21 | 22 | if (currentNode == n - 1) { 23 | return layersExplored; 24 | } 25 | 26 | for (auto neighbor : adjList[currentNode]) { 27 | if (visited[neighbor]) continue; 28 | nodeQueue.push(neighbor); 29 | nextLayerNodeCount++; 30 | visited[neighbor] = true; 31 | } 32 | } 33 | 34 | currentLayerNodeCount = nextLayerNodeCount; 35 | nextLayerNodeCount = 0; 36 | layersExplored++; 37 | 38 | } 39 | 40 | return -1; 41 | } 42 | 43 | vector shortestDistanceAfterQueries(int n, vector>& queries) { 44 | vector answer; 45 | vector> adjList(n, vector(0)); 46 | 47 | 48 | for (int i = 0; i < n - 1; i++) { 49 | adjList[i].push_back(i + 1); 50 | } 51 | 52 | for (auto& road : queries) { 53 | int u = road[0]; 54 | int v = road[1]; 55 | adjList[u].push_back(v); 56 | 57 | answer.push_back(bfs(n, adjList)); 58 | } 59 | 60 | return answer; 61 | } 62 | }; 63 | 64 | -------------------------------------------------------------------------------- /2641. Cousins in Binary Tree II: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* replaceValueInTree(TreeNode* root) { 15 | if (!root) return root; 16 | 17 | queue q; 18 | q.push(root); 19 | vector levelsum; 20 | while (!q.empty()) { 21 | int sum = 0; 22 | int n = q.size(); 23 | for (int i = 0; i < n; i++) { 24 | TreeNode* node = q.front(); 25 | q.pop(); 26 | sum += node->val; 27 | if (node->left != NULL) q.push(node->left); 28 | if (node->right != NULL) q.push(node->right); 29 | } 30 | levelsum.push_back(sum); 31 | } 32 | q.push(root); 33 | int levelIndex = 1; 34 | root->val = 0; 35 | 36 | while (!q.empty()) { 37 | int n = q.size(); 38 | for (int i = 0; i < n; i++) { 39 | TreeNode* node = q.front(); 40 | q.pop(); 41 | int siblingSum = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); 42 | if (node->left) { 43 | node->left->val = levelsum[levelIndex] - siblingSum; 44 | q.push(node->left); 45 | } 46 | if (node->right) { 47 | node->right->val = levelsum[levelIndex] - siblingSum; 48 | q.push(node->right); 49 | } 50 | } 51 | levelIndex++; 52 | } 53 | 54 | return root; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /2110-number-of-smooth-descent-periods-of-a-stock/README.md: -------------------------------------------------------------------------------- 1 |

2233. Number of Smooth Descent Periods of a Stock

Medium


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

2 | 3 |

A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule.

4 | 5 |

Return the number of smooth descent periods.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: prices = [3,2,1,4]
12 | Output: 7
13 | Explanation: There are 7 smooth descent periods:
14 | [3], [2], [1], [4], [3,2], [2,1], and [3,2,1]
15 | Note that a period with one day is a smooth descent period by the definition.
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: prices = [8,6,7,7]
22 | Output: 4
23 | Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7]
24 | Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.
25 | 
26 | 27 |

Example 3:

28 | 29 |
30 | Input: prices = [1]
31 | Output: 1
32 | Explanation: There is 1 smooth descent period: [1]
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • 1 <= prices.length <= 105
  • 40 |
  • 1 <= prices[i] <= 105
  • 41 |
42 | -------------------------------------------------------------------------------- /1092. Shortest Common Supersequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestCommonSupersequence(string str1, string str2) { 4 | int str1Length = str1.length(); 5 | int str2Length = str2.length(); 6 | 7 | vector> dp(str1Length + 1, vector(str2Length + 1, 0)); 8 | 9 | 10 | for (int row = 0; row <= str1Length; row++) { 11 | dp[row][0] = row; 12 | } 13 | 14 | for (int col = 0; col <= str2Length; col++) { 15 | dp[0][col] = col; 16 | } 17 | 18 | for (int row = 1; row <= str1Length; row++) { 19 | for (int col = 1; col <= str2Length; col++) { 20 | if (str1[row - 1] == str2[col - 1]) { 21 | 22 | dp[row][col] = dp[row - 1][col - 1] + 1; 23 | } else { 24 | 25 | dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + 1; 26 | } 27 | } 28 | } 29 | 30 | string supersequence = ""; 31 | int row = str1Length, col = str2Length; 32 | 33 | while (row > 0 && col > 0) { 34 | if (str1[row - 1] == str2[col - 1]) { 35 | 36 | supersequence += str1[row - 1]; 37 | row--; 38 | col--; 39 | } else if (dp[row - 1][col] < dp[row][col - 1]) { 40 | 41 | supersequence += str1[row - 1]; 42 | row--; 43 | } else { 44 | 45 | supersequence += str2[col - 1]; 46 | col--; 47 | } 48 | } 49 | 50 | 51 | while (row > 0) { 52 | supersequence += str1[row - 1]; 53 | row--; 54 | } 55 | 56 | while (col > 0) { 57 | supersequence += str2[col - 1]; 58 | col--; 59 | } 60 | 61 | 62 | reverse(supersequence.begin(), supersequence.end()); 63 | return supersequence; 64 | } 65 | }; -------------------------------------------------------------------------------- /2685. Count the Number of Complete Components: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countCompleteComponents(int n, vector>& edges) { 4 | // Create adjacency list representation of the graph 5 | vector> graph(n); 6 | for (const auto& edge : edges) { 7 | int u = edge[0], v = edge[1]; 8 | graph[u].push_back(v); 9 | graph[v].push_back(u); 10 | } 11 | 12 | vector visited(n, false); 13 | int completeComponents = 0; 14 | 15 | // Process each unvisited vertex 16 | for (int vertex = 0; vertex < n; vertex++) { 17 | if (!visited[vertex]) { 18 | // BFS to find all vertices in the current component 19 | vector component; 20 | queue q; 21 | q.push(vertex); 22 | visited[vertex] = true; 23 | 24 | while (!q.empty()) { 25 | int current = q.front(); 26 | q.pop(); 27 | component.push_back(current); 28 | 29 | // Process neighbors 30 | for (int neighbor : graph[current]) { 31 | if (!visited[neighbor]) { 32 | q.push(neighbor); 33 | visited[neighbor] = true; 34 | } 35 | } 36 | } 37 | 38 | // Check if component is complete (all vertices have the right 39 | // number of edges) 40 | bool isComplete = true; 41 | for (int node : component) { 42 | if (graph[node].size() != component.size() - 1) { 43 | isComplete = false; 44 | break; 45 | } 46 | } 47 | 48 | if (isComplete) { 49 | completeComponents++; 50 | } 51 | } 52 | } 53 | 54 | return completeComponents; 55 | } 56 | }; -------------------------------------------------------------------------------- /3508. Implement Router: -------------------------------------------------------------------------------- 1 | class Router { 2 | private: 3 | int size; 4 | unordered_map> packets; 5 | unordered_map> counts; 6 | queue q; 7 | 8 | long long encode(int source, int destination, int timestamp) { 9 | return ((long long)source << 40) | ((long long)destination << 20) | timestamp; 10 | } 11 | 12 | int lowerBound(vector& list, int target) { 13 | return (int)(lower_bound(list.begin(), list.end(), target) - list.begin()); 14 | } 15 | 16 | int upperBound(vector& list, int target) { 17 | return (int)(upper_bound(list.begin(), list.end(), target) - list.begin()); 18 | } 19 | 20 | public: 21 | Router(int memoryLimit) { 22 | size = memoryLimit; 23 | } 24 | 25 | bool addPacket(int source, int destination, int timestamp) { 26 | long long key = encode(source, destination, timestamp); 27 | 28 | if (packets.find(key) != packets.end()) 29 | return false; 30 | 31 | if ((int)packets.size() >= size) 32 | forwardPacket(); 33 | 34 | packets[key] = {source, destination, timestamp}; 35 | q.push(key); 36 | counts[destination].push_back(timestamp); 37 | 38 | return true; 39 | } 40 | 41 | vector forwardPacket() { 42 | if (packets.empty()) return {}; 43 | 44 | long long key = q.front(); 45 | q.pop(); 46 | 47 | vector packet = packets[key]; 48 | packets.erase(key); 49 | 50 | int dest = packet[1]; 51 | counts[dest].erase(counts[dest].begin()); 52 | 53 | return packet; 54 | } 55 | 56 | int getCount(int destination, int startTime, int endTime) { 57 | auto it = counts.find(destination); 58 | if (it == counts.end() || it->second.empty()) 59 | return 0; 60 | 61 | vector& list = it->second; 62 | 63 | int left = lowerBound(list, startTime); 64 | int right = upperBound(list, endTime); 65 | 66 | return right - left; 67 | } 68 | }; -------------------------------------------------------------------------------- /2940. Find Building Where Alice and Bob Can Meet: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Segtree { 5 | private: 6 | vector tree; 7 | int n; 8 | 9 | void build(const vector& arr, int v, int L, int R) { 10 | if (L == R) { 11 | tree[v] = arr[L]; 12 | } else { 13 | build(arr, 2 * v, L, (L + R) / 2); 14 | build(arr, 2 * v + 1, (L + R) / 2 + 1, R); 15 | tree[v] = max(tree[2 * v], tree[2 * v + 1]); 16 | } 17 | } 18 | 19 | int leftmost_gt(int v, int lv, int rv, int l, int r, int x) { 20 | if (lv > r || rv < l) return -1; 21 | if (l <= lv && rv <= r) { 22 | if (tree[v] <= x) return -1; 23 | while (lv != rv) { 24 | const int mid = (lv + rv) / 2; 25 | if (tree[2 * v] > x) { 26 | v = 2 * v; 27 | rv = mid; 28 | } else { 29 | v = 2 * v + 1; 30 | lv = mid + 1; 31 | } 32 | } 33 | return lv; 34 | } 35 | 36 | const int mid = (lv + rv) / 2; 37 | const int val = leftmost_gt(2 * v, lv, mid, l, r, x); 38 | if (val != -1) return val; 39 | return leftmost_gt(2 * v + 1, mid + 1, rv, l, r, x); 40 | } 41 | 42 | public: 43 | Segtree(const vector& arr) : n(arr.size()) { 44 | tree.assign(4 * n, 0); 45 | build(arr, 1, 0, n - 1); 46 | } 47 | 48 | int leftmost_gt(int i, int x) { return leftmost_gt(1, 0, n - 1, i, n - 1, x); } 49 | }; 50 | 51 | class Solution { 52 | public: 53 | vector leftmostBuildingQueries(const vector& heights,const vector>& queries) { 54 | Segtree st(heights); 55 | 56 | vector ans; 57 | 58 | for (const vector& q : queries) { 59 | const auto [i, j] = minmax(q.front(), q.back()); 60 | 61 | if (i == j) { 62 | ans.emplace_back(i); 63 | continue; 64 | } 65 | 66 | const int max_height = max(heights[i], heights[j]); 67 | 68 | if (heights[i] < heights[j]) { 69 | ans.emplace_back(j); 70 | } else { 71 | ans.emplace_back(st.leftmost_gt(j, max_height)); 72 | } 73 | } 74 | 75 | return ans; 76 | } 77 | }; -------------------------------------------------------------------------------- /3306. Count of Substrings Containing Every Vowel and K Consonants II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool isVowel(char c) { 4 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; 5 | } 6 | 7 | public: 8 | long countOfSubstrings(string word, int k) { 9 | long numValidSubstrings = 0; 10 | int start = 0; 11 | int end = 0; 12 | unordered_map vowelCount; 13 | int consonantCount = 0; 14 | 15 | vector nextConsonant(word.size()); 16 | int nextConsonantIndex = word.size(); 17 | for (int i = word.size() - 1; i >= 0; i--) { 18 | nextConsonant[i] = nextConsonantIndex; 19 | if (!isVowel(word[i])) { 20 | nextConsonantIndex = i; 21 | } 22 | } 23 | 24 | while (end < word.size()) { 25 | char newLetter = word[end]; 26 | 27 | if (isVowel(newLetter)) { 28 | vowelCount[newLetter]++; 29 | } else { 30 | consonantCount++; 31 | } 32 | 33 | while (consonantCount > k) { 34 | char startLetter = word[start]; 35 | if (isVowel(startLetter)) { 36 | vowelCount[startLetter]--; 37 | if (vowelCount[startLetter] == 0) { 38 | vowelCount.erase(startLetter); 39 | } 40 | } else { 41 | consonantCount--; 42 | } 43 | start++; 44 | } 45 | 46 | while (start < word.size() && vowelCount.size() == 5 && 47 | consonantCount == k) { 48 | numValidSubstrings += nextConsonant[end] - end; 49 | char startLetter = word[start]; 50 | if (isVowel(startLetter)) { 51 | vowelCount[startLetter]--; 52 | if (vowelCount[startLetter] == 0) { 53 | vowelCount.erase(startLetter); 54 | } 55 | } else { 56 | consonantCount--; 57 | } 58 | 59 | start++; 60 | } 61 | end++; 62 | } 63 | 64 | return numValidSubstrings; 65 | } 66 | }; -------------------------------------------------------------------------------- /stats.json: -------------------------------------------------------------------------------- 1 | {"leetcode":{"easy":4,"hard":0,"medium":6,"shas":{"0047-permutations-ii":{"0047-permutations-ii.cpp":"4ab9acc4831b7143473343c6a1f119900d3413fc","README.md":"e4746eb8914468f3224dbbf99026d522d990050c"},"1262-greatest-sum-divisible-by-three":{"1262-greatest-sum-divisible-by-three.cpp":"b0f986670938ea9cbd20826133facaf9463e743c","README.md":"d901b77965f97bf0e9fa5f9cc29c81fd4cfcc899","difficulty":"medium"},"README.md":{"":"69a784797caf1149b07d92d15e54979ad13290c8"},"1018-binary-prefix-divisible-by-5":{"1018-binary-prefix-divisible-by-5.cpp":"9cae372407802a08cb7e01540b33bd28779a7582","README.md":"19aa97ad8ea79ccdcf4c8e1de3680fd5e75b24d1","difficulty":"easy"},"stats.json":{"":"6983e90df0f8488d7ae2988dfcda11409d8ea967"},"1015-smallest-integer-divisible-by-k":{"1015-smallest-integer-divisible-by-k.cpp":"0c86bb86fc6a60326b98c2336e195db6ad09ed5b","README.md":"b9ad37125ecf9939522541a7307274d971816c2f","difficulty":"medium"},"2211-count-collisions-on-a-road":{"2211-count-collisions-on-a-road.cpp":"69f049aef6c960fd1ebf3d16cd0ca10c7645dcf4","README.md":"758f0e05abd57f60a5882e71337fc60afdaa8833","difficulty":"medium"},"3432-count-partitions-with-even-sum-difference":{"3432-count-partitions-with-even-sum-difference.cpp":"b7bd0eb4ddd24d8bfafe4ad0dc169bdf16d5f6bb","README.md":"08a84b853657404f3caae1698f7e1dbf0f6f4dc8","difficulty":"easy"},"3578-count-partitions-with-max-min-difference-at-most-k":{"3578-count-partitions-with-max-min-difference-at-most-k.cpp":"40c00277d13b046ae8643731045efbf85a470250","README.md":"293534f4dada06b3e41c5ac8169f67ed14a4e02b","difficulty":"medium"},"1523-count-odd-numbers-in-an-interval-range":{"1523-count-odd-numbers-in-an-interval-range.cpp":"da4c7abfb9b718860f96b9215db4c609c956ad79","README.md":"09cdcaa1d9599937ea00097f5d375c04e4c8c04b","difficulty":"easy"},"1925-count-square-sum-triples":{"1925-count-square-sum-triples.cpp":"690dda4cbdfc534c2ee0516f3777b2acaec2b1d9","README.md":"7dad7098bc77df25ba78bd09572351008255cc6e","difficulty":"easy"},"3531-count-covered-buildings":{"3531-count-covered-buildings.cpp":"8c8ec33f4be21690d57cc9a23f92c5858f6aab83","README.md":"0ad1608da51ecb4a14310d244e7a4417f25bdcef","difficulty":"medium"},"2110-number-of-smooth-descent-periods-of-a-stock":{"2110-number-of-smooth-descent-periods-of-a-stock.cpp":"11e41203d03f686153104f78ca6dd00c88301585","README.md":"375b941f9bfdf74febadff0b510717dc89155e5f","difficulty":"medium"}},"solved":10}} -------------------------------------------------------------------------------- /1976. Number of Ways to Arrive at Destination: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPaths(int n, vector>& roads) { 4 | const int MOD = 1e9 + 7; 5 | 6 | // Build adjacency list 7 | vector>> graph(n); 8 | for (auto& road : roads) { 9 | int startNode = road[0], endNode = road[1], travelTime = road[2]; 10 | graph[startNode].emplace_back(endNode, travelTime); 11 | graph[endNode].emplace_back(startNode, travelTime); 12 | } 13 | 14 | // Min-Heap (priority queue) for Dijkstra 15 | priority_queue, vector>, 16 | greater<>> 17 | minHeap; 18 | 19 | // Store shortest time to each node 20 | vector shortestTime(n, LLONG_MAX); 21 | // Number of ways to reach each node in shortest time 22 | vector pathCount(n, 0); 23 | 24 | shortestTime[0] = 0; // Distance to source is 0 25 | pathCount[0] = 1; // 1 way to reach node 0 26 | 27 | minHeap.emplace(0, 0); // {time, node} 28 | 29 | while (!minHeap.empty()) { 30 | long long currTime = minHeap.top().first; // Current shortest time 31 | int currNode = minHeap.top().second; 32 | minHeap.pop(); 33 | 34 | // Skip outdated distances 35 | if (currTime > shortestTime[currNode]) continue; 36 | 37 | for (auto& [neighborNode, roadTime] : graph[currNode]) { 38 | // Found a new shortest path → Update shortest time and reset 39 | // path count 40 | if (currTime + roadTime < shortestTime[neighborNode]) { 41 | shortestTime[neighborNode] = currTime + roadTime; 42 | pathCount[neighborNode] = pathCount[currNode]; 43 | minHeap.emplace(shortestTime[neighborNode], neighborNode); 44 | } 45 | // Found another way with the same shortest time → Add to path 46 | // count 47 | else if (currTime + roadTime == shortestTime[neighborNode]) { 48 | pathCount[neighborNode] = 49 | (pathCount[neighborNode] + pathCount[currNode]) % MOD; 50 | } 51 | } 52 | } 53 | 54 | return pathCount[n - 1]; 55 | } 56 | }; -------------------------------------------------------------------------------- /3578-count-partitions-with-max-min-difference-at-most-k/README.md: -------------------------------------------------------------------------------- 1 |

3835. Count Partitions With Max-Min Difference at Most K

Medium


You are given an integer array nums and an integer k. Your task is to partition nums into one or more non-empty contiguous segments such that in each segment, the difference between its maximum and minimum elements is at most k.

2 | 3 |

Return the total number of ways to partition nums under this condition.

4 | 5 |

Since the answer may be too large, return it modulo 109 + 7.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 |

Input: nums = [9,4,1,3,7], k = 4

12 | 13 |

Output: 6

14 | 15 |

Explanation:

16 | 17 |

There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most k = 4:

18 | 19 |
    20 |
  • [[9], [4], [1], [3], [7]]
  • 21 |
  • [[9], [4], [1], [3, 7]]
  • 22 |
  • [[9], [4], [1, 3], [7]]
  • 23 |
  • [[9], [4, 1], [3], [7]]
  • 24 |
  • [[9], [4, 1], [3, 7]]
  • 25 |
  • [[9], [4, 1, 3], [7]]
  • 26 |
27 |
28 | 29 |

Example 2:

30 | 31 |
32 |

Input: nums = [3,3,4], k = 0

33 | 34 |

Output: 2

35 | 36 |

Explanation:

37 | 38 |

There are 2 valid partitions that satisfy the given conditions:

39 | 40 |
    41 |
  • [[3], [3], [4]]
  • 42 |
  • [[3, 3], [4]]
  • 43 |
44 |
45 | 46 |

 

47 |

Constraints:

48 | 49 |
    50 |
  • 2 <= nums.length <= 5 * 104
  • 51 |
  • 1 <= nums[i] <= 109
  • 52 |
  • 0 <= k <= 109
  • 53 |
54 | -------------------------------------------------------------------------------- /2337. Move Pieces to Obtain a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canChange(string start, string target) { 4 | // To keep track of visited states to avoid cycles 5 | unordered_set visitedStates; 6 | // Queue for current state 7 | queue stateQueue; 8 | // Start with the initial state 9 | stateQueue.push(start); 10 | 11 | while (!stateQueue.empty()) { 12 | string currentState = stateQueue.front(); 13 | stateQueue.pop(); 14 | 15 | // If we reach the target state, return true 16 | if (currentState == target) return true; 17 | 18 | for (int position = 1; position < currentState.size(); position++) { 19 | // Try moving 'L' to the left 20 | if (currentState[position] == 'L' && 21 | currentState[position - 1] == '_') { 22 | swap(currentState[position], currentState[position - 1]); 23 | if (visitedStates.find(currentState) == 24 | visitedStates.end()) { 25 | // Add the new state to the queue 26 | stateQueue.push(currentState); 27 | // Mark the new state as visited 28 | visitedStates.insert(currentState); 29 | } 30 | // Restore the state 31 | swap(currentState[position], currentState[position - 1]); 32 | } 33 | // Try moving 'R' to the right 34 | if (currentState[position - 1] == 'R' && 35 | currentState[position] == '_') { 36 | swap(currentState[position], currentState[position - 1]); 37 | if (visitedStates.find(currentState) == 38 | visitedStates.end()) { 39 | // Add the new state to the queue 40 | stateQueue.push(currentState); 41 | // Mark the new state as visited 42 | visitedStates.insert(currentState); 43 | } 44 | // Restore the state 45 | swap(currentState[position], currentState[position - 1]); 46 | } 47 | } 48 | } 49 | 50 | // If no valid transformation sequence is found, return false 51 | return false; 52 | } 53 | }; -------------------------------------------------------------------------------- /3321. Find X-Sum of All K-Long Subarrays II: -------------------------------------------------------------------------------- 1 | class Helper { 2 | public: 3 | Helper(int x) { 4 | this->x = x; 5 | this->result = 0; 6 | } 7 | 8 | void insert(int num) { 9 | if (occ[num]) { 10 | internalRemove({occ[num], num}); 11 | } 12 | ++occ[num]; 13 | internalInsert({occ[num], num}); 14 | } 15 | 16 | void remove(int num) { 17 | internalRemove({occ[num], num}); 18 | --occ[num]; 19 | if (occ[num]) { 20 | internalInsert({occ[num], num}); 21 | } 22 | } 23 | 24 | long long get() { return result; } 25 | 26 | private: 27 | void internalInsert(const pair& p) { 28 | if (large.size() < x || p > *large.begin()) { 29 | result += static_cast(p.first) * p.second; 30 | large.insert(p); 31 | if (large.size() > x) { 32 | result -= static_cast(large.begin()->first) * 33 | large.begin()->second; 34 | auto transfer = *large.begin(); 35 | large.erase(transfer); 36 | small.insert(transfer); 37 | } 38 | } else { 39 | small.insert(p); 40 | } 41 | } 42 | 43 | void internalRemove(const pair& p) { 44 | if (p >= *large.begin()) { 45 | result -= static_cast(p.first) * p.second; 46 | large.erase(p); 47 | if (!small.empty()) { 48 | result += static_cast(small.rbegin()->first) * 49 | small.rbegin()->second; 50 | auto transfer = *small.rbegin(); 51 | small.erase(transfer); 52 | large.insert(transfer); 53 | } 54 | } else { 55 | small.erase(p); 56 | } 57 | } 58 | 59 | private: 60 | int x; 61 | long long result; 62 | set> large, small; 63 | unordered_map occ; 64 | }; 65 | 66 | class Solution { 67 | public: 68 | vector findXSum(vector& nums, int k, int x) { 69 | Helper helper(x); 70 | 71 | vector ans; 72 | for (int i = 0; i < nums.size(); ++i) { 73 | helper.insert(nums[i]); 74 | if (i >= k) { 75 | helper.remove(nums[i - k]); 76 | } 77 | if (i >= k - 1) { 78 | ans.push_back(helper.get()); 79 | } 80 | } 81 | return ans; 82 | } 83 | }; -------------------------------------------------------------------------------- /3347. Maximum Frequency of an Element After Performing Operations II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxFrequency(vector& nums, int k, int numOperations) { 4 | sort(nums.begin(), nums.end()); 5 | int ans = 0; 6 | unordered_map numCount; 7 | set modes; 8 | 9 | auto addMode = [&](int value) { 10 | modes.insert(value); 11 | if (value - k >= nums.front()) { 12 | modes.insert(value - k); 13 | } 14 | if (value + k <= nums.back()) { 15 | modes.insert(value + k); 16 | } 17 | }; 18 | 19 | int lastNumIndex = 0; 20 | for (int i = 0; i < nums.size(); ++i) { 21 | if (nums[i] != nums[lastNumIndex]) { 22 | numCount[nums[lastNumIndex]] = i - lastNumIndex; 23 | ans = max(ans, i - lastNumIndex); 24 | addMode(nums[lastNumIndex]); 25 | lastNumIndex = i; 26 | } 27 | } 28 | 29 | numCount[nums[lastNumIndex]] = nums.size() - lastNumIndex; 30 | ans = max(ans, (int)nums.size() - lastNumIndex); 31 | addMode(nums[lastNumIndex]); 32 | 33 | auto leftBound = [&](int value) { 34 | int left = 0, right = nums.size() - 1; 35 | while (left < right) { 36 | int mid = (left + right) / 2; 37 | if (nums[mid] < value) { 38 | left = mid + 1; 39 | } else { 40 | right = mid; 41 | } 42 | } 43 | return left; 44 | }; 45 | 46 | auto rightBound = [&](int value) { 47 | int left = 0, right = nums.size() - 1; 48 | while (left < right) { 49 | int mid = (left + right + 1) / 2; 50 | if (nums[mid] > value) { 51 | right = mid - 1; 52 | } else { 53 | left = mid; 54 | } 55 | } 56 | return left; 57 | }; 58 | 59 | for (int mode : modes) { 60 | int l = leftBound(mode - k); 61 | int r = rightBound(mode + k); 62 | 63 | int tempAns; 64 | if (numCount.count(mode)) { 65 | tempAns = min(r - l + 1, numCount[mode] + numOperations); 66 | } else { 67 | tempAns = min(r - l + 1, numOperations); 68 | } 69 | ans = max(ans, tempAns); 70 | } 71 | 72 | return ans; 73 | } 74 | }; -------------------------------------------------------------------------------- /2127. Maximum Employees to Be Invited to a Meeting: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumInvitations(vector& favorite) { 4 | int n = favorite.size(); 5 | vector> reversedGraph(n); 6 | for (int person = 0; person < n; ++person) { 7 | reversedGraph[favorite[person]].push_back(person); 8 | } 9 | 10 | auto bfs = [&](int startNode, unordered_set& visitedNodes) -> int { 11 | queue> q; 12 | q.push({startNode, 0}); 13 | int maxDistance = 0; 14 | while (!q.empty()) { 15 | auto [currentNode, currentDistance] = q.front(); 16 | q.pop(); 17 | for (int neighbor : reversedGraph[currentNode]) { 18 | if (visitedNodes.count(neighbor)) continue; 19 | visitedNodes.insert(neighbor); 20 | q.push({neighbor, currentDistance + 1}); 21 | maxDistance = max(maxDistance, currentDistance + 1); 22 | } 23 | } 24 | return maxDistance; 25 | }; 26 | 27 | int longestCycle = 0, twoCycleInvitations = 0; 28 | vector visited(n, false); 29 | 30 | for (int person = 0; person < n; ++person) { 31 | if (!visited[person]) { 32 | unordered_map visitedPersons; 33 | int current = person; 34 | int distance = 0; 35 | while (true) { 36 | if (visited[current]) break; 37 | visited[current] = true; 38 | visitedPersons[current] = distance++; 39 | int nextPerson = favorite[current]; 40 | if (visitedPersons.count(nextPerson)) { 41 | int cycleLength = distance - visitedPersons[nextPerson]; 42 | longestCycle = max(longestCycle, cycleLength); 43 | if (cycleLength == 2) { 44 | unordered_set visitedNodes = {current, 45 | nextPerson}; 46 | twoCycleInvitations += 47 | 2 + bfs(nextPerson, visitedNodes) + 48 | bfs(current, visitedNodes); 49 | } 50 | break; 51 | } 52 | current = nextPerson; 53 | } 54 | } 55 | } 56 | 57 | return max(longestCycle, twoCycleInvitations); 58 | } 59 | }; -------------------------------------------------------------------------------- /3432-count-partitions-with-even-sum-difference/README.md: -------------------------------------------------------------------------------- 1 |

3704. Count Partitions with Even Sum Difference

Easy


You are given an integer array nums of length n.

2 | 3 |

A partition is defined as an index i where 0 <= i < n - 1, splitting the array into two non-empty subarrays such that:

4 | 5 |
    6 |
  • Left subarray contains indices [0, i].
  • 7 |
  • Right subarray contains indices [i + 1, n - 1].
  • 8 |
9 | 10 |

Return the number of partitions where the difference between the sum of the left and right subarrays is even.

11 | 12 |

 

13 |

Example 1:

14 | 15 |
16 |

Input: nums = [10,10,3,7,6]

17 | 18 |

Output: 4

19 | 20 |

Explanation:

21 | 22 |

The 4 partitions are:

23 | 24 |
    25 |
  • [10], [10, 3, 7, 6] with a sum difference of 10 - 26 = -16, which is even.
  • 26 |
  • [10, 10], [3, 7, 6] with a sum difference of 20 - 16 = 4, which is even.
  • 27 |
  • [10, 10, 3], [7, 6] with a sum difference of 23 - 13 = 10, which is even.
  • 28 |
  • [10, 10, 3, 7], [6] with a sum difference of 30 - 6 = 24, which is even.
  • 29 |
30 |
31 | 32 |

Example 2:

33 | 34 |
35 |

Input: nums = [1,2,2]

36 | 37 |

Output: 0

38 | 39 |

Explanation:

40 | 41 |

No partition results in an even sum difference.

42 |
43 | 44 |

Example 3:

45 | 46 |
47 |

Input: nums = [2,4,6,8]

48 | 49 |

Output: 3

50 | 51 |

Explanation:

52 | 53 |

All partitions result in an even sum difference.

54 |
55 | 56 |

 

57 |

Constraints:

58 | 59 |
    60 |
  • 2 <= n == nums.length <= 100
  • 61 |
  • 1 <= nums[i] <= 100
  • 62 |
63 | -------------------------------------------------------------------------------- /3539. Find Sum of Array Product of Magical Sequences: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long quickmul(long long x, long long y, long long mod) { 4 | long long res = 1, cur = x % mod; 5 | while (y) { 6 | if (y & 1) { 7 | res = res * cur % mod; 8 | } 9 | y >>= 1; 10 | cur = cur * cur % mod; 11 | } 12 | return res; 13 | }; 14 | 15 | int magicalSum(int m, int k, vector& nums) { 16 | int n = nums.size(); 17 | const long long mod = 1e9 + 7; 18 | vector fac(m + 1, 1); 19 | for (int i = 1; i <= m; i++) { 20 | fac[i] = fac[i - 1] * i % mod; 21 | } 22 | vector ifac(m + 1, 1); 23 | for (int i = 2; i <= m; i++) { 24 | ifac[i] = quickmul(i, mod - 2, mod); 25 | } 26 | for (int i = 2; i <= m; i++) { 27 | ifac[i] = ifac[i - 1] * ifac[i] % mod; 28 | } 29 | vector numsPower(n, vector(m + 1, 1)); 30 | for (int i = 0; i < n; i++) { 31 | for (int j = 1; j <= m; j++) { 32 | numsPower[i][j] = numsPower[i][j - 1] * nums[i] % mod; 33 | } 34 | } 35 | 36 | vector f(n, 37 | vector(m + 1, vector(m * 2 + 1, vector(k + 1, 0)))); 38 | for (int j = 0; j <= m; j++) { 39 | f[0][j][j][0] = numsPower[0][j] * ifac[j] % mod; 40 | } 41 | for (int i = 0; i + 1 < n; i++) { 42 | for (int j = 0; j <= m; j++) { 43 | for (int p = 0; p <= m * 2; p++) { 44 | for (int q = 0; q <= k; q++) { 45 | int q2 = p % 2 + q; 46 | if (q2 > k) { 47 | break; 48 | } 49 | for (int r = 0; r + j <= m; r++) { 50 | int p2 = p / 2 + r; 51 | f[i + 1][j + r][p2][q2] += f[i][j][p][q] * 52 | numsPower[i + 1][r] % 53 | mod * ifac[r] % mod; 54 | f[i + 1][j + r][p2][q2] %= mod; 55 | } 56 | } 57 | } 58 | } 59 | } 60 | long long res = 0; 61 | for (int p = 0; p <= m * 2; p++) { 62 | for (int q = 0; q <= k; q++) { 63 | if (__builtin_popcount(p) + q == k) { 64 | res = (res + f[n - 1][m][p][q] * fac[m] % mod) % mod; 65 | } 66 | } 67 | } 68 | return res; 69 | } 70 | }; -------------------------------------------------------------------------------- /2211-count-collisions-on-a-road/README.md: -------------------------------------------------------------------------------- 1 |

2317. Count Collisions on a Road

Medium


There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point.

2 | 3 |

You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.

4 | 5 |

The number of collisions can be calculated as follows:

6 | 7 |
    8 |
  • When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.
  • 9 |
  • When a moving car collides with a stationary car, the number of collisions increases by 1.
  • 10 |
11 | 12 |

After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.

13 | 14 |

Return the total number of collisions that will happen on the road.

15 | 16 |

 

17 |

Example 1:

18 | 19 |
20 | Input: directions = "RLRSLL"
21 | Output: 5
22 | Explanation:
23 | The collisions that will happen on the road are:
24 | - Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.
25 | - Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.
26 | - Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.
27 | - Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.
28 | Thus, the total number of collisions that will happen on the road is 5. 
29 | 
30 | 31 |

Example 2:

32 | 33 |
34 | Input: directions = "LLRR"
35 | Output: 0
36 | Explanation:
37 | No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.
38 | 39 |

 

40 |

Constraints:

41 | 42 |
    43 |
  • 1 <= directions.length <= 105
  • 44 |
  • directions[i] is either 'L', 'R', or 'S'.
  • 45 |
46 | --------------------------------------------------------------------------------