Posts

Showing posts from September, 2022

590. N-ary Tree Postorder Traversal

Question Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [5,6,3,2,4,1] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] Solution class Solution { public: vector v; vector postorder(Node* root) { if(root==NULL) return v; for(int i=0;i children.size();i++){ postorder(root->children[i]); } v.push_back(root->val); return v; } };

2000. Reverse Prefix of Word

Question Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". Return the resulting string. Example 1: Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation: The first occurrence of "d" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". Example 2: Input: word = "xyxzxe", ch = "z" Output: "zxyxxe" Explanation: The first and only occurrence of "z" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". Solution class Solution ...

2089. Find Target Indices After Sorting Array

Question You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. Example 1: Input: nums = [1,2,5,2,3], target = 2 Output: [1,2] Explanation: After sorting, nums is [1,2,2,3,5]. The indices where nums[i] == 2 are 1 and 2. Example 2: Input: nums = [1,2,5,2,3], target = 3 Output: [3] Explanation: After sorting, nums is [1,2,2,3,5]. The index where nums[i] == 3 is 3. Solution class Solution { public: vector targetIndices(vector & nums, int target) { vector v; sort(nums.begin(),nums.end()); for(int i=0;i

658. Find K Closest Elements

Question Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| findClosestElements(vector & arr, int k, int x) { vector result; for(auto itr=arr.begin();itr!=arr.end();itr++) *itr-=x; sort(arr.begin(),arr.end(),[](int a, int b){return (a==-1*b && a

1337. The K Weakest Rows in a Matrix

Question You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i is weaker than a row j if one of the following is true: The number of soldiers in row i is less than the number of soldiers in row j. Both rows have the same number of soldiers and i kWeakestRows(vector >& mat, int k) { vector v; map m; int x=0; for(int i=0;i m[j]){ min = m[j]; d=j; } } v.push_back(d); m[d]=INT_MAX; } return v; } };

**1237. Find Positive Integer Solution for a Given Equation

Question Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: f(x, y) f(1, 4) = 1 + 4 = 5. x=2, y=3 -> f(2, 3) = 2 + 3 = 5. x=3, y=2 -> f(3, 2) = 3 + 2 = 5. x=4, y=1 -> f(4, 1) = 4 + 1 = 5. Example 2: Input: function_id = 2, z = 5 Output: [[1,5],[5,1]] Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y. The following positive integer values of x and y make f(x, y) equal to 5: x=1, y=5 -> f(1, 5) = 1 * 5 = 5. x=5, y=1 -> f(5, 1) = 5 * 1 = 5. Solution class Solution { public: vector > findSolution(CustomFunction& customfunction, int z) { vector > ans; int j = 1000; for(int i=1; i 1 && customfunction.f(i, j) > z) j--; if(customfunction.f(i, j) == z) ans.push...

1385. Find the Distance Value Between Two Arrays

Quesition Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| d=2 |4-9|=5 > d=2 |4-1|=3 > d=2 |4-8|=4 > d=2 For arr1[1]=5 we have: |5-10|=5 > d=2 |5-9|=4 > d=2 |5-1|=4 > d=2 |5-8|=3 > d=2 For arr1[2]=8 we have: |8-10|=2 d=2 |8-8|=0 & arr1, vector & arr2, int d) { int value = 0; int n = arr1.size(), m = arr2.size(); for(int i = 0; i

2413. Smallest Even Multiple

Question Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n. Example 1: Input: n = 5 Output: 10 Explanation: The smallest multiple of both 5 and 2 is 10. Example 2: Input: n = 6 Output: 6 Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself. Solution class Solution { public: int smallestEvenMultiple(int n) { if(n%2==0) return n; return 2*n; } }; // 100 Faster

771. Jewels and Stones

Question You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1: Input: jewels = "aA", stones = "aAAbbbb" Output: 3 Example 2: Input: jewels = "z", stones = "ZZ" Output: 0 Solution class Solution { public: int numJewelsInStones(string jewels, string stones) { int d=0; for(int i=0;i

1431. Kids With the Greatest Number of Candies

Question There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. Note that multiple kids can have the greatest number of candies. Example 1: Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true] Explanation: If you give all extraCandies to: - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. - Kid 5, they will have 3 ...

1476. Subrectangle Queries

Question Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2). 2. getValue(int row, int col) Returns the current value of the coordinate (row,col) from the rectangle. Example 1: Input ["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"] [[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]] Output [null,1,null,5,5,null,10,5] Explanation SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); // The initial rectangle (4x3) looks like: // 1 2 1 // 4...

1678. Goal Parser Interpretation

Question You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. Given the string command, return the Goal Parser's interpretation of command. Example 1: Input: command = "G()(al)" Output: "Goal" Explanation: The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal". Example 2: Input: command = "G()()()()(al)" Output: "Gooooal" Example 3: Input: command = "(al)G(al)()()G" Output: "alGalooG" Solution class Solution { public: string check(string x){ if(x=="G") re...

455. Assign Cookies

Question Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children,...

561. Array Partition

Question Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum. Example 1: Input: nums = [1,4,3,2] Output: 4 Explanation: All possible pairings (ignoring the ordering of elements) are: 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 So the maximum possible sum is 4. Example 2: Input: nums = [6,2,6,5,1,2] Output: 9 Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. Solution class Solution { public: int arrayPairSum(vector & nums) { sort(nums.begin(),nums.end()); int d=0; for(int i=0;i

1365. How Many Numbers Are Smaller Than the Current Number

Question Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] smallerNumbersThanCurrent(vector & nums) { vector v; for(int i=0;i nums[j]) x++; } v.push_back(x); } return v; } };

1859. Sorting the Sentence

Question A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3". Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence. Example 1: Input: s = "is2 sentence4 This1 a3" Output: "This is a sentence" Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers. Example 2: Input: s = "Myself2 Me1 I4 and3" Output: "Me Myself and I" Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers. Soluti...

2396. Strictly Palindromic Number

Question An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic. Given an integer n, return true if n is strictly palindromic and false otherwise. A string is palindromic if it reads the same forward and backward. Example 1: Input: n = 9 Output: false Explanation: In base 2: 9 = 1001 (base 2), which is palindromic. In base 3: 9 = 100 (base 3), which is not palindromic. Therefore, 9 is not strictly palindromic so we return false. Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic. Example 2: Input: n = 4 Output: false Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic. Therefore, we return false. Solution class Solution { public: bool pal(string d){ for(int i=0;i

2161. Partition Array According to Given Pivot

Question You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i pivot and nums[j] > pivot, then pi pivotArray(vector & nums, int pivot) { vector s; vector l; int d=0; for(int i=0;i

557. Reverse Words in a String III

Question Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Example 2: Input: s = "God Ding" Output: "doG gniD" Solution class Solution { public: string rev(string s){ string x=""; for(int i=0;i

1877. Minimize Maximum Pair Sum in Array

Question The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Each element of nums is in exactly one pair, and The maximum pair sum is minimized. Return the minimized maximum pair sum after optimally pairing up the elements. Example 1: Input: nums = [3,5,2,3] Output: 7 Explanation: The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. Example 2: Input: nums = [3,5,4,2,4,6] Output: 8 Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. Solution class Solution { public: int minPairSum(vector & nums) { sort(nums.begin(), nums.end()); ...

2108. Find First Palindromic String in the Array

Question Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward. Example 1: Input: words = ["abc","car","ada","racecar","cool"] Output: "ada" Explanation: The first string that is palindromic is "ada". Note that "racecar" is also palindromic, but it is not the first. Example 2: Input: words = ["notapalindrome","racecar"] Output: "racecar" Explanation: The first and only string that is palindromic is "racecar". Example 3: Input: words = ["def","ghi"] Output: "" Explanation: There are no palindromic strings, so the empty string is returned. Solution class Solution { public: bool pal(string d){ for(int i=0;i & words) { for(int i=0;i

Array Subset of another array

Question Given two arrays: a1[0..n-1] of size n and a2[0..m-1] of size m. Task is to check whether a2[] is a subset of a1[] or not. Both the arrays can be sorted or unsorted. Example 1: Input: a1[] = {11, 1, 13, 21, 3, 7} a2[] = {11, 3, 7, 1} Output: Yes Explanation: a2[] is a subset of a1[] Example 2: Input: a1[] = {1, 2, 3, 4, 5, 6} a2[] = {1, 2, 4} Output: Yes Explanation: a2[] is a subset of a1[] Solution string isSubset(int a1[], int a2[], int n, int m) { map a; map b; int d=INT_MIN; for(int i=0;i a[i]) return "No"; } return "Yes"; }

113. Path Sum II

Question Given the root of a binary tree and an integer targetSum, it returns all paths from the root to a leaf where the sum of the values ​​of the nodes in the path equals targetSum. Each path should be returned as a list of node values, not as node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum is equal to targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 Example 2: Input: root = [1,2,3], target sum = 5 Output: [] Example 3: Input: root = [1,2], targetSum = 0 Output: [] Solution class Solution { public: vector > ans; vector path; void dfs(TreeNode* root, int current, int target) { if(!root) { return; } current += root->val; path.push_back(root->val); ...

389. Find the Difference

Question You are given two strings s and t. The string t is generated by randomly shuffling the strings s and then adding another letter at a random location. Return the letter that was added to t. Example 1: Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added. Example 2: Input: s = "", t = "y" Output: "y" Solution class Solution { public: char findTheDifference(string s, string t) { int a[26]={0},b[26]={0}; for(int i=0;i

414. Third Maximum Number

Question Given an integer array of nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum count. Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. Example 2: Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. There is no third distinct maximum, so maximum (2) is returned instead. Example 3: Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together because they have the same value). The third distinct maximum is 1. Solution class Solution { public: int thirdMax(vector & nums) { sort(nums.begin(),nums.end(),greater ()); if(nums.size()

148. Sort List

Question Given a linked list header, return the sorted list in ascending order. Example 1: Input: head = [4,2,1,3] Output: [1,2,3,4] Example 2: Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] Example 3: Input: head = [] Output: [] Solution /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { vector v; while(head){ v.push_back(head->val); head=head->next; } sort(v.begin(),v.end()); ListNode*l = new ListNode(-1); ListNode*x=l; for(int i=0;i next = new ListNode(v[i]); l=l->next; } return x->next; } };

160. Intersection of Two Linked Lists

Question Given the heads of two separately linked lists headA and headB , return the node at which the two lists intersect. If the two linked lists do not intersect at all, return null. For example, the following two linked lists begin to intersect at node c1: Test cases are generated in such a way that there are no loops anywhere in the entire linked structure. Note that linked lists must retain their original structure when the function returns. Own referee: The inputs for the referee are as follows (your program will not receive these inputs): intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersecting node. listA - The first linked list. listB - Second linked list. skipA - The number of nodes to skip forward in list A (starting from the beginning) to reach the intersected node. skipB - The number of nodes to skip forward in list B (starting from the beginning) to reach the intersecting node. The arbiter then...

141. Linked List Cycle

Question The given head, the linked list head, determines whether the linked list has a cycle. A loop exists in a linked list if there is any node in the list that can be reached again by continuously tracking the next pointer. Internally, pos is used to indicate the index of the node to which the next tail pointer is attached. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a loop in the linked list where the end connects to the 1st node (index 0). Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a loop in the linked list where the end connects to the 0th node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Solution class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL||head->next==NULL) return false; ...

1680. Concatenation of Consecutive Binary Numbers

Question Given an integer n, returns the decimal value of the binary string formed by concatenating the binary representations 1 through n in order, modulo 109 + 7. Example 1: Input: n = 1 Output: 1 Explanation: "1" in binary format corresponds to a decimal value of 1. Example 2: Input: n = 3 Output: 27 Explanation: In binary, 1, 2 and 3 correspond to "1", "10" and "11". After concatenating them, we have "11011", which corresponds to the decimal value of 27. Example 3: Input: n = 12 Output: 505379714 Explanation: The result of the concatenation is "1101110010111011110001001101010111100". The decimal value is 118505380540. After modulo 109 + 7, the result is 505379714. Solution class Solution { public: int concatenatedBinary(int n) { long ans = 0, mod = 1e9+7, length = 0; for (int i = 1; i

136. Single Number

Given a non-empty array of integers num, each element appears twice except one. Find the one and only. You need to implement a solution with linear complexity at runtime and use only constant extra space. Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Output: 4 Example 3: Input: nums = [1] Output: 1 Limitations: 1 & nums) { unordered_map a; for(auto x: nums) a[x]++; for(auto z:a) if(z.second==1) return z.first; return -1; } };

125. Valid Palindrome

A phrase is a palindrome if it reads the same forwards and backwards after converting all uppercase letters to lowercase and removing all non-alphanumeric characters. Alphanumeric characters include letters and numbers. If the string s is given, returns true if it is a palindrome, or false otherwise. Example 1: Input: s = "Man, Plan, Channel: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "car race" Output: false Explanation: "raceacar" is not a palindrome. Example 3: Input: s = " " Output: true Explanation: s is the empty string "" after removing non-alphanumeric characters. Since the empty string reads forwards and backwards the same way, it is a palindrome. Limitations: 1

121. Best Time to Buy and Sell Stock

You get an array of prices where prices[i] is the price of the given stock on that day. You want to maximize your profit by choosing a single day to buy one stock and choose another day in the future to sell that stock. Return the maximum profit you can make from this transaction. If you can't make any profit, return 0. Example 1: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed as you must buy before selling. Example 2: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no trades are made and maximum profit = 0. Limitations: 1 & prices) { int n = prices.size(); int maxi =0,mini = INT_MAX; for(int i=0; i

557. Reverse Words in a String III

Given the string s, it reverses the order of characters in each word in the sentence while preserving spaces and initial word order. Example 1: Input: s = "Let's take the LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Example 2: Input: s = "God Ding" Output: "dog gniD" Limitations: 1

119. Pascal's Triangle II

Given an integer rowIndex, returns the rowIndexth (indexed 0) row of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it, as shown: Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Output: [1,1] 0 getRow(int rowIndex) { vector > ans; ans.push_back({1}); for(int i = 1 ; i level(i); level[0] = 1; ans.push_back(level); for(int j = 1; j

985. Sum of Even Numbers After Queries

985. Even sum after query means Get integer array nums and array query. where queries[i] = [vali, indexi]. For each query i, first apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values ​​of nums. Returns an integer array response. response[i] is the response for the ith query. Example 1: Input: number = [1,2,3,4], query = [[1,0], [-3,1], [-4,0], [2,3 ] ]] Output: [8,6,2,4] Description: The first array is [1,2,3,4]. If you add 1 to nums[0] , the array becomes [2,2,3,4] and the sum of the even values ​​is 2 + 2 + 4 = 8. After adding -3 to nums[1] the array is [2,-1,3,4] and the sum of the even numbers is 2 + 4 = 6. Adding -4 to nums[0] gives an array of [-2,- 1, 3, 4]. ], and the sum of the even values ​​is -2 + 4 = 2. is -2 + 6 = 4. Example 2: Input: Number = [1], Query = [[4,0]] Output: [0] Constraint: 1 sumEvenAfterQueries(vector & nums, vector >& queries) { int sum = 0, N = queries.size(); for (int n : nums) { ...

118. Pascal's Triangle

Given the root of a binary tree and an integer targetSum, returns true if the tree has a path from root to leaf such that the addition of all values ​​along the path equals targetSum. A leaf is a node that has no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Description : Shows the path from the root to the leaf containing the goal sum. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Description: The tree has two root-to-leaf paths: (1 --> 2 ) : the sum is 3. (1 --> 3): Total is 4. There is no path from root to leaf with sum = 5. Example 3: Input: root = [], targetSum = 0 Output: false Description: There is no root because the tree is empty - the path to the sheet. Limits: The number of nodes in the tree is in the range [0, 5000]. -1000 > generate(int n) { vector > ans; vector v; v.push_back(1); ans.push_back(v); int s=2; n--; while(n--) { vector t(s); t[0]=v[0]; t[s-1]=v[v.size()-1]; ...

112. Path Sum

Given the root of a binary tree and an integer targetSum, returns true if the tree has a path from root to leaf such that the addition of all values ​​along the path equals targetSum. A leaf is a node that has no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Description : Shows the path from the root to the leaf containing the goal sum. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Description: The tree has two root-to-leaf paths: (1 --> 2 ) : the sum is 3. (1 --> 3): Total is 4. There is no path from root to leaf with sum = 5. Example 3: Input: root = [], targetSum = 0 Output: false Description: There is no root because the tree is empty - the path to the sheet. Limits: The number of nodes in the tree is in the range [0, 5000]. -1000 val==targetSum && !root->left && !root->right) return true; return hasPathSum(root->left, targetSum-root->val) ...

111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth. Minimum depth is the number of nodes on the shortest path from the root node to the next leaf node. Note: A leaf is a node that has no children. Example 1: Input: Root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: Root = [2,null,3, null,4,null,5,null,6] Output: 5 Limits: The range of nodes in the tree is [0, 105]. -1000 left == NULL && root->right ==NULL){ return 1; } int l = solve(root->left); int r = solve(root->right); if(l!=0 && r!=0){ return 1+min(l,r); } else if(l==0){ return 1+r; } else if(r==0){ return 1+l; } // return 1+min(l,r); return -1; } int minDepth(TreeNode* root) { return solve(root); } };

110. Balanced Binary Tree

Determines if the given binary tree is height balanced. For this problem, a height-balanced binary tree is defined as follows. Example 1: Input: root = [3,9,20,null,null,15,7] Output: true Example 2: Input: root = [1,2,2, 3,3,null,null,4, 4] Output: false Example 3: Input: root = [] Output: true Limit: The number of nodes in the tree is in the range [ 0, 5000]. -104 1){ ans = false; } int height =Math.max(lh,rh)+1; return height; } public boolean isBalanced(TreeNode root) { heightOfTree(root); return ans; } }

108. Convert Sorted Array to Binary Search Tree

Converts the given integer array nums , whose elements are sorted in ascending order, to a height-adjusted binary search tree. A height-balanced binary tree is a binary tree in which the depths of the two subtrees at each node do not differ by more than one. Example 1: Input: Number = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Description: [0, -10,5,null,-3,null,9] is also accepted: Example 2: Input: nums = [1,3] Output: [3,1] Description: [1,null , 3] and [3,1] are both height-corrected BST. Constraints: 1 &v) { if(s>e) { return NULL; } int mid=s+(e-s)/2; TreeNode*root=new TreeNode(v[mid]); root->left=helper(s,mid-1,v); root->right=helper(mid+1,e,v); return root; } public: TreeNode* sortedArrayToBST(vector & nums) { int s=0; int e=nums.size()-1; TreeNode*root=NULL; root=helper(s,e,nums); return root; } };

75. Sort Colors

 class Solution { public:     void sortColors(vector<int>& nums) {         int s=0,e=nums.size()-1;         while(s<=e){             if(nums[s]!=0 && nums[e]==0){                 swap(nums[s],nums[e]);                 s++;                 e--;             }             else if(nums[s]==0)                 s++;             else if(nums[e]!=0)                 e--;         }                  e=nums.size()-1;                  while(s<=e){             if(nums[s]!=...

73. Set Matrix Zeroes

 class Solution { public:          void setZeroes(vector<vector<int>>& matrix) {                  map<int,int>r,c;                  for(int i=0;i<matrix.size();i++){             for(int j=0; j<matrix[i].size();j++){                 if(matrix[i][j]==0){                     r[i]=1;                     c[j]=1;                 }             }         }                  for(int i=0;i<matrix.size();i++){             for(int j=0; j<matrix[i].size();j++){                 if(r...

104. Maximum Depth of Binary Tree

  int maxDepth (TreeNode* root) { if (!root) return 0 ; int maxLeft = maxDepth(root->left); int maxRight = maxDepth(root->right); return max(maxLeft, maxRight)+ 1 ; }

69. Sqrt(x)

  class Solution { public : int mySqrt ( int x) { long r = x; while (r*r > x) r = (r + x/r) / 2 ; return r; } }

Majority Element

Brute Force | Using Map | 100% Success int Solution::majorityElement( const vector< int > &A) {     map< int , int >m;     for ( int i= 0 ;i<A.size();i++){         m[A[i]]++;     }     for ( int i= 0 ;i<A.size();i++){         if (m[A[i]]>A.size()/ 2 )         return A[i];     }     return - 1 ; }

67. Add Binary

Add Binary   (C++) class Solution { public : string addBinary ( string a, string b ) { string ans= "" ; int carry= 0 ; while (a.size()||b.size()) { int x= 0 ,y= 0 ; if (a.size()){ x=a.back()- '0' ; a.pop_back(); } if (b.size()){ x+=b.back()- '0' ; b.pop_back(); } x+=carry; if (x== 1 ){ans+= '1' ;carry= 0 ;} if (x== 0 )ans+= '0' ; if (x== 2 ){ans+= '0' ;carry= 1 ;} if (x== 3 ){ans+= '1' ;carry= 1 ;} } if (carry)ans+= '1' ; reverse(ans.begin(),ans.end()); return ans; } };

2007. Find Original Array From Doubled Array

class Solution { public:     vector<int> findOriginalArray(vector<int>& changed) {         int n = changed.size();         if (n % 2 == 1) return {};         sort(changed.begin(), changed.end());         vector<int> ans;         map<int, int> mp;         for (int i = 0; i < n; i++) {             mp[changed[i]]++;         }         for (int i = 0; i < n; i++) {           if (mp[changed[i]] == 0) continue;           if (mp[changed[i] * 2] == 0) return {};           ans.push_back(changed[i]);           mp[changed[i]]--;           mp[changed[i] * 2]--;         }         return ans;     } }...

66. Plus One

 class Solution { public: vector<int> plusOne(vector<int>& digits) { int n=digits.size(); int carry=0; if(digits[n-1]+1==10){ digits[n-1]=0; carry++; for(int i=n-2;i>=0;i--){ int num=digits[i]+carry; carry=0; if(num==10){ digits[i]=0; carry=carry+1; } else digits[i]=num; } if(carry==1){ digits.push_back(carry); int i=0; int num1=digits.size(); int temp=digits[i]; digits[i]=digits[num1-1]; digits[num1-1]=temp; } } else{ digits[n-1]=digits[n-1]+1; } return digits; } };

58. Length of Last Word

 class Solution { public: int lengthOfLastWord(string s) {     int i = s.size( )-1;     int idx=i; // find the position of the first non-space character from the // last of the string... while(s[i]==' '){ i--; }     idx =i;          int len =0;          for(int k=idx;k>=0;k--){         if(s[k]!=' ')             len++;                  else             break;     }          return len;         } };

70. Climbing Stairs

 class Solution { public:          int rec(int num, int arr[])     {         if(arr[num])             return arr[num];         return (arr[num]=rec(num-1,arr)+rec(num-2,arr));     }     int climbStairs(int n) {         int arr[46]={0};         arr[0]=arr[1]=1;         int num=rec(n,arr);                  return num;     } };

1457. Pseudo-Palindromic Paths in a Binary Tree

class Solution{ public:   int pseudoPalindromicPaths(TreeNode *root, int count = 0){     // dfs way to find the number of pseudo palindromic paths     if (!root)       return 0;     count ^= 1 << root->val;     int res = pseudoPalindromicPaths(root->left, count) + pseudoPalindromicPaths(root->right, count);     if (!root->left && !root->right && (count & (count - 1)) == 0)       res++;     return res;   } };

441. Arranging Coins

  class Solution { public : int arrangeCoins ( int n) { int i = 0 ; for ( ; n-i>= 0 ; i++ ) n=n-i; return i -1 ; } };

287. Find the Duplicate Number

 class Solution { public:     int findDuplicate(vector<int>& nums) {         map<int,int>m;         for(int i=0;i<nums.size();i++){             if(m[nums[i]]>=1)                 return nums[i];             else {                 m[nums[i]]++;             }         }         return -1;     } };

70. Climbing Stairs

  class Solution { public : int rec ( int num, int arr[]) { if (arr[num]) return arr[num]; return (arr[num]=rec(num -1 ,arr)+rec(num -2 ,arr)); } int climbStairs ( int n) { int arr[ 46 ]={ 0 }; arr[ 0 ]=arr[ 1 ]= 1 ; int num=rec(n,arr); return num; } };

83. Remove Duplicates from Sorted List

 class Solution { public:     ListNode* deleteDuplicates(ListNode* head) {         if(head==NULL||head->next==NULL) return head;         ListNode* newHead=deleteDuplicates(head->next);         if(head->val==newHead->val) return newHead;         else{             head->next=newHead;         }         return head;     } };

100. Same Tree

 class Solution { public:     bool inorder(TreeNode* p,TreeNode* q)     {         bool x,y,z;         if(p->left && q->left)             x=inorder(p->left,q->left);         else if(!p->left && !q->left)             x=true;         else             return false;         y=(p->val==q->val);         if(p->right && q->right)             z=inorder(p->right,q->right);         else if(!p->right && !q->right)             z=true;         else             return false;         return (x && y && z);     }     bo...

35. Search Insert Position

 class Solution { public:     int searchInsert(vector<int>& nums, int target) {     int s=0,e=nums.size()-1;     while(s<e){         int  mid=s + (e-s)/2;         if(nums[mid]>=target)             e=mid;         else             s=mid+1;     }     return nums[s]>=target?s:s+1; } };

27. Remove Element

 class Solution { public:     int removeElement(vector<int>& nums, int val) {         int current = 0;         for (int i = 0; i < nums.size(); i++)         {             if (nums[i] != val){                 nums[current] = nums[i];                 current++;             }         }         return current;     } };

1351. Count Negative Numbers in a Sorted Matrix

 class Solution { public:     int countNegatives(vector<vector<int>>& grid) {         int d=0;         for(int i=0;i<grid.size();i++){             for(int j=0;j<grid[i].size();j++){                 if(grid[i][j]<0)                     d++;             }         }         return d;     } };

26. Remove Duplicates from Sorted Array

class Solution { public:     int removeDuplicates(vector<int>& nums) {         map<int,int>m;         vector<int>v;                  for(int i=0;i<nums.size();i++){             m[nums[i]]++;             if(m[nums[i]]>1){                 continue;             }             v.push_back(nums[i]);         }         nums=v;         return v.size();     } };

1383. Maximum Performance of a Team

class Solution{ public:     const int mod = (int)1e9 + 7;     int maxPerformance(int n, vector<int> &speed, vector<int> &efficiency, int k){       priority_queue<int, vector<int>, greater<int>> pq;       vector<pair<int, int>> v;       for (int i = 0; i < n; i++){         v.push_back({efficiency[i], speed[i]});       }       sort(v.rbegin(), v.rend());        long totSpeed = 0, ans = 0;       for (int i = 0; i < n; i++) {         int currEff = v[i].first;         int currSpeed = v[i].second;         if (pq.size() == k) {           totSpeed -= pq.top();           pq.pop();         }         pq.push(currSpeed);        ...

21. Merge Two Sorted Lists

  class Solution { public : ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { if (list1 == NULL ) return list2; if (list2 == NULL ) return list1; ListNode* dummy = new ListNode(); ListNode* temp = dummy; while (list1 && list2) { if (list1->val < list2->val) { temp->next = list1; list1 = list1->next; } else { temp->next = list2; list2 = list2->next; } temp = temp->next; } if (list1) temp->next = list1; if (list2) temp->next = list2; return dummy->next; } };

14. Longest Common Prefix

 # include <bits/stdc++.h> class Solution { public : string longestCommonPrefix ( vector < string >& strs) { string ans= "" ; string first = strs[ 0 ]; for ( int i= 0 ; i<strs[ 0 ].size(); i++){ for ( int j= 1 ; j<strs.size(); j++){ string temp = strs[j]; if (temp[i] == first[i]){ continue ; } else { return ans; } } ans+=first[i]; } return ans; } };

13. Roman to Integer

C++ | Hash class Solution { public:     int romanToInt(string s) { unordered_map<char,int> mp; mp['I']=1; mp['V']=5; mp['X']=10; mp['L']=50; mp['C']=100; mp['D']=500; mp['M']=1000;     int sum=0;     for(int i=0;i<s.length()-1;i++){         if(mp[s[i]]>=mp[s[i+1]]){             sum+=mp[s[i]];         }         else{             sum-=mp[s[i]];         }     }     sum+=mp[s[s.length()-1]];     return sum; } };

8. String to Integer (atoi)

C++ | 100% Success | Brute Force | Easy Understanding class Solution { public : int myAtoi ( string s) { int sign = 1 ; int i = 0 ; long long int ans = 0 ; while (s[i]== ' ' )i++; if (s[i]== '-' ){ sign = -1 ; i++; } else if (s[i]== '+' ) i++; int u = INT_MAX; int l = INT_MIN; int j = i; while (s[j]>= '0' && s[j]<= '9' ){ if (s[j]== ' ' ) continue ; ans += s[j] - '0' ; if (sign*ans<=l) return l; else if (sign*ans>=u) return u; ans = ans * 10 ; j++; } ans = ans / 10 ; ans = ans*sign; return ( int )ans; } };

7. Reverse Integer

C++ | 100% Success | Brute Force | Easy Understanding class Solution { public : int reverse (int x) { int max = INT_MAX ; int min = INT_MIN ; int result= 0 ; while (x) { int digit=x% 10 ; x=x/ 10 ; if (result> max / 10 ||result== max / 10 && digit> max % 10 ) return {}; if (result< min / 10 ||result== min / 10 && digit< min % 10 ) return {}; result=result* 10 +digit; } return result; } };

188. Best Time to Buy and Sell Stock IV

  class Solution { public : int maxProfit ( int k, vector < int > &prices) { if (k == 0 ) return 0 ; if (prices.size() == 0 || prices.size() == 1 ) return 0 ; vector < vector < int >> dp(k + 1 , vector < int >(prices.size())); for ( int i = 0 ; i < dp.size(); i++) { for ( int j = 0 ; j < dp[i].size(); j++) { if (i == 0 ) dp[i][j] = 0 ; else if (j == 0 ) dp[i][j] = 0 ; else { int x; int mx = INT_MIN; for ( int k = 0 ; k < j; k++) { x = prices[j] - prices[k] + dp[i - 1 ][k]; mx = max(x, mx); } dp[i][j] = max(dp[i][j - 1 ], mx); } } ...

108. Convert Sorted Array to Binary Search Tree

 /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution { public:          TreeNode*BST(int s, int e , vector<int>nums){         if(s>e){             return NULL;         }         int m = s+(e-s)/2;         TreeNode*root = new TreeNode(nums[m]);         root->left = BST(s, m-1 , nums);         root->right = BST(m+1, e , nums);     ...

2236. Root Equals Sum of Children

 /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution { public:     bool checkTree(TreeNode* root) {         if(root->val==root->left->val + root->right->val)             return true;         return false;     } };

101. Symmetric Tree

 C++ | 100% Success | Recursion | Easy Understanding   /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution { public:     bool isSameTree(TreeNode* p, TreeNode* q) {         if(p==NULL && q==NULL)             return true;         if(p==NULL && q!=NULL || (p!=NULL && q==NULL))             return false;                 bool l = isSameTree(p->right,q->l...

100. Same Tree

 C++ | 100% Success | Recursion | Easy Understanding /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution { public:     bool isSameTree(TreeNode* p, TreeNode* q) {         if(p==NULL && q==NULL)             return true;         if(p==NULL && q!=NULL || (p!=NULL && q==NULL))             return false;                  bool l = isSameTree(p->left,q->lef...

4. Median of Two Sorted Arrays

C++ | Easy UnderStanding | Brute Force class Solution { public:     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {         if(nums2.size()<nums1.size()) return findMedianSortedArrays(nums2,nums1);                  int n1=nums1.size();         int n2=nums2.size();         int low=0,high=n1;                  while(low<=high){             int cut1 = (low+high)>>1;             int cut2 = (n1+n2+1)/2-cut1;             int left1 = cut1==0 ? INT_MIN : nums1[cut1-1];             int left2 = cut2==0 ? INT_MIN : nums2[cut2-1];                          int right1 = cut1==n1 ? INT_MAX : nums1[cut1]; ...

20. Valid Parentheses

C++ | Easy Understanding | Brute Force | Easy | 100% Success  class Solution { public:     bool isValid(string s) {         stack<char> st;           for(auto i:s)           {             if(i=='(' or i=='{' or i=='[')                  st.push(i);              else                {                 if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or                        (st.top()=='[' and i!=']'))                  return false;                 st.pop();               }       ...

Sum of nodes on the longest path from root to leaf node

  class Solution { public:          void findsum(Node*root , int sum , int &maxsum , int len , int &maxlen){         if(root==NULL){             if(len>maxlen)             maxlen = len;             else if(len == maxlen)             maxsum  = max(sum,maxsum);             return;         }         sum += root->data;         findsum(root->left,sum,maxsum,len+1,maxlen);         findsum(root->right,sum,maxsum,len+1,maxlen);         return;     }          int sumOfLongRootToLeafPath(Node *root)     {         //code here         int sum=0,maxsum=0,len=0,maxlen=0;        ...

1996. The Number of Weak Characters in the Game

C++ | Simple Explaination | 100% Success class Solution { public : static bool comp ( vector < int > &a, vector < int > &b) { if (a[ 0 ]==b[ 0 ]){ return a[ 1 ]>b[ 1 ]; } return a[ 0 ]<b[ 0 ]; } int numberOfWeakCharacters ( vector < vector < int >>& prop) { sort(prop.begin(),prop.end(),comp); int maxTillNow = INT_MIN; int ans= 0 ; for ( int i=prop.size() -1 ;i>= 0 ;i--){ if (prop[i][ 1 ]<maxTillNow){ ans++; } maxTillNow = max(maxTillNow,prop[i][ 1 ]); } return ans; } };

6. Zigzag Conversion

C++ | Easy Under Standing | Brute Force | Vector  #include <bits/stdc++.h> using namespace std; class Solution { public:     string convert(string s, int numRows)     {         if (numRows == 1)         {             return s;         }         vector<string> rows(min(numRows, int(s.size())));         int curRow = 0;         bool goingDown = false;         for (char c : s)         {             rows[curRow] += c;             if (curRow == 0 || curRow == numRows - 1)             {                 goingDown = !goingDown;             }             curRow += goingDown ? 1 : -1; ...

24. Swap Nodes in Pairs

C++ | 100% Success | Easy Explaination | Linked-List  /**  * Definition for singly-linked list.  * struct ListNode {  *     int val;  *     ListNode *next;  *     ListNode() : val(0), next(nullptr) {}  *     ListNode(int x) : val(x), next(nullptr) {}  *     ListNode(int x, ListNode *next) : val(x), next(next) {}  * };  */ class Solution { public:     ListNode* swapPairs(ListNode* h) {         ListNode*head = h;               int x=0,d;         while(head!=NULL){             if(x%2==0 && head->next){                 d = head->val;                 head->val = head->next->val;                 head->next-...

5. Longest Palindromic Substring

C++ | 100% Success | Simple Approach class Solution { public:     string longestPalindrome(string s) {         int n = s.length();         if(n==1) return s;         string ans = "";         int low, high;         int start_index;         int max_length = 0;         for(int i = 1; i < n; i++)         {             low = i - 1;             high = i + 1;             while(low >= 0 && high < n && s[low] == s[high])             {                 if(max_length < high - low + 1)                 {                     max_length = high - low + 1;   ...