**
**In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different ....

taking the help of depth and parent node of the given two node values....

## class Solution { public: void findDepth(TreeNode* node, int testVal, int origDepth, TreeNode* &parent, int& dept......

**
**Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input : 3 / 9 20 / 15 7

Output : [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Henc....

using two queues ....

## class Solution { public: vector<double> averageOfLevels(TreeNode* root) { vector<double> res; ......

**
**Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.....

simple recursive solution....

## class Solution { public TreeNode trimBST(TreeNode root, int L, int R) { if (root == null) return null; ......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

Map....

## class Solution { public: int distributeCandies(vector<int>& candies) { unordered_map<int,int> mp; ......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input : s = "anagram", t = "nagaram"

Output : true

Example 2:

Input : s = "rat", t = "car"

Output : false Note: You may assume the string contains only lowercase alphabets. Follow up: What if ....

Map....

## class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false; ......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

Map....

## class Solution { public: int sumdigitsquare(int n) { int sq=0; while(n){ int digit= n%10......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Exa....

Map....

## class Solution { public: int longestPalindrome(string s) { int res=0; bool flag=false; map<ch......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2,2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [4,9] Note: Each element in the result should appear as many times as it shows in both arr....

Map....

## class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> v;......

**
**We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input : [1,3,2,2,5,2,3,7] ....

Map....

## class Solution { public: int findLHS(vector<int>& nums) { if(nums.empty()) return 0; int res=0; ......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1....

Map....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map <int,int> mp; vector......

**
**Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers,

iutput all of them with no order r....

Map....

## class Solution { public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { un......

**
**The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this se....

Map....

## class Solution { public: vector<int> findErrorNums(vector<int>& nums) { map<int,int> mp; vector<in......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

Map....

## class Solution { public: int numberOfBoomerangs(vector<pair<int, int>>& points) { int res=0; for(int i......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

Map....

## class Solution { public: int numJewelsInStones(string J, string S) { map<char,int> mp; int res=0; f......

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard like the image below.

Example :

Input : ["Hello", "Alaska", "Dad", "Peace"]

Output : ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once.....

Map....

## class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> result; ......

**
**Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, re....

Map....

## class Solution { public: string longestWord(vector<string>& words) { string res = ""; unordered_map<st......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

Map....

## class Solution { public: bool isHappy(int n) { map <int,int>M; while(n!=1) { int temp=0; ......

**
**Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, re....

Map....

## class Solution { public: string longestWord(vector<string>& words) { int z = words.size(); map< ......

**
** Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.

Example s: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. ....

Store the occurrences of each element in string in a map. Iterate over the string again, and output the character that has frequency 1 . ....

## class Solution { public: int firstUniqChar(string s) { map <char,int> mp; for(char c:s) { ......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [9,4] Note: Each element in the result must be unique. The result can be in any....

Iterate over first array and store the occurrences of each element. While iterating over second array, check if the element is present in the map . If the element is present, add the element to the re....

## class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { map<i......

**
**The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this se....

Map....

## class Solution { public: vector<int> findErrorNums(vector<int>& nums) { vector <int> M; vector......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

Map....

## class Solution { public: int numJewelsInStones(string J, string S) { map <char,int> M; for(char c:S) ......

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard like the image below.

Example :

Input : ["Hello", "Alaska", "Dad", "Peace"]

Output : ["Alaska", "Dad"] Note: You may use one character in the keyboard more than....

Map....

## class Solution { public: vector<string> findWords(vector<string>& words) { vector <string> ans; ma......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

Map....

## class Solution { public: int distributeCandies(vector<int>& candies) { map<int,int> M; for(int val: ca......

**
**We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input : [1,3,2,2,5,2,3,7] ....

Map....

## class Solution { public: int findLHS(vector<int>& nums) { unordered_map <int,int> M; for(int i ......

**
**Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers,

iutput all of them with no order r....

Map....

## class Solution { public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { ma......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Exa....

map....

## class Solution { public: int longestPalindrome(string s) { map <char,int> M; int sum=0,max=0; for(char c......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.

Example s: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters.....

Map....

## class Solution { public: int firstUniqChar(string s) { map<char,int> M; for(char c:s) M[c]+......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2,2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [4,9] Note: Each element in the result should appear as many times as it shows in both arr....

Map....

## class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { map<int,......

**
**

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [9,4] Note: Each element in the result must be unique. The result can be in any order.....

map....

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input : s = "anagram", t = "nagaram"

Output : true

Example 2:

Input : s = "rat", t = "car"

Output : false....

Map....

## class Solution { public: bool isAnagram(string s, string t) { map <char,int> M; if(s.length()!=t.length(......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1....

Map....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; ......

**
**You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.....

DP....

## class Solution { public: int climbStairs(int n) { if(n == 1) return 1; int dp[n]; dp[0] = 1; dp[......

**
**On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.....

DP....

## class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int res = cost.size(); if(res ==......

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

DP ....

## class Solution { public: int rob(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1......

**
**Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example :

Input : [-2,1,-3,4,-1,2,1,-5,4],

Output : 6 Explanation: [4,-1,2,1] has the largest sum = 6.....

.....

## class Solution { public: int maxSubArray(vector<int>& nums) { int gMax=nums[0],lMax=nums[0],len=nums.size(); ......

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

.....

## class Solution { public: int rob(vector<int>& nums) { int len=nums.size(); if(len==1) return nums[......

**
**In LeetCode Store, there are some kinds of items to sell. Each item has a price.
However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given the each item s price, a set of special offers, and the number we need ....

.....

## class Solution { public: int dp[7][7][7][7][7][7]; int A,B,C,D,E,F; vector<int> gCost; int func(vector<......

**
**In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;....

.....

## class Solution { public: int dp[365+3]; int func(int ind,vector<int>& days, vector<int>& cost){ int len=......

**
**Given a square array of integers A, we want the minimum sum of a falling path through A.
A falling path starts at any element in the first row, and chooses one element from each row. The next row s choice must be in a column that is different from the previous row s column by at most one.
....

.....

## class Solution { public: int minFallingPathSum(vector<vector<int>>& A) { int sz=A.size(); int x1,x2,x3......

**
**Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
Alex and Lee ....

.....

## class Solution { public: int dp[501][501]={0}; int func(int i,int j,vector<int> &piles){ if(i>j || i<0......

**
**Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1 s in their binary representation and return them as an array.

Example 1:

Input : 2

Output : [0,1,1]

Example 2:

Input : 5

Output : [0,1,1,2,1,2] Follow up: It is very easy t....

.....

## class Solution { public: vector<int> countBits(int num) { vector<int> ans(num+1,0); for(int i=1;i<=n......

**
**dp....

dp....

## class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; int currSum = 0; ......

**
**dp....

dp....

## class Solution { public int climbStairs(int n) { if(n == 0) return 0; else if(n == 1) r......

**
**Dp....

dp....

## class Solution { public int rob(int[] nums) { int max = 0; if(nums.length == 0) return max; ......

**
**You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.....

DP Problem....

## class Solution { public: int climbStairs(int n) { if (n == 1) return 1; if (n == 2) return 2; int dp[......

**
**Given an array nums, write a function to move all 0 s to the end of it while maintaining the relative order of the non-zero elements.....

arrays....

## class Solution { public: void moveZeroes(vector<int>& nums) { int start=0; int end=0; int i; ......

**
**Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.....

arrays....

## class Solution { public: int missingNumber(vector<int>& nums) { int s=0; for(int i:nums) { ......

**
**Given an array nums of n integers where n > 1, return an array

iutput such that

iutput [i] is equal to the product of all the elements of nums except nums[i].....

arrays....

## class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); ......

**
**Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
....

arrays....

## class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { int dis=0; map<......

**
**Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is d....

arrays....

## class Solution { public: bool containsDuplicate(vector<int>& nums) { map<int,int> m; for(int i=0;......

**
**Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations....

ararys....

## class Solution { public: vector<vector<int>> res; vector<vector<int>> combinationSum3(int k, int n) { in......

**
**Given an array, rotate the array to the right by k steps, where k is non-negative.
....

arrays....

## class Solution { public: void rotate(vector<int>& nums, int k) { int n=nums.size(); int arr[n]; ......

**
**Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2....

arrays....

## class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> v; ......

**
**A peak element is an element that is greater than its neighbors.
Given an

input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-....

arrays....

## class Solution { public: int findPeakElement(vector<int>& nums) { int n=nums.size(); int l=0; ......

**
**Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.....

arrays....

## class Solution { public: int min(vector<int> nums ,int n, int low, int high) { if(high<low) retur......

**
**Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transac....

arrays ....

## class Solution { public: int maxProfit(vector<int>& prices) { int profit=0; for(int i=1;i<prices......

**
**Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements fr....

arrays....

## class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int len=m+n......

**
**Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.....

arrays....

## class Solution { public: int removeDuplicates(vector<int>& nums) { int ind=0; int n=nums.size(); ......

**
**Given a set of distinct integers, nums, return all possible subsets (the power set).....

arrays....

## class Solution { public: vector<vector<int>> res; vector<vector<int>> subsets(vector<int>& nums) { ......

**
**Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not ....

arrays....

## class Solution { public: void swap(vector<int>& nums,int i,int j) { int temp=nums[i]; nums[i]=num......

**
**Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading z....

arrays....

## class Solution { public: vector<int> plusOne(vector<int>& digits) { vector<int> v; int n=digit......

**
**A robot is located at the top-left corner of a m x n grid (marked Start in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked Finish in the diagram below).
How many possible unique ....

arrays....

## class Solution { public: int uniquePaths(int m, int n) { if(m==0 || n==0) return 0; int arr......

**
**Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum....

arrays....

## class Solution { public: int maxSubArray(vector<int>& nums) { int max_sofar=nums[0]; int current_su......

**
**Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.....

arrays....

## class Solution { public: int searchInsert(vector<int>& nums, int target) { int i; for(i=0;i<nums.size();i+......

**
**Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn t matter what....

arrays....

## int removeElement(vector<int>& nums, int val) { int i=0; int n=nums.size(); while(i<n) {......

**
**Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each

input would have exactly one solution.....

arrays....

## class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(),nums.end(......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Arrays....

## vector<int> twoSum(vector<int>& nums, int target) { vector<int> v; map<int,int> m; for......

**
**Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?....

Array....

## class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; for(int i ......

**
**On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.....

Array....

## class Solution { public: int minCostClimbingStairs(vector<int>& cost) { for(int i=2;i<cost.size();i++) { ......

**
**A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a ....

Array....

## class Solution { public: int lenLongestFibSubseq(vector<int>& A) { unordered_set <int> s(A.begin(), A.end()......

**
**Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.....

Array....

## class Solution { public: int findMin(vector<int>& nums) { int mini = INT_MAX; for(int i=0;i<nums.size(......

**
**Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each

input would have exactly one solution.....

Array....

## class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end());......

**
**Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not ....

Array....

## class Solution { public: void sortColors(vector<int>& nums) { int l = 0, r = nums.size() - 1; int zro = ......

**
**A peak element is an element that is greater than its neighbors.
Given an

input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-....

Array....

## class Solution { public: int findPeakElement(vector<int>& nums) { int first = 0, end = nums.size() - 1; ......

**
**Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.....

Array....

## class Solution { public: int removeDuplicates(vector<int>& nums) { int h = 0; int num; if(nums.size......

**
**Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.....

Array....

## class Solution { public: int maximumSwap(int num) { string s = to_string(num); int res = num; for(int......

**
**A robot is located at the top-left corner of a m x n grid (marked Start in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked Finish in the diagram below).
How many possible unique ....

Array....

## class Solution { public: int uniquePaths(int m, int n) { int j = 1; long int res = 1; m--; n--; for(i......

**
**Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.....

Array....

## class Solution { public: int findDuplicate(vector<int>& nums) { if(nums.size() > 0) { int slow = nums[......

**
**Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct inte....

Array....

## class Solution { public: vector<int> constructArray(int n, int k) { vector<int> res; int revC = k; ......

**
**In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo s attacking ascending time series towards Ashe and the poisoning time duration per Teemo s attacking, you need to

iutput the total time that Ashe is in poisoned conditi....

Array....

## class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { int res = 0; ......

**
**Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).....

Array....

## class Solution { public: int thirdMax(vector<int>& nums) { long long f = LLONG_MIN, s = LLONG_MIN, t = LLONG_......

**
**Given an array, rotate the array to the right by k steps, where k is non-negative.....

Array....

## class Solution { public: void rotate(vector<int>& nums, int k) { vector<int> vec = nums; if(k != 0) ......

**
**Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and

iutput its length.....

Array....

## class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> v = nums; sort(nums......

**
**Count the number of prime numbers less than a non-negative number, n.....

use arrays to track prime no....

## class Solution { public: int countPrimes(int n) { vector<int> primes(n, 0); int i=2; ......

**
**Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.....

use map....

## Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that the......

**
**Apart from the Hanging Gardens the Babylonians (around 3000-539 b.c.) built the Tower of Babylon as well. The tower was meant to reach the sky, but the project failed because of a confusion of language imposed from much higher above.
For the 2638th anniversary a model of the tower will be rebuilt....

dp....

## #include <bits/stdc++.h> using namespace std; #define F first #define S second vector<pair<pair<int,int>,int......

**
**The tribe soon discovers that just communication is not enough and wants to meet each other to form a joint force against the terminator. But there is a deep canyon that needs to crossed. Points have been identified on both sides on which bridge ends can be made. But before the construction could be....

dp....

## #include <bits/stdc++.h> using namespace std; vector <pair<int,int> > vec(1009); int dp[1009]; int main(void){......

**
**Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

Input : [1,3,4,2,2]

Output : 2....

.....

## class Solution { public: int findDuplicate(vector<int>& nums) { int slow=nums[nums[0]],fast=nums[nums[n......

**
**Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input : 2736

Output : 7236 Explanation: Swap the number 2 and the number 7.....

.....

## class Solution { public: int maximumSwap(int num) { if(num/10 == 0) return num; string s=to_string(num); ......

**
**Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.

Example 1: Given nums = [1,1,1,2,2,3....

.....

## class Solution { public: int removeDuplicates(vector<int>& nums) { int ind=0,len=nums.size(),i=0,j; whil......

**
**A peak element is an element that is greater than its neighbors.
Given an

input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-....

.....

## class Solution { public: int findPeakElement(vector<int>& nums) { int l=0,h=nums.size()-1,m,L,R,len=nums.size......

**
**Given a rod of length L , you can cut as many pieces of any arbitrary length you desire . Your task is to find max. possible profit you can acquire , given the selling price of different lengths.
INPUT :
L- length of rod
A[1 through L ] - each denoting selling price of given length of rod
....

.....

## int maxPossibleProfit(int L, vector<int> cost){ vector<int> dp(L+1,0); for(int i=1;i<=L;i++) dp[i]=cost[i-1]......

**
**dp....

dp....

## class Solution { public int lengthOfLIS(int[] nums) { if(nums.length == 0) return 0; int[] dp = new ......

**
**Dp....

DP....

## class Solution { public int jump(int[] nums) { int[] dp = new int[nums.length]; dp[0] = 0; for(i......

**
**You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.

Example 1:

Input : 2

Output : 2 Explanation: There are two ways to climb to the ....

.....

## class Solution { public: int climbStairs(int n) { if(n<3) return n; int F=1,S=2,temp; for(int i=2;i......

**
**Given an unsorted array of integers, find the number of longest increasing subsequence.

Example 1:

Input : [1,3,5,4,7]

Output : 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input : [2,2,2,2,2]

Output : 5 Explanation: The length of longest ....

.....

## using namespace std; class Solution { public: int findNumberOfLIS(vector<int>& nums) { int len=nums.si......

**
**Binary Search ....

Array....

## class Solution { public int findPeakElement(int[] nums) { if(nums.length == 1) return 0; int s......

**
**Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.....

use map....

## class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> ma......

**
**Array....

Array....

## class Solution { public int findLength(int[] A, int[] B) { int[][] matrix = new int[A.length + 1][B.length......

**
**Array....

Array....

## class Solution { public boolean canJump(int[] nums) { int reached = 0; int i = 0; while(i ......

**
**Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not ....

.....

## class Solution { public: void sortColors(vector<int>& nums) { int S=0,E=0,len=nums.size()-1; while(E<=......

**
**Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.

Example 1:

Input : [3,4,5,1,2]

Output : 1....

.....

## class Solution { public: int findMin(vector<int>& nums) { int L=0,R=nums.size()-1,mid,ans=nums[0]; while......

**
**A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a ....

.....

## using namespace std; class Solution { public: int lenLongestFibSubseq(vector<int>& A) { int len=A.size(),ans......

**
**Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not emp....

Array....

## class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { if(n <= 0) return true; ......

**
**Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.....

Array....

## class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map <int, int> M; fo......

**
**Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements fr....

Array....

## class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int sz = nums1.......

**
**Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to

iutput the maximum average value.....

Array....

## class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int sum = 0; int res = INT_MI......

**
**Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.....

Array....

## class Solution { public: int removeDuplicates(vector<int>& nums) { int count = 0; int sze = nums.size();......

**
**In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.....

Array....

## class Solution { public: int dominantIndex(vector<int>& nums) { int firstMax = -1; int secondMax = -1; ......

**
**Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.....

Array....

## class Solution { public: int searchInsert(vector<int>& nums, int target) { for(int i=0;i<nums.size();i++) {......

**
**Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1.....

Array....

## class Solution { public: int pivotIndex(vector<int>& nums) { int sum = 0; for(int i=0;i<nums.size();i+......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Array....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map <int, int> M; vecto......

**
**A robot is located at the top-left corner of a m x n grid (marked Start in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked Finish in the diagram below).
How many possible unique ....

.....

## class Solution { public: int uniquePaths(int m, int n) { vector<vector<int> > vec; vector<int> temp(......

**
**Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.....

Array....

## class Solution { public: int maxSubArray(vector<int>& nums) { int g_c = INT_MIN,curr=0; for(int i=0;i<......

**
**Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn t matter what....

Array....

## class Solution { public: int removeElement(vector<int>& nums, int val) { int j =0; for(int i=0;i<nums.......

**
**Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.....

Array....

## class Solution { public: int findShortestSubArray(vector<int>& nums) { map<int, int> M; map<int, int......

**
**Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your retur....

Array....

## class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int s = 0; int e = num......

**
**Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does n....

Array....

## class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> vec; fo......

**
**Given an array nums, write a function to move all 0 s to the end of it while maintaining the relative order of the non-zero elements.....

Array....

## class Solution { public: void moveZeroes(vector<int>& nums) { int j =0; for(int i=0;i<nums.size();i++......

**
**Given a binary array, find the maximum number of consecutive 1s in this array.....

Array....

## class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int total = 0; int res = 0; ......

**
**Array....

Array....

## class Solution { public int uniquePaths(int m, int n) { int[][] matrix = new int[m][n]; for(int i = 0......

**
**Array....

Array....

## class Solution { public boolean canJump(int[] nums) { int max = 0; for(int i = 0; i<nums.length; i+......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
....

use map....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> m; vec......

**
**Diameter of BT....

Tree....

## /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNod......

**
**Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input : [3, 2, 1]

Output : 1 Explanation: The third maximum is 1. ....

.....

## class Solution { public: int thirdMax(vector<int>& nums) { int F,S,T; int f1=0,f2=0,f3=0; for(int v......

**
**Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and

iutput its length.

Example 1:

Input : [2, 6, 4, 8, 10, 9, 15] O....

.....

## using namespace std; class Solution { public: int findUnsortedSubarray(vector<int>& nums) { int len=nu......

**
**Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.

Example 1:

Input : [2,3,1,1,4]

Output : true Explanati....

.....

## class Solution { public: bool canJump(vector<int>& nums) { int possible=0,steps=nums.size(); for(int i=0......

**
**Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct inte....

.....

## using namespace std; class Solution { public: vector<int> constructArray(int n, int k) { vector<int>......

**
**tree....

Tree....

**
**In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo s attacking ascending time series towards Ashe and the poisoning time duration per Teemo s attacking, you need to

iutput the total time that Ashe is in poisoned conditi....

.....

## class Solution { public: int findPoisonedDuration(vector<int>& timeSeries, int duration) { int ans=0,le......

**
**Given an array nums of n integers where n > 1, return an array

iutput such that

iutput [i] is equal to the product of all the elements of nums except nums[i].

Example :

Input : [1,2,3,4]

Output : [24,12,8,6] Note: Please solve it without division and in O(n).....

.....

## class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int len=nums.size(); ......

**
**Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?

Example :

Input : [4,3,2,7,8,2,3,1]

Output : [2,3]....

.....

## using namespace std; class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int le......

**
**Array....

Array....

## class Solution { public int findPairs(int[] nums, int k) { if(nums.length == 0 || k < 0) return 0......

**
**array....

array....

## class Solution { public int findUnsortedSubarray(int[] nums) { int[] arr = nums.clone(); Arrays.sort(arr); ......

**
**Array....

Array....

## class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count = 0; int size = flowerb......

**
**array....

contains duplicate 2....

## class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> h = new HashSet&......

**
**Merge sorted array....

Array....

## class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int index = n + m - 1; i......

**
**Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:

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

Output :....

.....

## class Solution { public: int findPairs(vector<int>& nums, int k) { map<int,int> mp; for(int val:nums) ......

**
**Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not emp....

.....

## class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int sz=flowerbed.size(); ......

**
**Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements fr....

.....

## class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int len=m+n-1; ......

**
**Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST s total elements.....

.....

## /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *ri......

**
**Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is....

.....

## using namespace std; class Solution { public: // -1 if equal // 0 if s1<s2 // 1 if s1>s2 int comp(string......

**
**Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input : num1 = "2", num2 = "3"

Output : "6"

Example 2:

Input : num1 = "123", num2 = "456"

Output : "56088" Note: The length of both num1 and....

.....

## using namespace std; class Solution { public: string multiply(string num1, string num2) { int sz=0; rev......

**
**You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of l....

.....

## class Solution { public: int check(string a,string b){ if(a.size()!=b.size()) return 0; map<char,char> m......

**
**The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where....

.....

## class Solution { public: string countAndSay(int n) { string st="1",temp,len; if(n==1) return st; for(......

**
**Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input : "abab"

Output : T....

.....

## class Solution { public: bool repeatedSubstringPattern(string s) { string temp=s.substr(1,s.size()-1); te......

**
**Given an

input string, reverse the string word by word.

Example 1:

Input : "the sky is blue"

Output : "blue is sky the"

Example 2:

Input : " hello world! "

Output : "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.....

.....

## class Solution { public: string reverseWords(string s) { istringstream L(s); string ans=""; while(L>>......

**
**Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.

Example 1: Given nums = [1,1,2], Your....

.....

## using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { vector<int> :: ite......

**
**Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to

iutput the maximum average value.

Example 1:

Input : [1,12,-5,-6,50,3], k = 4

Output : 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 ....

.....

## class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int sum=0,ans; int len=nums.s......

**
**In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
If it is, return the index of the largest element, otherwise return -1.

Example 1:

Input : nums = [3, 6, ....

.....

## class Solution { public: int dominantIndex(vector<int>& nums) { int len=nums.size(); if(len==1) return 0......

**
**Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.

Example 1:

Input : [1,3,5,6], 5

Output : 2....

.....

## class Solution { public: int searchInsert(vector<int>& nums, int target) { int i,len=nums.size(); for(i=......

**
**Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1.....

.....

## class Solution { public: int pivotIndex(vector<int>& nums) { int sum=0; for(int val:nums) sum+=val; ......

**
**Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example :

Input : [-2,1,-3,4,-1,2,1,-5,4],

Output : 6 Explanation: [4,-1,2,1] has the largest sum = 6.....

Kadane s....

**
**Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.....

String....

## class Solution { public: bool isPalindrome(string s) { int start = 0, end = 0; string s1 = ""; for(in......

**
**Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, t....

String....

## class Solution { public: int leastInterval(vector<char>& tasks, int n) { map <char, int> M; map <cha......

**
**Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.....

String....

## class Solution { public: string complexNumberMultiply(string a, string b) { stringstream aa(a); stringstre......

**
**You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of l....

String....

## class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { ve......

**
**Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your r....

String....

## class Solution { public: bool canConstruct(string ransomNote, string magazine) { map <char, int>M; for(i......

**
**Given a string containing only three types of characters: ( , ) and * , write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis ( must have a corresponding right parenthesis ) .
Any right parenthesis ) must have a c....

String....

## class Solution { public: bool check(string &s, int start, int count){ if(count < 0) return false; for(i......

**
**Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B i....

String....

## class Solution { public: int repeatedStringMatch(string A, string B) { int flag = 0; int count = 1; ......

**
**Validate if a given string can be interpreted as a decimal number.....

String....

## class Solution { public: bool isNumber(string s) { int n = s.size(), i = 0, digits = 0, dots = 0; for (; i......

**
**Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.....

String....

## class Solution { int flag = 0; int st = 0; int end = 0; string s = ""; bool func(int i, string s) { ......

**
**.....

Array....

## class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { for(int i = 0; i < nums.length; i......

**
**Move Zeroes....

Arrays....

## class Solution { public void moveZeroes(int[] nums) { int i = 0; int j = 0; while(j < nums.len......

**
**Max. consecutive ones....

Array....

## class Solution { public int findMaxConsecutiveOnes(int[] nums) { int count = 0; int maxCount = 0; ......

**
**On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Examp....

.....

## class Solution { public: int minCostClimbingStairs(vector<int>& cost) { int step1=cost[0],step2=cost[......

**
**Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading z....

.....

## class Solution { public: vector<int> plusOne(vector<int>& digits) { reverse(digits.begin(),digits.end......

**
**Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn t matter what....

.....

## // important appli. of Q.283 class Solution { public: int removeElement(vector<int>& nums, int val) { ......

**
**Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input : [3,0,1]

Output : 2

Example 2:

Input : [9,6,4,2,3,5,7,0,1]

Output : 8....

.....

## class Solution { public: int missingNumber(vector<int>& nums) { int sum=0,n=nums.size(); for(auto val:nu......

**
**Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input : [1, 2, 2, 3....

.....

## class Solution { public: int findShortestSubArray(vector<int>& nums) { map<int,pair<int,int> > mp; ......

**
**Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your retur....

.....

## class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int st=0,en=numbers.s......

**
**Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does n....

.....

## class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { int n=nums.size(); ......

**
**Given an array nums, write a function to move all 0 s to the end of it while maintaining the relative order of the non-zero elements.

Example :

Input : [0,1,0,3,12]

Output : [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operati....

.....

## class Solution { public: void moveZeroes(vector<int>& nums) { int st=0,en=0,n=nums.size(); for(int......

**
**Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input : [1,1,0,1,1,1]

Output : 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The

input array will only contain 0 ....

.....

## class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int ans=0,temp=0; for(int......

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is a ....

for each count cum len of brick .final ans will be wall size - max occurance of any len....

## class Solution { public: int leastBricks(vector<vector<int>>& wall) { unordered_map<int,int> len; fo......

**
**In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.

Example s:

Input : answers = [1, 1, 2]

Output :....

for all different color group count the number .if count is greater than number take ceiling of count/group number ....

## class Solution { public: int numRabbits(vector<int>& answers) { unordered_map<int,double> num; for(aut......

**
**Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input : "tree"

Output : "eert" Explanation: e appears twice while r and t both appear once. So e must appear before both r and t . Therefore "eetr" is also a valid answer.

Example 2:

Input ....

store all char frequency and sort them based on frequency ....

## class Solution { public: string frequencySort(string s) { unordered_map<char,int> ch_fr; for(auto &i:s) ......

**
**Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input : "aacecaaa"

Output : "aaacecaaa"

Example 2:

Input : "abcd"

Output : "dcbabcd"....

.....

## using namespace std; class Solution { public: int computeLPSArray(string pat){ int len = 0,M=pat.size(); ......

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

get first string in map and check for different value for key in map repeat for second string....

## class Solution { public: bool isIsomorphic(string s, string t) { map<char, char> m1; map<char, ch......

**
**Number of Boomerang....

Map....

## class Solution { public int numberOfBoomerangs(int[][] points) { int ans = 0; for(int[] p : points) { ......

**
**Given a string containing just the characters ( and ) , find the length of the longest valid (well-formed) parentheses substring.....

Strings....

## class Solution { public: int longestValidParentheses(string s) { stack<int> m; int start=0; ......

**
**Given a string containing just the characters ( and ) , find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input : "(()"

Output : 2 Explanation: The longest valid parentheses substring is "()"

Example 2:

Input : ")()())"

Output : 4 Explanation: The long....

.....

## class Solution { public: int longestValidParentheses(string s) { stack<int> stk; int temp=0,ans=0;......

**
**Convert a non-negative integer to its english words representation. Given

input is guaranteed to be less than 231 - 1.....

strings....

## class Solution { public: string lessthantwenty[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "E......

**
**Brick wall....

Map....

## class Solution { public int leastBricks(List<List<Integer>> wall) { HashMap<Integer, Integer> h = new Hash......

**
**The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.....

when we get element for second time push into vector. for missing element iterate through map....

## class Solution { public: vector<int> findErrorNums(vector<int>& nums) { vector<int> res; map&l......

**
**Sort characters by frequency....

Map....

## class Solution { public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()){ return f......

**
**We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may re....

....

## class Solution { public: vector<string> uncommonFromSentences(string A, string B) { istringstream wrdStr(B); ......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and....

....

## class Solution { public: int numJewelsInStones(string J, string S) { unordered_map<char,int> jewel; for(......

**
**Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate
Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.
It is guaranteed a....

....

## class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { unordere......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

store all different kind of candies....

## class Solution { public: int distributeCandies(vector<int>& candies) { unordered_map<int,int> candy; f......

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard .

Example :

Input : ["Hello", "Alaska", "Dad", "Peace"]

Output : ["Alaska", "Dad"]....

push all char in map ....

## class Solution { public: vector<string> findWords(vector<string>& words) { unordered_map<char,int> letter......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.

Example : ....

count the number of pair of char ....

## class Solution { public: int longestPalindrome(string s) { unordered_map<char,int> p; for(auto i:s) ......

**
**Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.

Example :

Input : s = "abcd" t = "abcde"

Output : e Explanation: e is the letter ....

put all char of s in map and remove all char which is present int t and the char which is not in s will be the result....

## class Solution { public: char findTheDifference(string s, string t) { unordered_map<char,int> alpha; cha......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.

Example s: s = "leetcode" return 0. s = "loveleetcode", return 2.....

put all char in map with their index,if a char is repeated make their index as infinite.then return the char which have minimum index....

## class Solution { public: int firstUniqChar(string s) { unordered_map<char,int> letter; for(int i =0;i<......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [9,4]....

put array 1 in map and check if array 2 element is present or not .....

## class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_map......

**
**given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.....

use map....

## class Solution { public: int findLHS(vector<int>& nums) { map <int,int> mp; int res=0; for(int i =0......

**
**Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input : [1,2,3,1]

Output : true

Example 2:

Input : [1,2,3,4]

Output : fal....

put array element in map . return true if you encounter a number which is already present in map else return false....

## class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int,int> n; for(aut......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 ....

traverse the num array . for each element check whether target minus curr element is present in map or not.if it is present then done otherwise insert curr ele in map and move to the next element....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> n; ......

**
**Isomorphic String....

MAP....

**
**Multiply Strings....

String....

## class Solution { public String multiply(String num1, String num2) { String n1 = new StringBuilder(num1).reverse(......

**
**Compare Version Numbers....

String....

## class Solution { public int compareVersion(String version1, String version2) { String[] arr1 = version1.split("\......

**
**Group Anagrams....

Map Strings....

## class Solution { public String getSortedString(String str) { char[] arr = str.toCharArray(); Arrays.sor......

**
**Two Sum....

Map....

## class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> h = new HashMap<>()......

**
**Set Mismatch....

Map....

## class Solution { public int[] findErrorNums(int[] nums) { int[] freq = new int[nums.length + 1]; int[......

**
**A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers....

if it is repeating then it s infinite loop else continue till equal to 1....

## class Solution { public: bool isHappy(int n) { map<int, int> m; int squares = 0; while(n) { ......

**
**Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input : "1+1i", "1+1i"

Output : "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the f....

.....

## class Solution { public: string complexNumberMultiply(string a, string b) { int ind=a.find("+"); int l......

**
**Write a function that takes a string as

input and reverse only the vowels of a string.

Example 1:

Input : "hello"

Output : "holle"

Example 2:

Input : "leetcode"

Output : "leotcede"....

.....

## class Solution { public: string reverseVowels(string s) { vector<int> ind; for(int i=0;i<s.size();i++)......

**
**Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k char....

.....

## class Solution { public: string reverseStr(string s, int k) { int ind=0,len=s.size(); while(ind<len){ ......

**
**You are given a string representing an attendance record for a student. The record only contains the following three characters:
A : Absent.
L : Late.
P : Present.
A student could be rewarded if his attendance record doesn t contain more than one A (absent) or more than two continuous L....

.....

## class Solution { public: bool checkRecord(string s) { s+= P ; int ct1=0,ct2=0; for(int i=0;i<s.size......

**
**Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.

Example :

Input : "Hello, my name is John"

Output : 5....

.....

## class Solution { public: int countSegments(string s) { istringstream L(s); int ans=0; while(L>>s) ans......

**
**Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the

input array in-place, return the new length o....

.....

## class Solution { public: int ctDigit(int num){ int ans=0; while(num){ ans++; num/=10; }......

**
**Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn t banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. W....

.....

## class Solution { public: int check(char ch){ return (ch>= a &&ch<= z ) || (ch>= A && ch<= Z ); } stri......

**
**You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don t affect the one-to-one mapping relationship....

.....

**
**Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your r....

.....

## class Solution { public: bool canConstruct(string ransomNote, string magazine) { map<char,int> mp1,mp2; ......

**
**Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one s....

.....

## class Solution { public: int romanToInt(string s) { map<char,int> mp{{ I ,1},{ V ,5},{ X ,10},{ L ,50},{ C ,1......

**
**Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
A subsequence is a ....

.....

## class Solution { public: int findLUSlength(string a, string b) { if(a==b) return -1; return max((int)a.siz......

**
**International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-.....

.....

## class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { vector<string> values={".-......

**
**Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain . s or + s.
If you add periods ( . ) between some characte....

.....

## class Solution { public: int numUniqueEmails(vector<string>& emails) { set<string> st; for(string name......

**
**A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.....

get the words from string in map and check for frequency equal 1 and push the words in vector....

## class Solution { public: vector<string> uncommonFromSentences(string A, string B) { map<string,int> mp; ......

**
**Reverese words in a string....

String....

## class Solution { public String reverseWords(String s) { StringBuilder str = new StringBuilder(); StringBuil......

**
**Happy Number....

Map....

## class Solution { public boolean helper(HashSet<Integer> h, int n) { if(n == 1) return true; if......

**
**
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.....

1. get the char in string 2 . add even count in res 3. final res = even + odd + (n-1) (odd-1)....

## class Solution { public: int longestPalindrome(string s) { map<char,int> mp; bool odd = true; int r......

**
**Longest Palindrome....

Map....

## class Solution { public int longestPalindrome(String s) { HashMap<Character, Integer> h = new HashMap<>(); ......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.
....

using map....

## Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1. c......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

get the count of candies in map if all are distinct return map length else array lenth....

## class Solution { public: int distributeCandies(vector<int>& candies) { int l=candies.size(); map<int,in......

**
**Given an array of integers, find if the array contains any duplicates.
....

1.get the values of array in map and return true when 2 same element in array....

## class Solution { public: bool containsDuplicate(vector<int>& nums) { map<int , int> m; bool valid; ......

**
**String t is generated by random shuffling string s and then add one more letter at a random position.....

1. get the char of string 1 in map 2. decrement the value of char in string 2 in map and add new char....

## class Solution { public: char findTheDifference(string s, string t) { map<char,int> m; char a; ......

**
**Given two arrays, write a function to compute their intersection.
....

get the elements of first array in map for second array check if it is present in map and push into vector....

## class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { map<int,int......

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.....

for first array count the frequency of number using map for second array decrement the frequency value of matching number in first array find the number with frequency = 1....

## class Solution { public: int singleNumber(vector<int>& nums) { map<int,int> m1; int res; for(int......

**
**Distribute Candies....

Map....

## class Solution { public int distributeCandies(int[] candies) { HashSet<Integer> h = new HashSet<>(); ......

**
**Uncommon Words from two strings....

Map....

## class Solution { public String[] uncommonFromSentences(String A, String B) { HashMap<String, Integer> h = new ......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input : s = "anagram", t = "nagaram"

Output : true

Example 2:

Input : s = "rat", t = "car"

Output : false....

if size is different then not a valid anagram . and for same size put all char from first string into map and then reduce the count if a char is present in second string ....

## class Solution { public: bool isAnagram(string s, string t) { if(s.size()>t.size()) return false; u......

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input : [2,2,1]

Output : 1

Example 2:

Input : [4,1,2,1,2]

Output : 4....

take xor of all number....

## class Solution { public: int singleNumber(vector<int>& nums) { int res=0; for(auto n:nums) res ^=......

**
**Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B i....

.....

## class Solution { public: int repeatedStringMatch(string A, string B) { int lenA=A.size(),lenB=B.size(); in......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.
....

1. get the values of string s into map c 2. iterate through second string and decrement the map value for matching char 3. if map c has all zeros it is anagram else not anagram....

## class Solution { public: bool isAnagram(string s, string t) { map<char, int> c; for (int i = 0; i < s.......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.....

first insert the char of string J (stones) and then iterate through string S to find the char in map and count res for matching values in map....

## class Solution { public: int numJewelsInStones(string J, string S) { int res=0; map<char,int> C; fo......

**
**Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B i....

string....

## class Solution { public: int repeatedStringMatch(string A, string B) { int c=1; string temp......

**
**Find character which is randomly added to original string....

map....

## class Solution { public char findTheDifference(String s, String t) { int[] freq = new int[26]; for(in......

**
**Shortest Completing word....

map....

## class Solution { public boolean findAllChar(int[] temp) { for(int i = 0; i < temp.length; i++) { if......

**
**Find the number which has frequency 1....

used xor ....

## class Solution { public int singleNumber(int[] nums) { int xor = 0; for(int i = 0; i < nums.length;......

**
**Intersection of Two Arrays....

Map....

## class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> h = new HashSet<>();......

**
**A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a....

.....

## class Solution { public: int check(char ch){ if(ch== a || ch== e || ch== i || ch== o || ch== u || ch== ......

**
**Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input : "Let s take LeetCode contest"

Output : "s teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space....

.....

## class Solution { public: string reverseWords(string s) { string ans=""; istringstream L(s); while(L>>......

**
**Write a function that reverses a string. The

input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii charac....

.....

## class Solution { public: void reverseString(vector<char>& s) { for(int i=0;i<s.size()/2;i++) swap(s[......

**
**Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input : "Hello"

Output : "hello"....

.....

## class Solution { public: string toLowerCase(string str) { for(int i=0;i<str.size();i++) if(str[i]>= A ......

**
**Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input : "A man, a plan, a canal: Panama"

Output : true....

.....

## class Solution { public: // note: s1=s1+s[i]; ........... gives memory limit exceeded bool isPalindrome(string s)......

**
**Given a string s consists of upper/lower-case alphabets and empty space characters , return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.

Example :

Input : "Hello W....

.....

## class Solution { public: int lengthOfLastWord(string s) { istringstream L(s); int ans=0; while(L>>s) ......

**
**Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

Example 1:

Input : ["flower","flow","flight"]

Output : "fl"....

.....

## class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.size()==0) return ""; ......

**
**Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:

Input : "aba"

Output : True....

.....

## class Solution { public: bool validPalindrome(string s) { int st1=0,en1=s.size()-1,st2=0,en2=s.size()-1; w......

**
**Given a string containing just the characters ( , ) , { , } , [ and ] , determine if the

input string is valid.
An

input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also ....

.....

## class Solution { public: char getMatch(char ch){ if(ch== ) ) return ( ; if(ch== ] ) return [ ; if(ch=......

**
**Valid Paranthesis....

String....

## import java.util.*; class Solution { public boolean isValid(String str) { Stack<Character> s = new Stack<>(......

**
**LCA in BST....

if p and q are present at left then go left or if they are present at right subtree then go right otherwise return root....

## class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(p.val ......

**
**Validate BST....

using helper function with 2 parameters min and max value....

## class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VAL......

**
**Find words which can be typed using characters of single row of keyboard....

using hashmap....

## class Solution { public String[] findWords(String[] words) { HashMap<Character, Integer> h = new Has......

**
**Given a list of emails, we send one email to each address in the list. How many different addres

Input : ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]

Output : 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually recei....

string....

## class Solution { public: string helper(string s) { // string s=t.substr(0,x); // strin......

**
**A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a....

string....

## class Solution { public: int isvowel(char c) { if(c== a ||c== e ||c== i ||c== o ||c== u ||c== A ||c== E ||c== I ......

**
**Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input : "Hello"

Output : "hello"....

string....

## class Solution { public: string toLowerCase(string str) { for(int i=0;i<str.size();i++) { s......

**
**Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.....

string....

## class Solution { public: // i created this fun bool ispalindrome(string s, int start,int end) { while(......

**
**You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don t affect the one-to-one mapping relationship....

string....

**
**Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input : "Let s take LeetCode contest"

Output : "s teL ekat edoCteeL tsetnoc"....

string....

## class Solution { public: void rev(string &s,int start,int end) { char temp; while(start<end) { ......

**
**You are given a string representing an attendance record for a student. The record only contains the following three characters:
A : Absent.
L : Late.
P : Present.
A student could be rewarded if his attendance record doesn t contain more than one A (absent) or more than two continuous L....

string....

## class Solution { public: bool checkRecord(string s) { int l=0,a=0; int i; for(i=0;i<s.size();i++) ......

**
**Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k char....

string....

## class Solution { public: string reverseStr(string s, int k) { int i=0; while(i<s.size()) { i......

**
**Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
A subsequence is a ....

string....

## class Solution { public: int findLUSlength(string a, string b) { if(a==b) return -1; ......

**
**Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Onl....

string....

## /* here take two variables s for count of small and c for capital and check all given condition */ class Solution {......

**
**Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input : "abab"

Output : T....

string....

## class Solution { public: bool repeatedSubstringPattern(string s) { int i; string temp=""; for(i=0;i&l......

**
**Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the

input array in-place, return the new length o....

string....

## class Solution { public: int compress(vector<char>& chars) { if(chars.size()==1) return 1; if(c......

**
**Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.

Example :

Input : "Hello, my name is John"

Output : 5s in a String....

string....

## class Solution { public: int countSegments(string s) { int res = 0; s.push_back( ); //adding space at las......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.

Example s: s = "leetcode" return 0. s = "loveleetcode", return 2.....

string....

## class Solution { public: int firstUniqChar(string s) { map<char,int> m; for(int i=0;i<s.size();i......

**
**Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your r....

string....

## class Solution { public: bool canConstruct(string ransomNote, string magazine) { if(magazine.size()<ransomNot......

**
**Write a function that takes a string as

input and reverse only the vowels of a string.

Example 1:

Input : "hello"

Output : "holle"

Example 2:

Input : "leetcode"

Output : "leotcede....

string....

## class Solution { public: bool isvowel(char c) { switch(c) { case a : return true; ......

**
**Write a function that reverses a string. The

input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii charac....

string....

## class Solution { public: void reverseString(vector<char>& s) { int start=0; int end=s.size()-1; int......

**
**Given a string s consists of upper/lower-case alphabets and empty space characters , return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.

Example :

Input : "Hello W....

string....

## class Solution { public: int lengthOfLastWord(string s) { if(s.size()==0) return 0; int res=0......

**
**

Input : ["eat", "tea", "tan", "ate", "nat", "bat"],

Output :
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]....

string....

## class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { int i; map<st......

**
**1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.....

string....

## class Solution { public: string countAndSay(int n) { int i; string temp="1"; while(n>1) { ......

**
**Given a string containing just the characters ( , ) , { , } , [ and ] , determine if the

input string is valid.
An

input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also ....

String....

## class Solution { public: bool isValid(string s) { stack<char> t; int i; for(i=0;i<s.si......

**
**. Longest Common Prefix....

. Longest Common Prefix....

## class Solution { public: string longestCommonPrefix(vector<string>& strs) { string x=""; if(strs.size......

**
**Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.....

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.....

## class Solution { public: int value(char c) { if(c== I ) return 1; if(c== V ) return 5; ......

**
**You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don t affect the one-to-one mapping relationship....

String....

## class Solution { public: string s; string tree2str(TreeNode* root) { printTree(root); if(root == NU......

**
**Given a string containing just the characters ( , ) , { , } , [ and ] , determine if the

input string is valid.
An

input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also ....

String....

## class Solution { public: bool isValid(string s) { stack<char> stk; for(int i=0;i<s.size();i++) { ......

**
**Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.....

String....

## class Solution { public: int countSegments(string s) { int cnt = 0; istringstream iss(s); string word......

**
**Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""....

String....

## class Solution { public: string longestCommonPrefix(vector<string>& strs) { string result = ""; in......

**
**Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the

input array in-place, return the new length o....

String....

## class Solution { public: int compress(vector<char>& chars) { char curr = chars[0]; int i = 0; vec......

**
**Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.....

String....

## class Solution { public: bool repeatedSubstringPattern(string s) { int startCount = 1; string substr = "";......

**
**The count-and-say sequence is the sequence of integers with the first five terms as following:....

String....

## class Solution { public: string countAndSay(int n) { string temp = "1a"; string str = ""; int cnt = 0......

**
**Given a string s consists of upper/lower-case alphabets and empty space characters , return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.....

String....

## class Solution { public: int lengthOfLastWord(string s) { int cnt = 0; int len = s.length() - 1; whi......

**
**Write a function that takes a string as

input and reverse only the vowels of a string.....

String....

## class Solution { public: void swap(int start, int end, string &s) { char temp = s[start]; s[start] = s[en......

**
**Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn t banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. W....

String....

## class Solution { public: string mostCommonWord(string paragraph, vector<string>& banned) { for(int i = 0; i &......

**
**Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k char....

String....

## class Solution { public: string reverseStr(string s, int k) { int startPtr = 0; int endptr = k; while......

**
**You are given a string representing an attendance record for a student. The record only contains the following three characters:
A : Absent.
L : Late.
P : Present.
A student could be rewarded if his attendance record doesn t contain more than one A (absent) or more than two continuous L....

String....

## class Solution { public: bool checkRecord(string s) { int noOfAb = 0; for(int i=0;i<s.size();i++) { ......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.....

String....

## class Solution { public: int firstUniqChar(string s) { unordered_map<char, int> Umap; for(int i= 0 ;i &l......

**
**A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a....

String....

## class Solution { public: string toGoatLatin(string S) { string word = ""; string Res = ""; int wordC......

**
**Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.....

String....

## class Solution { public: string toLowerCase(string str) { for(int i = 0;i<str.size(); i++) { if(str[i]......

**
**International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.....

String....

## class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { vector<string> morseValues......

**
**Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain . s or + s.
If you add periods ( . ) between some characte....

String....

## class Solution { public: int numUniqueEmails(vector<string>& emails) { int findAt = 0; int low = 0; ......

**
**Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.....

String....

## class Solution { public: string reverseWords(string s) { int prevI = 0; s.insert(0, " "); for(int i =......

**
**Write a function that reverses a string. The

input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii charac....

String....

## class Solution { public: void reverseString(vector<char>& s) { char curr = a ; int S = 0; int E = s......

**
**First Unique Character in String....

In first pass store all the frequencies of character. Then in next pass find first character which has frequency 1....

## class Solution { public int firstUniqChar(String s) { HashMap<Character, Integer> h = new HashMap<>(); ......

**
**Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.....

string....

## string reverseWords(string s) { stringstream ss(s); string str; string ans = ""; while(ss>>str){ reverse(str.begin(......

**
**Write a function that reverses a string. The

input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the

input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii charac....

string....

## class Solution { public: void reverseString(vector<char>& s) { int i = 0; for(int i = 0 ; i < s.s......

**
**Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
....

string....

## class Solution { public: string toLowerCase(string str) { for (auto i = 0; i < str.size(); i++) if (......

**
**A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a....

string....

## string toGoatLatin(string S) { unordered_set<char> vowel({ a , e , i , o , u , A , E , I , O , U }); istrin......

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 ....

We take the help of a helper function called depth.This is a top down approach. Recursion applied!....

## class Solution { public: int depth(TreeNode* root){ if(root==NULL) return 0; return max(depth(root-......

**
**Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

Input : 1 / ....

Recursive....

## class Solution { public: TreeNode* trimBST(TreeNode* root, int L, int R) { if(root==NULL) return root; ......

**
**Given a binary tree, determine if it is a complete binary tree.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h no....

with the help of calculating left child and right child index comparing with the total nodes we can avoid extra memory.Using queues might be inefficient.....

## class Solution { public: int nodes(TreeNode* root) { if(root==NULL) return 0; return (......

**
**Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be ....

simple recursion!....

## class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { ......

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input : 1->1->2

Output : 1->2

Example 2:

Input : 1->1->2->3->3

Output : 1->2->3....

....

## /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int......

**
**Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input : 1->2->3->3->4->4->5

Output : 1->2->5

Example 2:

Input : 1->1->1->2->3

Output : 2->3....

....

**
**Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list s nodes, only nodes itself may be changed.

Example : Given 1->2->3->4, you should return the list as 2->1->4->3.....

....

**
**We are given the head node root of a binary tree, where additionally every node s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
....

....

**
**Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST s total elements.

Example 1:

Input : root = [3,1,4,null,2], k = 1 3 / 1 4 2

Output : 1

Example 2:

Input : root = [....

....

**
**Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input : 2 / 1 3

Output : 1

Example 2:

Input : 1 / 2 3 / / 4 5 6 / 7

Output : 7....

....

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / 9 ....

....

**
**Given a binary tree, determine if it is a complete binary tree.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h node....

....

**
**You need to find the largest value in each row of a binary tree.

Example :

Input : 1 / 3 2 / 5 3 9

Output : [1, 3, 9]....

....

**
**We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.

Example 1:

Input : root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2 Outpu....

....

**
**Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node s descendants. The tree s could also be considered as a subtree of itself.

Example 1: Given tree ....

....

**
**Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.

Example : Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 ....

....

**
**Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node s value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to

iutput the ....

....

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.

Example : Given the below binary tree and sum = 22, 5 / 4 8 / / 11 1....

....

**
**We are given the head node root of a binary tree, where additionally every node s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)....

.....

**
**Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.....

.....

## using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *......

**
**Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be ....

.....

**
**Given a binary tree, find the leftmost value in the last row of the tree.....

.....

**
**Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.....

Phone number-Backtracking....

## class Solution { public: vector<string> letterCombinations(string digits) { map<int,string> phoneComb; ......

**
**Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.....

Backtracking....

## class Solution { public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { ......

**
**Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node s descendants. The tree s could also be considered as a subtree of itself.

Example 1: Given tre....

we create a new function, sameTree to compare the sameness of two trees(Identical). rest is just use of recursion....

## class Solution { public: bool isSubtree(TreeNode* s, TreeNode* t) { if(!s) return false; if(sameTree(s,t))......

**
**Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node s value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to

iutput th....

recurse....

**
**Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.

Example : Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / ....

recursive approach....

## class Solution { public: int minDepth(TreeNode* root) { if(root == NULL){return 0;} if(root->left == NULL ......

**
**Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1:

Input : [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / 3 6 / 2 4 8 / ....

direct recursive approach....

## class Solution { public: TreeNode* increasingBST(TreeNode* root,TreeNode* tail = NULL) { if(!root) return tail;......

**
**Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input : [-4,-1,0,3,10]

Output : [0,1,9,16,100]

Example 2:

Input : [-7,-3,2,3,11]

Output : [4,9,9,49,121]....

implementation....

## class Solution { public: vector<int> sortedSquares(vector<int>& A) { sort(A.begin(),A.end()); fo......

**
**Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the sam....

SIMPLE RECURSIVE SOLUTION....

## class Solution { public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { string seq1,seq2; preO......

**
**Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1:

Input : [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / 3 6 / 2 4 8 / ....

MAKE USE OF HELPER FUNCTION....

## class Solution { public: TreeNode* increasingBST(TreeNode* root) { TreeNode *start=NULL,*curr=NULL; ......

**
**Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.....

Find total diameter for each node then find max of prev diameter value with diameter of both side subtrees.....

**
**Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all node....

For each node ,recursively find sum of all left and right child and find abs difference. Then return root->val+l+r.....

**
**Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the mer....

Traverse each side and if thenode is null then take 0 as value and further pass null for that node. Create a new tree using temp as pointer and add new values there.....

## /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left......

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.....

tree....

## bool isBalanced(TreeNode* root) { int depth = 0; return isBalanced(root, depth); } bool isBalanced(TreeNode*......

**
**Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.....

tree....

## class Solution { public: int minDepth(TreeNode* root) { if(root==NULL) return 0; else if(root->left=......

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.....

tree....

## public: bool hasPathSum(TreeNode* root, int sum) { if(root==NULL)return false ; if(root->left==NULL && root->right==N......

**
**Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node s descendants. The tree s could also be considered as a subtree of itself.....

trees....

## class Solution { bool isSame(TreeNode* s, TreeNode* t){ if(s==nullptr && t==nullptr){ return true; }......

**
**Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node s descendants. The tree s could also be considered as a subtree of itself.....

.....

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.

Example : Given the below binary tree and sum = 22,....

.....

## using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *le......

**
**Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node s value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to

iutput th....

.....

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.....

.....

**
**Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.....

.....

**
**Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:....

.....

**
**Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example : Given a binary tree ....

.....

**
**Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all node....

.....

**
**Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.....

.....

**
**Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the mer....

.....

**
**Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.....

Traverse recursivley each side,by storing current sum in "current" variable, which is curr*10 + root->val ....

**
**Invert a binary tree.
....

Here Each subtree(or each node) is being inverted (i.e left and right child are interchanging) ,then that subtree is also inverted wrt its parent node.So ,go until bottom and invert that tree and b....

**
**Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:....

Use helper function and consider it as combination of 2 trees(divide like mirror) and then take 2 roots for the 2 trees and check left of first tree with right node of 2nd tree and vice versa.....

**
**Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.....

traverse recursively each side of both tree .....

**
**Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.....

Back tracking....

## class Solution { public: bool exist(vector<vector<char>>& board, string word) { int index = 0; bool ou......

**
**Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.....

Back tracking ....

## class Solution { public: vector<vector<int>> a; vector<vector<int>> subsets(vector<int>& nums) { v......

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

Back tracking....

## class Solution { public: vector<string> out; vector<string> generateParenthesis(int n) { string s; ......

**
**Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.....

Back tracking....

## class Solution { public: vector<vector<char>> v; vector<string> letterCasePermutation(string S) { vect......

**
**Given a collection of distinct integers, return all possible permutations.....

Back tracking....

## class Solution { public: vector<vector<int>> v; vector<vector<int>> permute(vector<int>& nums) { v......

**
**Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive....

Backtracking......

## class Solution { public: vector<int> res; vector<vector<int>> R; vector<vector<int>> combinationSum2......

**
**Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.....

Backtracking....

## class Solution { public: vector<int> res; vector<vector<int>> R; vector<vector<int>> combinationSum3......

**
**Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (includ....

Backtracking....

## class Solution { public: vector<int> res; vector<vector<int>> R; vector<vector<int>> combinationSum(......

**
**Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.....

Backtracking....

## class Solution { public: vector<vector<int>> result; vector<vector<int>> combine(int n, int k) { vec......

**
**Find the sum of all left leaves in a given binary tree.....

.....

## //using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode......

**
**Count Complete Tree Nodes....

.....

**
**Mungeri Lal is opening a medicine shop. So u need to make his life easy..He is having a inventory rural area.and he is having a shop in the main market.In the shop he need to store all the medicine..each medicine have multiple units.so when ever a customer come to him he will ask for the medicine so....

.....

## // we assume all following data stored initially const long long refOfDaysForCalcUnits=30; // assuming Mungerilal is ......

**
**We have discussed the registration system in the class...The question is as follows..user used to give there user name if the username is present then we need say ok. If the username is already taken then we need to add 1,2,3, so on to the end of the username..now there is a prob..if one of the user....

.....

## First we assume that there is no white space in the userName We maintain a map of active userNames as key and value a......

**
**Design a Phone Directory which supports the following operations: 1) get: Provide a number which is not assigned to anyone. 2) check: Check if a number is available or not. 3) release: Recycle or release a number..Write all the three FUNCTION....

.....

## /* We use a map as the data structure ,named "directory" with key as the number(in string format) and value as the per......

**
**Invert a binary tree.....

.....

**
**Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.....

.....

**
**Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you b....

Arrays....

## class Solution { public int maxProfit(int[] prices) { if (prices.length == 0) return 0; int profit = 0; ......

**
**A robot is located at the top-left corner of a m x n grid (marked Start in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked Finish in the diagram below).
Now consider if some obst....

Backtracking....

## class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (null == obstacleGrid) return 0;......

**
**Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.....

....

## class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> rs = new Ar......

**
**Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.....

Binary search....

## class Solution { public boolean search(int[] nums, int target) { int start = 0, end = nums.length - 1, mid =......

**
**Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.....

....

## class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length ==......

**
**Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.....

Arrays....

## class Solution { public void setZeroes(int[][] m) { boolean fr = false; boolean fc = false; for(......

**
**Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transac....

greedy....

## class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int profit = 0; ......

**
**Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.....

greedy....

## class Solution { public int jump(int[] nums) { // If nums.length < 2, means that we do not // need to mov......

**
**Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.....

.....

**
**Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.....

Greedy....

## class Solution { public String removeKdigits(String num, int k) { if(k == 0) return num; Stack<Character>......

**
**Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.....

greedy....

## class Solution { enum Index { GOOD, BAD, UNKNOWN } public boolean canJump(int[] nums) { if(nums.leng......

**
**Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentat....

Backtracking....

## class Solution { private Map<String,List<String>> map = new HashMap<>(); public List<String> wordBre......

**
**Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.....

Backtracking....

## class Solution { private HashMap<Character, String> digitMap = new HashMap<>(); { digitMap.put( 2 , "......

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

Backtracking....

## class Solution { public List<String> generateParenthesis(int n) { List<String> rs = new ArrayList<>(); ......

**
**Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.....

backtracking....

**
**Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.....

Use a trie....

## class Solution { public List<String> findWords(char[][] board, String[] words) { List<String> res = ne......

**
**Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.....

Backtracking....

## class Solution { public boolean exist(char[][] board, String word) { if(board.length == 0 || word.isEmpty()) ret......

**
**Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive....

Backtracking....

## class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List&......

**
**Given a collection of distinct integers, return all possible permutations.....

Backtracking....

## class Solution { List<List<Integer>> rs = new ArrayList<>(); public List<List<Integer>> permute(int[......

**
**Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.....

Backtracking....

## class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> list = ......

**
**You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.....

Backtracking....

## class Solution { private int count = 0; public int findTargetSumWays(int[] nums, int S) { findTargetSumWa......

**
**Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.....

Backtracking....

## class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List......

**
**Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.....

Backtracking....

## class Solution { List<List<Integer>> rs = new ArrayList<>(); public List<List<Integer>> combine(int ......

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

....

## class Solution { public int lengthOfLongestSubstring(String s) { if (null == s || s.isEmpty()) return 0; if......

**
**Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The part....

This question gives us a linked list and a positive number k. Let us split the linked list into part k and divide it as evenly as possible. If the node is not enough, use an empty node, as in example ....

## class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { vector<ListNode*> res(......

**
**Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example :

Input : [ 1->4->5, 1->3->4, 2->6 ]

Output : 1->1->2->3->4->4->5->6....

.....

## using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *ne......

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

.....

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input : 1->2->3->4->5->NULL, k = 2

Output : 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL....

.....

**
**Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list s nodes, only nodes itself may be changed.....

.....

**
**A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.....

.....

## /** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * Rand......

**
**Design valet parking system with **N** lot.where the cars come and park one after the other..if a car went out that place will be vacant..and whenever a new car come it will go to that place..you need to generate a token() for every car which is going to the parking lot..when the owner want to take ....

.....

## /* Since the size of the slot is fixed , we shall use set and vectors for the reqd. task */ //we defi......

**
**design a playlist(in music player)which include all the function like queue next,play at the end ,shuffle the list and repeat the current song.write a function for each of the requirement(15marks) *....

.....

## /** Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : ......

**
**add one pointer in each node such that the pointer points to the next to next node.(5marks)....

.....

## // Definition for singly-linked list. struct ListNode { int val; ListNode *next,*next2next; ListNode(int x......

**
**)Add one variable in each node which tells its index from the last.from the first(for first node n second node n-1 so on if there are N nodes).(5marks)....

.....

## // Definition for singly-linked list. struct ListNode { int val; int index; ListNode *next; ListNode(i......

**
**1)Add one variable in each node which tells its index.from the first(for first node 1 second node 2 so on).(5marks)....

.....

**
**Given a linked list, remove the n-th node from the end of list and return its head.

Example : Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do th....

.....

**
**Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.

Example :

Input : head = 1->4->3->2->5->2, x = 3

Output : 1->2->2->4->3->5....

.....

**
**Given a linked list, swap every two adjacent nodes and return its head.

Example : Given 1->2->3->4, you should return the list as 2->1->4->3.....

.....

**
**Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The part....

.....

**
**Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.

Example s:

Input : S = "a1b2"

Output : ["a1b2", "a1B2", "A1b2", "A1B2"]

Input : S = "3z4"

Output : ["3z4", "3Z4"]

Input : ....

SIMPLE BACKTRACKING!....

## class Solution { public: vector<string> ans; vector<string> letterCasePermutation(string S) { ......

**
**You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.....

Use backtracking....

**
**sum in combination or not (with repetition)....

repetition is allowed so take loopindex again from 0 each time and continue until sum==0 || sum==-1....

## //sum in combination or not with repetition of number.... #include <iostream> #include <vector> #include <alg......

**
**sum in combination or not without repetition of number....

if 2,5 is already checked then 5,2 should not be checked again for sum (same thing) ,so use x+1 to move forward.....

## #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> v; bool fun......

**
**Remove all elements from a linked list of integers that have value val.

Example :

Input : 1->2->6->3->4->5->6, val = 6

Output : 1->2->3->4->5....

.....

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input : 1->1->2

Output : 1->2....

.....

**
**You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the nu....

.....

**
**We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
Exampl....

.....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example :

Input : 1->2->4, 1->3->4

Output : 1->1->2->3->4->4....

.....

**
**You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the nu....

Reverse both the lists, create two variable for storing the sum and carry and initially set them to zero, iterate through both the lists and add the data values and carry. After adding both the lists ....

## /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNod......

**
**Write a program to find the node at which the intersection of two singly linked lists begins.....

Find the length of both the linked list, find the difference between there lenghts and move the pointer to the pointer of longer linkedlist steps equal to the difference of their lenghts and then chec....

**
**Remove all elements from a linked list of integers that have value val.....

Create a dummy node to the head of the list, create a pointer pointing to that dummy pointer, iterate through the list and check wheter the pointer.next data is equal to the data, if it is then put p.....

**
**Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
....

Create two pointer fast and slow, the fast moves two places ahead then the slow. If cycl exists in the linked list then these pointers would meet.....

## /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x......

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.....

Check for the current and the next node if the data is same the set current.next to current.next.next, else move one step forward.....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.....

Create a new list as ans, in ans add the data which is less as of both the lists data and move the pointer to the next position of the list with less data value, repeat the process untill end of both ....

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.....

Make the current node data equal to the next node data and make the current nodes next pointer to point to next node s next node.....

**
**Reverse a singly linked list.....

Reverse the pointers in the linkedlist.....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
....

Create two pointers fast and slow. The fast pointer moves twice then the slow one so that when the fast pointer is at the end of the list then the slow is in the middle.....

**
**Write a program to find the node at which the intersection of two singly linked lists begins.....

.....

**
**You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and positio....

.....

## class Solution { public: string getHint(string secret, string guess) { int ct=0; unordered_map<int......

**
**Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher s h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h....

.....

## class Solution { public: int hIndex(vector<int>& citations) { if(citations.size()==0) return 0; sort(cit......

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

Example 1:

Input : "abcabcbb"

Output : 3 Explanation: The answer is "abc", with the length of 3. ....

.....

## using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size()==0) r......

**
**Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is g....

.....

## class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { ......

**
**You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input :[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] ....

.....

## class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { vector<pair<int......

**
**Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input : [[1,1],[2,2],[3,3]]

Output : 3....

.....

## using namespace std; /** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0),......

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:

Example 1:

Input : head = [4,5,1,9], node = 5

Output : [4,1,9] Explanation: You are given the second node ....

.....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.

Example 1:

Input : [1,2,3,4,5]

Output : Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judg....

.....

**
**Reverse a singly linked list.

Example :

Input : 1->2->3->4->5->NULL

Output : 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?....

.....

**
**All possible arrangements of 4 things(1,2,3,4) be placed in 3 places.
Therefore, 4*4*4 = 64 ways. We should print 64 possible ouputs.....

I/P :1,2,3,4 places:3 O/P: 111, 112, 113, ... 444 (total 64)....

## class Solution { public: int count = 1; void subsets(vector<int>& nums) { vector<int> V; for(in......

**
**Ex: If

input is 3: code should print 000 to 111.....

I/P: 4 O/P: 0000 to 1111....

## class Solution { public: void combine(int n, int k) { vector<int> V; vector<vector<int>> V1; al......

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

Store all values in each level of binary tree, Then while printing print all subsequent values in reverse fashion.....

**
**Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.....

Store all values in all levels of binary tree. then take average. ....

**
**Given an n-ary tree, return the postorder traversal of its nodes values.
For example, given a 3-ary tree:....

Order is value of all nodes, then data. ....

## /* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(i......

**
**Given an n-ary tree, return the preorder traversal of its nodes values.
For example, given a 3-ary tree:....

N-ary pre order traversal. (data, value of all nodes)....

**
**Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.....

We use level order traversal.....

**
**Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.....

Put numbers in stack, If incoming number is less than top element, then pop the top element and put the element into the stack.....

## class Solution { public: string removeKdigits(string num, int k) { stack <int>S; int pick = 9; int ......

**
**Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.....

Question is to find if we can jump from start to end through the given path. Hint is to traverse backward.....

## class Solution { public: bool canJump(vector<int>& nums) { int flag = 0; int minHt = 1; if(nums.siz......

**
**In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can e....

N Queue theory....

## class Solution { public: string predictPartyVictory(string senate) { queue<int> q1, q2; for(int i= 0;i &......

**
**There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return....

Greedy algorithm....

## class Solution { public: int findModNum(int num, int sze) { if(num >= sze) { num %= sze; } ......

**
**given BBBRRR or similar find all possible arrangements....

seperate modules is self explanatory....

## public class AllPossibleValues { LinkedList<Character> elements; HashSet<String> result; AllPossibleValues() ......

**
**[1,2,3] given find all possible combinations
ex
[[123],[132],[213],[231],[312],[321]]....

taking the array into arraylist and performing backtracking in combination function....

## class Solution { List<List<Integer>> al=new ArrayList<List<Integer>>(); public List<List<Integer>> per......

**
**Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.....

use backtracking....

## class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> rs = new ArrayLis......

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.

Example : Given the below binary tree and sum = 22, 5 / 4 8 / / 11 1....

.....

## class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root == NULL)return false; sum -= r......

**
**Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example : Given a binary tree 1 / 2 3....

novel. We take help of another function which takes root node as input and an integer which in the initial height which is set to be zero. Then we move left recursively each time updating that height ....

## class Solution { public: int getHeight(TreeNode* root,int& maxHeight){ if(!root)return 0; int left = getHe......

**
**find the element that occurs n times in the array of size 2N if there are exact N+1 unique element in array and out of which only one element is repeated....

insert the element in the map if it appears 1st time else return the element if it is already occurs in the map....

## class Solution { public: int repeatedNTimes(vector<int>& A) { map<int , int >m; int d=A.size(); i......

**
**out of many stone you have identify the jewels....

create a map of the stone that are jewels, the traverse the whole string of stone that we have and check if it is jewel that count it otherwise don t .....

## class Solution { public: int numJewelsInStones(string J, string S) { int count=0; map<char,int>m; f......

**
**Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.

Example : Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / ....

recursion.....

## class Solution { public: int minDepth(TreeNode* root) { if(root==NULL) return 0; if (root->left ......

**
**Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input : 1 1 / / 2 3 2 3 [1,2,3]....

recursion....

## class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p==NULL&&q==NULL) return t......

**
**Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example :

Input : 1 / 2 3 / / 4 5 6

Output : 6....

recursion....

## class Solution { public: int countNodes(TreeNode* root) { if(root==NULL) { return 0; } ......

**
**The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n whe....

use nested for loop....

## class Solution { public String countAndSay(int n) { StringBuilder prev = new StringBuilder("1"); StringBuil......

**
**In a string S of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".
Call a group large if it has 3 or more characters. We would like the starting and ending positions of ev....

Use two pointers....

## class Solution { public List<List<Integer>> largeGroupPositions(String S) { List<List<Integer>> rs = new......

**
**Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.....

simple recursive solution....

## class Solution { public int addDigits(int num) { if(num <= 9) { return num; } int sum = 0; ......

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.....

use xor....

## class Solution { public int singleNumber(int[] nums) { int res = 0; for(int num: nums) { res = res ^......

**
**We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You ....

use map....

## class Solution { public String[] uncommonFromSentences(String A, String B) { Map<String, Integer> m = new Hash......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

....

## class Solution { public int numberOfBoomerangs(int[][] points) { int rs = 0; Map<Integer, Integer> ma......

**
**You are given a data structure of employee information, which includes the employee s unique id, his importance value and his direct subordinates id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respecti....

Use a map....

## class Solution { public int getImportance(List<Employee> employees, int id) { Map<Integer,Employee> m = new ......

**
**Given a pattern and a string str, find if str follows the same pattern.....

Use a map....

## class Solution { public boolean wordPattern(String pattern, String str) { if(pattern == null || pattern.isEmpty(......

**
**Given a string, sort it in decreasing order based on the frequency of characters.....

....

## class Solution { public String frequencySort(String s) { Map<Character,Integer> map = new HashMap<>(); ......

**
**Given a non-empty array of integers, return the k most frequent elements.....

Store the array entry and its count in a map. Now store the entries in the map in a max priority queue sorted by the count. Fetch k entries from the priority queue ....

## import javafx.util.Pair; class Solution { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integ......

**
** Implement a magic directory with buildDict, and search methods.
For the method buildDict, you ll be given a list of non-repetitive words to build a dictionary.
For the method search, you ll be given a word, and judge whether if you modify exactly one character into another character in this w....

Use a map....

## class MagicDictionary { Set<String> words; /** Initialize your data structure here. */ public MagicDictiona......

**
**Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.....

use map....

## class Solution { public int subarraySum(int[] nums, int k) { if(nums == null | nums.length == 0) return 0; ......

**
**Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.....

First build a map, with key the word and value the word count. Now get all of the keys from the map and sort it as follows: if the word count is same, then it should be sorted alphabetical else sorted....

## class Solution { public List<String> topKFrequent(String[] words, int k) { Map<String,Integer> m = new HashM......

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is ....

Use a map. Don t consider the last wall in each row....

## class Solution { public int leastBricks(List<List<Integer>> wall) { Map<Integer,Integer> m = new HashMap&l......

**
**The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).....

We use array for adding elements into it.....

## class Solution { public: int fib(int N) { if(N == 0) return 0; int A[N+1]; A[0] = 0; A[1] ......

**
**Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/
2 2
/ /
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/
2 2
3 3....

intuitive. Each subtree should be symmetric. so , two children become the inputs for our helper function.....

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

Example :

Input : [1,null,2,3] 1 2 / 3

Output : [3,2,1]....

recursive approach. first left, then right, then the root .....

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

Example :

Input : [1,null,2,3] 1 2 / 3

Output : [1,3,2]....

we create another function which takes in the root and vector as the input. we traverse recursively. from left to root and then root to right and in between this we push the value of the root to the v....

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is ....

.....

## using namespace std; class Solution { public: int leastBricks(vector<vector<int>>& wall) { map<int......

**
**Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input : ["i", "love", "leetcode", "i", "love", "....

.....

## class Solution { public: struct comp{ bool operator()(const pair<int,string> &p1,const pair<int,string>......

**
**Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input : [0,1]

Output : 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.....

.....

## class Solution { public: int findMaxLength(vector<int>& nums) { map<int,int> mp; int ans=0,sum=0......

**
**Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input :nums = [1,1,1], k = 2

Output : 2....

.....

## using namespace std; class Solution { public: int subarraySum(vector<int>& nums, int k) { int ans=0,su......

**
**Given a binary tree, flatten it to a linked list in-place.....

Use a dummy node....

**
** Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
....

Use an auxillary stack to store current min....

## class MinStack { Stack<Integer> st = new Stack<>(); Stack<Integer> mst = new Stack<>(); /** initializ......

**
**Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.....

use a hash set....

## class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { Set<Integer> tmp = new HashSet<......

**
**There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided

input is the start and end coordinates of the horizontal diameter. Since it s horizontal, y-coordinates don t matter and hence the x-coordinates of start and end of the diameter suffice. Start is alw....

Greedy approach....

## class Solution { public int findMinArrowShots(int[][] points) { if(points.length<=1) return points.length; ......

**
**The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is guaranteed each....

Sort the people array and use two pointer approach....

## class Solution { public int numRescueBoats(int[] people, int limit) { int rs = 0, s = 0, e = people.length - 1; ......

**
**Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. ....

Use greedy....

## /** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start......

**
**Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.....

Use a dummy node. ....

**
**The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is guaranteed each....

Here take 2 pointers and move from both sides, and check the given condition.....

## class Solution { public: int numRescueBoats(vector<int>& people, int limit) { int b= 0; int s = 0, e = peop......

**
**You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.
If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
If ....

*here we are given a vector of tokens. I your points(P) >= token[i] then you can buy that token and score will in crease by 1. If above case is not true then if you have atleast score=1 ,then you c....

## class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(),to......

**
**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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign....

Here,sort both the vectors and then check whether the size of cookie is >= greed of child or not. In loop,check whether k (index for greed vector) has not reached the end of vector.....

## class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(),g.e......

**
**Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed fro....

Here ,take two pointers which points to the 2 words.Now,if any char is found from the original word in the the other word,then increase i and j both ....else only increase pointer of other word(j++) ....

## class Solution { public: bool isSubsequence(string s, string t) { int i=0; int j=0; int c=0; ......

**
**There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided

input is the start and end coordinates of the horizontal diameter. Since it s horizontal, y-coordinates don t matter and hence the x-coordinates of start and end of the diameter suffice. Start is alw....

It is same as overlapping interval problem.If, here 2 intervals overlap or can reside fully inside other interval then a single arrow can burst both the intervals/ballons. Even if the interval startin....

## class Solution { public: int findMinArrowShots(vector<pair<int, int>>& points) { if(points.size()==0) ......

**
**Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
....

Here ,sort the intervals on basis of start end using comparator function,Then, check whether the start time of current interval is less than the end time of prev interval, if it is so then c++ (remove....

## /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), e......

**
**Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed fro....

If character do not match increment both i and j. Otherwise just increment j.....

## class Solution { public: bool isSubsequence(string s, string t) { int s1 = 0 , s2 = 0 ,i = 0, j = 0; whil......

**
**Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval s end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don t ....

Learn to use function which has to be performed based on struct elements: bool comp (const Interval &a, const Interval &b) { if(a.start == b.start) { return a.start > b.start; } ....

**
**The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is guaranteed each....

Use 2 pointers, one at start and one at end. ....

## class Solution { public: int numRescueBoats(vector<int>& people, int limit) { int boatCount = 0; int s = 0; i......

**
**There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided

input is the start and end coordinates of the horizontal diameter. Since it s horizontal, y-coordinates don t matter and hence the x-coordinates of start and end of the diameter suffice. Start is alw....

Here, shortening interval( [min(currentEnd, points[i].second)] ) is the key....

## class Solution { public: int findMinArrowShots(vector<pair<int, int>>& points) { int currentEnd =0; in......

**
**You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.
If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
If ....

Use 2 pointers, one at start and one at end. ....

## class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()......

**
**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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign....

The goal is to maximize the number of your content children and output the maximum number.....

## class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end())......

**
**You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input : s = "barfoothefoobarman", words = ["....

used lists technique in python.It may not be efficient code but u can get the desired result.....

## class Solution: def findSubstring(self, s, words): if not words: return [] m, n, o, target = len(s), len(wo......

**
**We are given head, the head node of a linked list containing unique integer values. We are also given the list G, a subset of the values in the linked list. Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.....

WE NEED TO MAINTAIN A MAP AND A CONDITION VARIABLE....

## class Solution { public: int numComponents(ListNode* head, vector<int>& G) { if(head==NULL) retu......

**
**You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.....

similar to adding but reverse the lists....

## class Solution { public: ListNode *rev(ListNode *head){ if(head==NULL||head->next==NULL){ return head; ......

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:

Example 1:

Input : head = [4,5,1,9], node = 5

Output : [4,1,9] Explanation: You are given the second node ....

easy concept.....

## class Solution { public: void deleteNode(ListNode* node) { node->val=node->next->val; ListNode *tmp=node->......

**
**You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list....

we need to traverse both the lists and keep adding these values and store this in another list and we should check the carry condition.....

## class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry=0,sum; ListNode *......

**
**Given a linked list, swap every two adjacent nodes and return its head.....

we need to take three pointers and swap the second with first address first with third and we need to check whether the third or fourth node is null each time.....

## class Solution { public: ListNode* swapPairs(ListNode* head) { if(head==NULL||head->next==NULL) { ......

**
**Implement a magic directory with buildDict, and search methods.
For the method buildDict, you ll be given a list of non-repetitive words to build a dictionary.
For the method search, you ll be given a word, and judge whether if you modify exactly one character into another character in this wo....

k....

## using namespace std; class MagicDictionary { public: map<string,pair<int,char> > mp; map<string,pair&l......

**
**In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.

Example s:

Input : answers = [1, 1, 2] Out....

k....

## using namespace std; class Solution { public: int numRabbits(vector<int>& answers) { unordered_map<i......

**
**Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input : nums = [1,1,1,2,2,3], k = 2

Output : [1,2]....

k....

## using namespace std; class Solution { public: struct comp{ bool operator()(const pair<int,int> &p1,const......

**
**Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input : "tree"

Output : "eert" Explanation: e appears twice while r and t both appear once. So e must appear before both r and t . Therefore "eetr" is also a valid answer.....

k....

## class Solution { public: struct comp{ bool operator()(const pair<char,int> &p1,const pair<char,int> &p2){ ......

**
**Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.
In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)
Return the number of ....

calculate the coins required for left and right subtree. calculate the coins needed for current node.....

**
**There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return....

....

## class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int tank = 0; for(int i = 0; i <......

**
**Given a string s and a string t, check if s is subsequence of t. ....

Use two pointers....

## class Solution { public boolean isSubsequence(String s, String t) { int si = 0; int ti = 0; while(......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1....

see for each element that (target - current value ) exist or not ....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector <int> ans; ......

**
**Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input : pattern = "abba", str = "dog cat cat dog"

Output : true....

Just maintain two maps which keep the information of relation between characters and string , since the relation is one-one hence two maps are required. When we get the relation which i....

## class Solution { public: bool wordPattern(string pattern, string str) { unordered_map<char,string> mp1; ......

**
**Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input : nums = [1,2,3,1], k = 3

Output : true....

For every value in vector , hash every index at which the value found , automatically for every value in map , the vector of index will be in sorted order (i.e. in increasing order) , t....

## class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map<int ,int> mp; ......

**
**Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same charac....

If strings have not equal length then return false otherwise just maintain two maps which keep the information of relation between characters , since the relation is on....

## class Solution { public: bool isIsomorphic(string s, string t) { map<char,char> mp1,mp2; if(s.size......

**
**The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this se....

The minimum number is 1 and the maximum number is size of vector i.e. nums.size() in proper vector. Since a number has frequency 2 and other element between 1 and nums.size() is absen....

## class Solution { public: vector<int> findErrorNums(vector<int>& nums) { long long total=nums.size(); ......

**
**Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all node....

we create another function sum which will add up all the left subtree tilt values and the right subtree and root->val....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example :

Input : 1->2->4, 1->3->4

Output : 1->1->2->3->4->4....

first find the head of by comparing the given two linked lists then traverse along the two linked lists and by comparing both of them select the desired node which is smallest and add it to the head ....

## class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1==NULL) { retur......

**
**Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input : h....

using sptr and fptr....

## class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) { return false; } ......

**
**Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.

Example 1:

Input : intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3

Output :....

traversing until we find the intersected node.iIt can also be done using count method.....

## class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *p1=headA; ......

**
**Given a singly linked list, determine if it is a palindrome.

Example 1:

Input : 1->2

Output : false

Example 2:

Input : 1->2->2->1

Output : true....

here the challenging thing is that in case of odd numbered list we need to eliminate the middle element in order to comapre so we make use of the prev slowpointer in this case.....

## class Solution { public: bool isPalindrome(ListNode* head) { bool result; if(head==NULL ||head->next==NULL)......

**
**328. Odd Even Linked List
Medium
593
199
Favorite
Share
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run....

a simple traversal!....

## class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head==NULL ||head->next==NULL) { ......

**
**203. Remove Linked List Elements
Easy
672
41
Favorite
Share
Remove all elements from a linked list of integers that have value val.

Example :

Input : 1->2->6->3->4->5->6, val = 6

Output : 1->2->3->4->5....

through traversing and updating the list each time when we occur a node with given value....

## class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode*p1=head,*p2; if(p1==N......

**
**Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list s nodes, only nodes itself may be changed.

Example 1: Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2: Given 1->2->3->4->5, reor....

find middle node,split list into 2 parts with the help of middle node,reverse second half ,create a new linked list and add the first half and second half thus creates a new linked list of desired ord....

## class Solution { public: void reorderList(ListNode* head) { if(head==NULL||head->next==NULL){ return; ......

**
**Integer to Roman....

Use greedy method....

## class Solution { String[] keys = new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}......

**
**Count the number of prime numbers less than a non-negative number, n.....

Use an array to keep track of which no is a prime....

## class Solution { public int countPrimes(int n) { if (n <= 2){ return 0; } boolean[] isN......

**
**Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.....

Compare alternate bits....

## class Solution { public boolean hasAlternatingBits(int n) { char[] ch = Integer.toBinaryString(n).toCharArray();......

**
**Given two arrays, write a function to compute their intersection....

Use a hash set....

## class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1.length == 0 || nums2.length ==......

**
**Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, re....

unordered set....

## string longestWord(vector<string>& words) { std::unordered_set<std::string> set(words.begin(), words.end()); ......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

map....

## class Solution { public: int sqaure_sum(int& n) { int sum = 0; while(n>0) {sum += (n%10) * (n%10......

**
**Given two arrays, write a function to compute their intersection....

map....

## class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.....

map....

## class Solution { public: int firstUniqChar(string s) { unordered_map<char, pair<int, int>> map; ......

**
**Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.....

map....

## bool containsDuplicate1(vector<int>& nums) { sort(nums.begin(), nums.end()); for (int i=0; i<int(nums.size())-......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

map....

## class Solution { public: long distanceSquare(pair<int, int> p1, pair<int, int> p2){ long x = p1.first - p2.......

**
**You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
....

map....

## class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int res = 0; int i = 0; ......

**
**You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
....

island....

## class Solution { private: int M , N; bool isSafe(int i , int j) { return (i >= 0 && i < M && j >= 0 &&......

**
**Find the sum of all left leaves in a given binary tree.

Example : 3 / 9 20 / 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.....

trivial....

## class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if(!root) return NULL; if(root->left && !ro......

**
**Invert a binary tree.

Example :

Input : 4 / 2 7 / / 1 3 6 9

Output : 4 / 7 2 / / 9 6 3 1....

direct recursive solution.....

## class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == NULL){ return NULL; } ......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]

Example 2:

Input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output : [9,4] Note: Each element in the result must be unique. The result can be in any order.....

hash for all distinct elements ,a pair, where first value of the pair =1 implies it occurred in the first array, similarly second value = 1 means it appeared in 2nd array. now iterate over entire ma....

**
**Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input : 5

Output : True Explanation: The binary representation of 5 is: 101....

hash for both 1 and 0 (the possible bit value at any position) , the indices%2,indices being indices where they occur as seen from right of binary representation. now for both 1 and 0 , check if al....

## class Solution { public: bool hasAlternatingBits(int n) { map<int,vector<int> >mp; int ind=0; ......

**
**You are given a data structure of employee information, which includes the employee s unique id, his importance value and his direct subordinates id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respecti....

its a simple backtracking problem. for every employee add its importance and call recursively for all its subordinates , do so for all . ....

## using namespace std; /* // Employee info class Employee { public: // It s the unique ID of each node. // uniqu......

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Example 1:

Input : [2,2,1]

Output : 1....

hash for all numbers in a map, then iterate over entire map to find if any key has freq greater than 1;....

## class Solution { public: int singleNumber(vector<int>& nums) { map<int,int> mp; for(int i=0;i<nums.s......

**
**Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input : [1,2,3,1]

Output : true....

keep adding in set until the no. has not been encountered and once got a no. which has been encountered before , return true, else return false at the end.....

## class Solution { public: bool containsDuplicate(vector<int>& nums) { set<int> st; for(int i=0;i&......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.

Example s: s = "leetcode" return 0.....

first of all hash freq. for all distinct characters . Now iterate over entire string from beginning, if at any instant a character is found whose freq.=1, return it else return -1.....

## class Solution { public: int firstUniqChar(string s) { map<char,int> mp; for(int i=0;i<s.size();......

**
**Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers,

iutput all of them with no order r....

maintain map of key string and value as pair, where first value from pair stores index of occurrence of string in 1st list, similarly 2nd value stores for 2nd list. Now make a map of int as key a....

## class Solution { public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { ......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2,2] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.....

simply hash freq of all unique elements int both arrays,as pair , where first value of pair is freq. from the 1st array and 2nd one from the 2nd array. having done that , simply add the element min(f....

## class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector <int> a......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

maintain a set of all distinct numbers found, if at any instant a number is found to be repeated , it implies that we are encountering same process, i,e, infinite loop. finally if "1" found, break....

## class Solution { public: bool isHappy(int n) { bool ans=false; set<int> st; while(n){ int su......

**
**Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, re....

first sort the dictionary ,which ensures that all prefixes of a word , if present are encountered before the word is encountered; Now , whenever a word of length is found insert in the set that its....

## class Solution { public: string longestWord(vector<string>& words) { //cout<<"length of dict.= "<<wor......

**
**You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
....

for each found island , add 4 to the answer , then if it has a shared island just above it , subtract 2 from it as 2 boundaries shared, Similarly do for an island found just laft to it .....

## class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int ct=0; for(int ......

**
**Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.

Example :

Input : s = "abcd" t = "abcde"

Output : e....

simply hash in same map for all characters in both strings. then iterate over entire map and see if any key has value od, then that character is the reqd. ans.....

## class Solution { public: char findTheDifference(string s, string t) { map<char,int> mp; for(int i=0;i<......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

for each i terate overall j !=i and hash for dist as keys and value as coordinates as pair . then for each distinct "distance" ,suppose we get A points ,then choosing that "i" we can select from re....

## class Solution { public: int numberOfBoomerangs(vector<pair<int, int>>& points) { map<int ,int> mp;......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]....

for every distinct value in the array hash a pair s first value as 1 if its present in 1st and hash 2nd value as 1 if its present in 2nd array. then key having both values in its corresponding p....

**
**You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.
If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
....

use two pointers and sort....

## class Solution { public int bagOfTokensScore(int[] tokens, int P) { int s = 0; int e = tokens.length - 1; ......

**
**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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign....

Use two pointers and sort both the arrays....

## class Solution { public int findContentChildren(int[] g, int[] s) { if(g.length == 0 || s.length == 0) return 0;......

**
**Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time ....

Logic has 4 cases i)Both left and right subtrees are NULL ii)Left or right subtrees is NULL iii)Both left and right subtree exists....

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard like the image below.....

map....

## class Solution { public String[] findWords(String[] words) { if(words == null || words.length == 0){ ......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.....

....

## class Solution { public boolean isAnagram(String s1, String s2) { if ((null == s1 && null != s2) || (null != s1 ......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Input : s = "anagram", t = "nagaram"

Output : true
....

map....

## class Solution { public: bool isAnagram(string s, string t) { map < char, int > m1,m2; for (int i=0; i&l......

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard....

Map....

## class Solution { public: vector<string> findWords(vector<string>& words) { map<char,int> mp{ ......

**
**candie size....

map....

## class Solution { public: map<int, int> can; int distributeCandies(vector<int>& candies) { for(int i = ......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S ....

map....

## class Solution { public: int numJewelsInStones(string J, string S) { map<char,int> jewel; int count = 0;......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

first count all distinct candies then return minimum of distinct count & total count/2;....

## class Solution { public: int distributeCandies(vector<int>& candies) { int len=candies.size(); map<int......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input : s = "anagram", t = "nagaram"

Output : true....

hash in increasing manner for all characters in 1st string and then do so in decreasing manner for 2nd string . then iterate over all map keys , if any value is non-zero then NOT ANAGRAM else ANAGR....

## class Solution { public: bool isAnagram(string s, string t) { map<char,int> mp; int len1=s.size(),......

**
**Given a List of words, return the words that can be typed using letters of alphabet on only one row s of American keyboard .

Example :

Input : ["Hello", "Alaska", "Dad", "Peace"]

Output : ["Alaska", "Dad"]....

first create a map of all characters in both upper & lower case,where value is the row number in which it occurs. then for each word store row number in a temp. var. and then iterate over all rest ....

## class Solution { public: vector<string> findWords(vector<string>& words) { map<char,int> mp{ ......

**
**We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You ....

here we maintain value of each distinct word as a pair. A first value=1 means that word is present in `first string once && a 2nd value=1 means that word is present in 2nd string. then itera....

## class Solution { public: vector<string> uncommonFromSentences(string A, string B) { map<string,pair&l......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

first hash for all jewels in string J. then iterate over all characters of string S . and whenever a jewel is found in hashed map , increase ct variable by one . ....

## class Solution { public: int numJewelsInStones(string J, string S) { map<char,int> mp; for(int i=0;i<J......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Exa....

first of all hash frequency of all distinct characters then take even no. of all distinct characters and add 1 if any one character with odd frequency!....

## class Solution { public: int longestPalindrome(string s) { map<char,int> mp; for(int i=0;i<s.size();i+......

**
**Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf....

depth first search function can be created and called to check if the final leaf vectors of both the trees and same or not .....

## class Solution { public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector <int>l1; vector <......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1....

direct application of map....

## class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { std::unordered_map<int, in......

**
**Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input : 1 1 / / 2 3 2 3 [1,2,3]....

simple application of recusive calling. if the left subtree of tree1 is equalto left subtree of tree2 "AND " right subtree of tree2 equal to the right subtree of tree 2 given that the root of the b....

**
**Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node s value equals the given value. Return the subtree rooted with that node. If such node doesn t exist, you should return NULL.
For example,
Given the tree:
4
/
....

so, provided that the root is not NULL and it s value is not equal to val(the number we want to search in the tree). So, if the value of the root is greater than the value we need, it means we need to....

## class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { while(root != NULL && root->val != val)......

**
**Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the mer....

so, we keep updating the values in the tree1 with the correspoding node s value in tree2. One of the trivial cases, is when one of the tree s root is NULL. It means , we will simple have to return th....

## class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (t1 == NULL) return t2; ......

**
**You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don t affect the one-to-one mapping relationship....

Binary tree: [1,2,3,null,4] => Output: "1(2()(4))(3)"....

**
**Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.....

The sum of maximum path in binary tree is returned from this code. ....

**
**The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automaticall....

Houses which are in adjacent levels of binary trees should never be robbed.....

**
**Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.....

Given inorder and preorder, this code will construct complete tree.....

**
**Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.....

This code will return vector of treenodes which are duplicate. ....

**
**You need to find the largest value in each row of a binary tree.....

Use depth first search....

**
**Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.....

[1,2,3]=> 12 + 13 = 25....

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.....

a binary tree in which the depth of the two subtrees of every node never differ by more than 1 is called Balanced binary tree according to question. ....

**
**Share
We are given the head node root of a binary tree, where additionally every node s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant....

Pruning refers to removal of subtrees whose entire values are zeros.....

**
**Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all node....

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Sum of tilt of all nodes is the total tilt o....

**
**You need to find the largest value in each row of a binary tree.....

This code will return a vector which will hold the maximum elements of rows in tree. ....

**
**Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:....

isSymmetric function will return whether the tree is a mirror of itself or not....

**
**Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. ....

do level order traversal....

**
**Given an n-ary tree, return the preorder traversal of its nodes values.....

regular pre-order traversal....

## /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} ......

**
**Given an n-ary tree, return the postorder traversal of its nodes values.....

regular post order traversal....

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.....

....

**
**Given a singly linked list, determine if it is a palindrome.....

Find the mid point of the list. Reverse the second half and check first and second half one node at a time....

**
**Given a linked list, swap every two adjacent nodes and return its head.

Example : Given 1->2->3->4, you should return the list as 2->1->4->3.....

Use recursion....

**
**Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.....

....

**
**Write a program to find the node at which the intersection of two singly linked lists begins.....

....

**
** A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list. ....

Map old values to new values.....

## /** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * Rando......

**
**You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the nu....

Use a stack....

**
**You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the nu....

traverse both the lists and compute sum....

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

use fast and slow pointers....

**
**Given a linked list, determine if it has a cycle in it.....

use fast and slow pointers....

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.....

Copy the next node s value to current node and delete next node....

**
**Reverse Linked List....

Reverse a linked list....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.....

Use two pointers, slow and fast....

**
**Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.....

If null list or list with one node, return head. Create a dummy node whose next is list head. Use two pointers, prev and cur.....

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.....

First check if list is empty or has only one node. If yes, just return the head. Use a previous and current pointers to traverse the list. Check if the prev s value is same as current s value. If ye....

**
**Given a linked list, remove the n-th node from the end of list and return its head.....

First position the second pointer n positions from the front. Now keep moving first and second pointers till first pointer is null....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.....

Use a dummy node and a priority queue to merge the lists....

**
**Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.....

Use a priority queue to merge the lists.....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.

Example 1:

Input : [1,2,3,4,5]

Output : Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judg....

taking two pointers fast and slow and traversing until the list is empty slow pointer gives us the middle of the linked list.....

## class Solution { public: ListNode* middleNode(ListNode* head) { if(head==NULL ||head->next==NULL) { ......

**
**Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.

Example :

Input : head = 1->4->3->2->5->2, x = 3

Output : 1->2->2->4->3->5....

consider two linked lists such that while traversing the given inked list if its value is lessthan the given value add it to the first else add it to the second while end of the traversing combine the....

## class Solution { public: ListNode* partition(ListNode* head, int x) { if(head==NULL ||head->next==NULL) { ......

**
**Find unique email addresses....

....

## class Solution { public int numUniqueEmails(String[] emails) { Set<String> res = new HashSet<>(); for(S......

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

....

**
**Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level).....

....

**
**Given a binary tree, return all root-to-leaf paths.....

....

**
**Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serializ....

....

**
** Given a binary tree, find the leftmost value in the last row of the tree. ....

Do a level order traversal, for each level, traverse from right to left. So when we reach the end, we will end up at the bottom left most node in the tree....

**
**Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node s key.
The right subtree of a node contains only nodes with keys greater than the node s key.
....

At each node, keep track of the min and max values. When we go to left child, the max value is the parent node s value. Similarly when we go to right child, the min value is the parent node val. At ea....

**
**Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.....

Use depth first search....

**
**Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.....

Keep a maxLevel variable, initialized to 0. Do a depth first search of the tree, right then left subtree. Pass a level variable to the recursion. Whenever the maxlevel is less than level, then add th....

**
**Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.....

Check if the root s values are same. Now check recursively left and right subtrees....

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

Iterative post order traversal of a binary tree....

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

Iterative pre-order traversal of a BST....

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

Iterative inorder traversal of a Binary Tree using a stack....

**
**You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c....

count is used t check if integers from all lists are present.....

## class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { vector <pair<int, int......

**
**Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the lin....

as discussed in the class using fptr and sptr.....

## class Solution { public: ListNode *detectCycle(ListNode *head) { bool cycle=false; ListNode *sptr......

**
**Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input : 1->2->3->3->4->4->5

Output : 1->2->5

Example 2:

Input : 1->1->1->2->3

Output : 2->3....

Here there is necessary for the dummy pointer because the duplicates might be started from the first index itself hence we need to store the address of head using dummy.....

## */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* dummy = new ListNod......

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.....

as k times right indicates n-k left. Here the interesting thing is inorder to form a new linked list in the rotated order and to return the head we create a newhead and join the two lists.....

## class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(head==NULL) { retu......

**
**Given a linked list, remove the n-th node from the end of list and return its head.

Example : Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.....

we need to traverse using two pointers that initially points to head.....

**
**Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input : [0,1]

Output : 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input : [0,1,0]

Output : 2 Explanation: [0, 1] (or [1, 0]) is....

replacing 0 with -1 and storing the index in map.....

## class Solution { public: int findMaxLength(vector<int>& nums) { map<int, int> myMap; map<int, int>::iter......

**
**You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input :[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] Out....

Using priority queues ....

## class Solution { public : vector < int > smallestRange(vector<vector< int >>& nums) { int curMax = ......

**
**Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is g....

using map we store the sum of two elements and check whether the sum multiplied by -1 is possible by the other pairs ....

**
**You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input :[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] Out....

Here we have given k lists and from that we need to find the smallest range..so we have multiple ways like priorities queue and stacks..but i m using two pointer and a map with a counter variable..Th....

## class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { vector<int>r; map&l......

**
**Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input : nums = [1,1,1,2,2,3], k = 2

Output : [1,2]

Example 2:

Input : nums = [1], k = 1

Output : [1]....

we take the key value pairs in map and then we keep in the vector and sort it using the function compare traverse it until k and append them to the result.....

## bool compare (pair<int, int> a, pair<int, int> b) { return a.second > b.second; } class Solution { ......

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. The brick wall is represented by a list of rows. Each row is a l....

using a map store the values of sum of bricks in row and return the maximum occuring.....

## class Solution { public: int leastBricks(vector<vector<int>>& wall) { if(wall.size() == 0 || wall[0].size()......

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is ....

using a map store the values of sum of bricks in row and return the maximum occuring.....

**
**Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher s h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h....

in order to find out n-h i have used the sort. when we traverse from the end and increment the count with condition that a[k]>count it is easy to find the h value....

## class Solution { public: int hIndex(vector& citations) { int c=0,n=citations.size(),k; if(n<1) return(0); ......

**
**Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.

Example : Given array....

we have taken a dictionary and using the concept of 2 sum i had stored the corresponding indexes with the sum in the dictionary and i had found that whether the target- 2sum is found in the dictionary....

## class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rty......

**
**Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the mer....

This function will merge two binary trees.....

**
**A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.....

isunivalTree will return if entire tree is having only one value or not....

**
**Given a binary tree and a sum, find all root-to-leaf paths where each path s sum equals the given sum.
Note: A leaf is a node with no children.....

pathSum will return all possible paths from head to leaf whose sum results in given number.....

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.....

hasPathSum will return if there us any path from head to lead with sum equals given number.....

**
**Given a list of daily temperatures T, return a list such that, for each day in the

input , tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71....

Use stack ....

## class Solution { public int[] dailyTemperatures(int[] temperatures) { int res [] = new int[temperatures.length]......

**
**Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input : nums = [1,1,1,2,2,3], k = 2

Output : [1,2]

Example 2:

Input : nums = [1], k = 1

Output : [1]....

Use min heap ....

## class Solution { public List<Integer> topKFrequent(int[] words, int k) { Map<Integer, Integer> map = new H......

**
**Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input : [[1,1],[2,2],[3,3]]

Output : 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4

Example 2:

Input : [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Out....

The points are said to be on the same line if they have same slope.So we found the slope for each pair of points that are possible and we store it in the map. Here there would be two special cases i.e....

## class Solution { public: int maxPoints(vector<Point> &points) { if(points.size()<2) return po......

**
**Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input : [[1,1],[2,2],[3,3]]

Output : 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4

Example 2:

Input : [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Out....

## class Solution { public: int maxPoints(vector<Point> &points) { if(points.size()<2) return po......

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

Example :

Input : [1,null,2,3] 1 2 / 3

Output : [1,2,3]....

Simple recursive solution. we create another function named preTraversal which takes root pointer and also a vector , and this helps us pushing the values into the vector v.....

**
**Implement a magic directory with buildDict, and search methods.
For the method buildDict, you ll be given a list of non-repetitive words to build a dictionary.
For the method search, you ll be given a word, and judge whether if you modify exactly one character into another character in this wo....

Consider a dictionary and insert all the strings of the input in the dictionary. traverse through the dictionary and find the word in the dictionary that is having samelength as of the input word. N....

## class MagicDictionary: def __init__(self): """ Initialize your data structure here. """ self.di......

**
**.....

.....

**
**.....

.....

**
**.....

.....

**
**.....

.....

**
**.....

.....

**
**.....

.....

## class Solution { public: bool helper(TreeNode *root,int n){ bool z; if(root->val==n){ z=true; ......

**
**Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same charac....

use one hashmap ....

## class Solution { public boolean isIsomorphic(String s, String t) { return isIsomorphicHelper(s,t) && isIsomorphi......

**
**Implement a magic directory with buildDict, and search methods.
For the method buildDict, you ll be given a list of non-repetitive words to build a dictionary.
For the method search, you ll be given a word, and judge whether if you modify exactly one character into another character in this wo....

using hashmap....

## class Pair{ int index; char ch; Pair(int index, char ch){ this.index = index; this.ch = ch; } } class ......

**
**https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=4387....

....

## #include<bits/stdc++.h> using namespace std; int index(vector<int> &d, int p){ for(int i=0;i<6;i++){ if(d......

**
**Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the di....

Creaet hashmap for each row/column and each block ....

## public class IsValidSudoku { public boolean isValidSudoku(char[][] board) { if (board == null || board.length ==......

**
**A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
....

just check the values of all the left and right children and then their children. All the children should also be univalued. That calls us for use of recursive call to the function.....

**
**Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.....

simple recursive way to traverse the children and find the maximum depth....

## class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; return max( maxD......

**
**You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).....

here we traverse entire tree node by node and add the no of possible root to leaf paths rooted at present node to the count (cnt) variable and return cnt....

## class Solution { public: int pathSum(TreeNode* root, int sum) { int no=0; cnt_no(root,&no,sum); retur......

**
**Given a binary tree and a sum, find all root-to-leaf paths where each path s sum equals the given sum.
Note: A leaf is a node with no children.....

same logic as leetcode 112 but here we declare a vector of vectors and use helper fn to add the root to leaf paths with given sum to that....

## class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> rtl......

**
**Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum....

go on decreasing sum valur by root->val ,if sum==root->val at leaf node then return true....

## class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root==NULL){ return false; }......

**
**Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.....

....

**
**Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the mer....

....

**
**Invert a binary tree.....

....

**
**Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.....

....

**
**Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
....

....

**
**A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.....

If the root is null then return true. Check if the root s value is same as left child value and right child value if they are not null. Now check for the left and right subtrees....

**
**.....

.....

## /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */......

**
**.....

.....

**
**.....

.....

## /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struc......

**
**.....

.....

**
**.....

.....

**
**.....

.....

## int max(int a,int b){ if(a>=b) return a; else return b; } int min(int a,int b){ if(a<=b) return a; else ......

**
**.....

.....

## int mod(int a){ if(a>=0) return a; else return -a; } int min(int a,int b){ if(a<=b) return a; else retur......

**
**.....

.....

## class Solution { public: int minAreaRect(vector<vector<int>>& points) { vector<vector<int> >&p=points; ......

**
**.....

.....

**
**.....

.....

## class Solution { public: int numRabbits(vector<int>& answers) { vector<int>& a =answers; map<int,int......

**
**.....

.....

## class Solution { public: int subarraySum(vector<int>& nums, int k) { vector<int>& n=nums; map<int,in......

**
**.....

.....

## class Solution { public: int leastBricks(vector<vector<int>>& wall) { vector<vector<int>>& w=wall; ......

**
**.....

.....

## class Solution { public: int numberOfBoomerangs(vector<pair<int, int>>& points) { vector<pair<int, int>......

**
**.....

.....

## class Solution { public: bool containsDuplicate(vector<int>& nums) { map<int,int>m; for(int i=0;i<nu......

**
**.....

.....

## class Solution { public: int singleNumber(vector<int>& nums) { vector<int>& n=nums; map<int,int>m; ......

**
**group anagarams....

-....

## class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<string>& s......

**
**bulls and cows....

-....

## class Solution { public: string getHint(string secret, string guess) { string s=secret; string g=guess; ......

**
**We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input : [1,3,2,2,5,2,3,7] ....

map and conditions....

## public: int findLHS(vector<int>& nums) { map<int,int> m; map<int,int>::iterator it; int an......

**
**Given a string s and a non-empty string p, find all the start indices of p s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of

iutput does not matter.

Example 1:

Input : s: "cbaebabacd" p:....

ARRAY OF SIZE 256....

## class Solution { public: vector<int> findAnagrams(string s, string p) { vector<int> pv(256,0); v......

**
**Given two arrays, write a function to compute their intersection.

Example 1:

Input : nums1 = [1,2,2,1], nums2 = [2,2]

Output : [2]....

USING FIND AND MAP....

## class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { ......

**
**Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input : pattern = "abba", str = "dog cat cat dog"

Output : true....

using dict and set....

## class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str ......

**
**no of primes....

traversing plays a major role.....

## class Solution { public: int countPrimes(int n) { if(n <= 1) return 0; if(n == 2) return 0; if(n ==......

**
**You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and positio....

MAP....

## class Solution { public: string getHint(string secret, string guess) { int i, A, B, len; A = B = 0; l......

**
**All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a D....

MAP....

## class Solution { public: map<string,int> m; vector<string> v; vector<string> findRepeatedDnaSequences(st......

**
**Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input :nums = [1,1,1], k = 2

Output : 2....

using map....

## class Solution { public: int subarraySum(vector<int>& nums, int k) { int rt=0, sum=0; map<int,in......

**
**Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same charac....

character array....

## class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}, n = s.size()......

**
**Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers,

iutput all of them with no order r....

MAP....

**
**Given two arrays, write a function to compute their intersection.....

MAP....

## class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<i......

**
**Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.
Left boundary is defined as the path from root to the left-most node. Right boundary is defined as t....

This question gives us a binary tree, let us output the boundaries of the tree in a counterclockwise order, in order of left, leaf, and right. The examples given in the title also give us a clear idea....

## class Solution { public: vector<int> boundaryOfBinaryTree(TreeNode* root) { if (!root) return {}; vector......

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

Check if the root node value is same as either p or q. If yes, return root node. Else search recursively left and right subtrees.....

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

Check if the root node is equal to first node or second node, then return root. Otherwise search recursively both left and right sub trees. if the result of both the recursive calls is not null, then ....

**
**Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
R....

The solution for finding if two trees are leaf similar....

## class Solution { public boolean leafSimilar(TreeNode root1, TreeNode root2) { List<Integer> root1Leaves = new ......

**
**Invert a tree.(Left becomes right and vice versa)....

Assign left pointer to right and right pointer to left. ....

**
**Find the diameter of the binary tree.....

Mark each diameter in variable sum and update it if it is lesser than current diameter. ....

**
**Given two roots, print if two trees are same or not....

If any one of node value doesn t match return false, in this way when you perform and operation final output will be false.....

**
**Find the maximum depth of the tree.....

Each node returns the max of its left, right added with 1(because of its own) to the calling element. ....

**
**Sum of leaf nodes in tree....

If a node is leaf node then add its value and return the output to the calling node.....

**
**Sum of elements in a tree....

Every node adds its value and returns output to calling node.....

**
**Count the number of leaf nodes....

Every leaf node adds 1 and returns the output to calling node.....

**
**Count the number of nodes in tree....

Every node adds 1 which will be returned to calling node.....

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

map....

## class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> m; a......

**
**The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this se....

MAP....

## class Solution { public: vector<int> findErrorNums(vector<int>& nums) { map<int,int> m; int r,......

**
**Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, re....

using substr....

## class Solution { public: string longestWord(vector<string>& words) { sort(words.begin(), words.end()); u......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

Using modulo and map....

## class Solution { public: bool isHappy(int n) { map<int,int> numbers; numbers[n]=1; int sum; ......

**
**Given a string, find the first non-repeating character in it and return it s index. If it doesn t exist, return -1.....

map....

## class Solution { public: int firstUniqChar(string s) { map<char,int> M; map<char, int> :: iterat......

**
**

Input : 1->2->3->4->5->NULL

Output : 5->4->3->2->1->NULL....

Iterative method. Comments in the code explain the logic pretty easily.....

**
**Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.....

check the map....

## class Solution { public: char findTheDifference(string s, string t) { map<char, int> M; char a; for......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

map is used....

## class Solution { public: int numJewelsInStones(string J, string S) { map<char,int> M; int count = 0; ......

**
**You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
....

check the top and side conditions.....

## class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int count = 0; for(int i=0;i......

**
**In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.....

by continuos division....

## class Solution { public: int numRabbits(vector<int>& answers) { map<int, int> M; map<int, int> :: it......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

calculate candies of unique occurance and compare with given size of vector.....

## class Solution { public: int distributeCandies(vector<int>& candies) { map<int,int> M; for......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

Based on distance and map value.....

## class Solution { public: int distance(pair <int,int> pair1, pair<int,int> pair2) { return (pair1.fi......

**
**Given two strings s and t , write a function to determine if t is an anagram of s.....

check the map condition....

## class Solution { public: bool isAnagram(string s, string t) { map<char,int> M1; map<char,i......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010.....

Count the no of even characters and check if any odd no of characters are available if available add 1 to result and for every odd character occurance add (odd-1) to result....

## class Solution { public: int longestPalindrome(string s) { map<char, int> M; map<char, int> :: iterato......

**
**Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use t....

Just by using two pointers, we can handle all other operations. Trivial. [Implementation]....

## class MyLinkedList { public: /** Initialize your data structure here. */ int size; ListNode *head; ListNod......

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9

Input : head = [4,5,1,9], node = 5

Output : [4,1,9]
Explanation: You are given the second no....

We actually replace the value of the node with the next node and point the next pointer to next to next element. if it was 1->2->3->4 and we were to delete 2, then we change the value at node 2 to....

## class Solution { public: void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node......

**
**valet parking system(Not valid between 12 to 1. ....

The space empty beginning from start will be the first to be filled and car will not be allowed in time 12 to 1....

## #include<stdio.h> #include<malloc.h> #include<iostream> using namespace std; struct node { int data; struc......

**
**design a playlist(in music player)which include all the function like queue next,play at the end ,shuffle the list and repeat the current song.....

queue next is insert in next position, play at end->insert at end, shuffle->play a random song, repeat->loop the current song.....

## #include<stdio.h> #include<malloc.h> #include<string.h> #include<stdlib.h> #include<iostream> using names......

**
**Add one variable in each node which tells its i)index from the first
ii)index from the last....

index_from_first indicates the index from start of linked list, and index_from_last indicates index starting from last of linked list.....

## #include<stdio.h> #include<malloc.h> #include<iostream> using namespace std; struct node { int data; int i......

**
**We are given head, the head node of a linked list containing unique integer values.....

Store all the values from vector in map. Traverse the list and check if the node s values is present in map ,then c++ and stop=false .If again next values are found in map and stop=false then cont....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
....

two pointer i.e slow and fast 1.Intially both points towards head. 2.update or traverse slow pointer by one node(i.e slow = slow.next) and fast pointer by two nodes(i.e fast=fast.next.next) 3.by th....

## class Solution { public ListNode middleNode(ListNode head) { ListNode slow=head; ListNode fast=head; w......

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.....

Firstly find length of list and if len>k then k=k%n; (because after n times rotation ,list will be same ) Now loop until(i<=k) (for rotating k times) and each time find end of loop and then append ....

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.
....

Firstly,find length of list ,if length>k then do k=k%n; Now,loop until i<=k (k times rotate) and each time find last node of list and point last node to first node and break its previous link.So.st....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
....

First compare initial value of both lists and make s point to the value which is smaller and store initial value of s in h. Now , take 2 pointers p and q and compare which value is smaller and mak....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.....

Take two pointers slow and fast. When slow will reach end of list then fast will reach at middle of list .....

**
**You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as show....

Here iterate over list and check if the particular node has child node then firstly store address of next node(of that particular node) in some pointer next and then connect child of this node as ne....

## /* // Definition for a Node. class Node { public: int val = NULL; Node* prev = NULL; Node* next = NULL; N......

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.....

traverse the list and delete the given value node by using prev and next pointer.....

**
**Reverse a singly linked list.....

Here reverse list using recursion. ....

**
**Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
....

same as linked list cycle(ii) problem....

**
**Write a program to find the node at which the intersection of two singly linked lists begins.
....

Find abs difference between length of two lists and then move that length forward in longer list.So ,from this point if we traverse till end,both list will have same length.Start traversing and check....

**
**Given a linked list, swap every two adjacent nodes and return its head.....

Here take one dummy at starting and set curr=dummy .Then iterate until curr->next ! =null and each time swap two nodes. ....

**
**Given a singly linked list, determine if it is a palindrome.....

Find middle of list using slow and fast and check if list is odd then remove middle number .Then reverse the two half lists and then check ,two lists are equal or not. ....

**
**Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.....

Make two list odd and even Find length of list and iterate over end of list and by checking i%2==0 or not,accordingly put ino even/odd list. Atlast ,connect both the lists.....

## class Solution { public: ListNode* oddEvenList(ListNode* head) { int n=0; ListNode* odd=new ListNode (1); ......

**
**Remove all elements from a linked list of integers that have value val.....

Iterate and check if the value is found then delete that value. One dummy node is made for easy deletion of head. Initially curr=dummy and iterate until curr->next!=NULL....

## class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head==NULL) { retur......

**
**Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the lin....

Take two pointers fast and slow with slow=slow->next and fast=fast->next->next . At one point(collison point) ,fast will be equal to slow. Then assign fast=head and then the distance between head to t....

## class Solution { public: ListNode *detectCycle(ListNode *head) { //the distance between head to the start of lo......

**
**Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.....

Take two lists more and less and then append values accordingly to the more/less lists....

## class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode *less=new ListNode(1); ......

**
**Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.....

here create one dummy node at starting so deletion of head is also easy.Then iterate to check until prev->next->val==curr->next->val....

## class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode *dummy=new ListNode(1); d......

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.
....

iterate over list and check if curr->val==curr->next->val then curr->next=next_next;(next to next of current) like if 1-1-1-2-3 then we need 1-2-3 so if first first time curr =curr->next->next then....

## class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* curr=head; ListNode*......

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

we need to reverse k nodes at a time. here , recursion is used. Firstly check k nodes are present in remeaining list or not,for this check until c!=k or temp!=null. so ,if temp==null means availabl....

## class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* curr=head,*prev=NULL,......

**
**Given a linked list, remove the n-th node from the end of list and return its head.....

we need to remove nth node from end of list ,here firstly finfd total length of list and then do L-n and we need to iterate L-n-1 times to reach the one node before the node to be deleted. ....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.....

We solve by the two pointer method. We take two pointers : slow and fast. Initially, both of them point towards the head. Then we traverse the linked list using these two pointers. The fast pointe....

## class Solution { public: ListNode* middleNode(ListNode* head) { ListNode *slow=head; ListNode *fast = head......

**
**reversing....

in this code we reverse the code....

## ** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ ......

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.....

discussed in class....

**
**We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.....

discussed in class....

## class Solution { public: int numComponents(ListNode* head, vector<int>& G) { if(head==NULL){ return 0;......

**
**Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts". ....

declare array of size k and decide no of elements each of pointer in vector can hold and accordingly add nodes ....

## class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { vector<ListNode*> v; ......

**
**You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.....

discussed in class....

## class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { l1=rev(l1); l2=rev(l2); ......

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.....

discussed in class....

**
**Reverse a singly linked list.....

discussed in class....

## class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) { ......

**
**You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list....

discussed in class....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example : ....

discussed in class....

**
**Given a linked list, determine if it has a cycle in it.....

discussed in class....

## class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) { return false; } ......

**
**Write a program to find the node at which the intersection of two singly linked lists begins.....

discussed in class....

**
**Given a linked list, swap every two adjacent nodes and return its head.....

discussed in class....

## class Solution { public: ListNode* swapPairs(ListNode* head) { if(head==NULL ||head->next==NULL) { ......

**
**Given a singly linked list, determine if it is a palindrome.....

discussed in class....

## class Solution { public: bool isPalindrome(ListNode* head) { bool res; if(head==NULL ||head->next=......

**
**Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.....

discussed in class....

**
**Remove all elements from a linked list of integers that have value val.....

discussed in class....

**
**Sort a linked list using insertion sort.....

same procedure as insertion sort....

## class Solution { public: ListNode* insertionSortList(ListNode* head) { if(head==NULL||head->next==NULL){ ......

**
**Given a singly linked list L: L0?L1??Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?....

find middle node,split list into 2 parts(after middle node),reverse second half and join one by one simultaneously....

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

.......

## class Solution { public: ListNode *detectCycle(ListNode *head) { bool cycle=false; ListNode *sptr=head,*fp......

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

same method as discussed in class....

**
**Remove Duplicates from Sorted List....

take two pointers curr,next(if their data are equal,delete next)and proceed in similar way....

## class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL ||head->next==NULL) { ......

**
**Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.....

same as leetcode 83 with slight changes....

## class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL||head->next==NULL) { ......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Exa....

---....

## class Solution { public int longestPalindrome(String s) { if ( s == null || s.length() == 0 ){ return 0; } ......

**
**Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading z....

Linked list. ....

## // LINKED LIST class Solution { public: ListNode* helperFunc(ListNode* head, ListNode** req) { if(head == NULL......

**
**Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.....

Linked list....

## /** LINKED LIST * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ......

**
**Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.....

Linked list.....

**
**Given a linked list, swap every two adjacent nodes and return its head.....

Linked list....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.....

Linked list. ....

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following: 4 -> 5 -> 1 -> 9....

Linked list problem. ....

**
**You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the nu....

Storing each bit in node in linked list and reversing both numbers and adding it. ....

**
**Reverse a singly linked list.....

Using recursion....

**
**Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.....

Map is used. ....

## class Solution { public: char findTheDifference(string s, string t) { map<char, int> alpha; for(int i=0;......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

Map is used. ....

**
**All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a D....

Map is used. ....

## class Solution { public: vector<string> findRepeatedDnaSequences(string s) { string substring = "a"; str......

**
**Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops e....

Map is used. ....

## class Solution { public: bool isHappy(int n) { map<int,int> numbers; int sum = 0; numbers[n] = 1; ......

**
**You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
....

Map is used.....

## class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int peri = 0; for(int it=0;i......

**
**Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.....

Map is used. ....

## class Solution { public: int findMaxLength(vector<int>& nums) { int result = 0, sze= nums.size(),sum = 0; ......

**
**You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and positio....

map is used. ....

## class Solution { public: string getHint(string secret, string guess) { int bull = 0,cows = 0; map<char,......

**
**Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input : 4->2->1->3

Output : 1->2->3->4

Example 2:

Input : -1->5->3->4->0

Output : -1->0->3->4->5....

Merge sort is applied . First of all the middle node of the list is found and then head and middle is send to merge procedure for making the list. ....

## class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; ......

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input : 1->2->3->4->5->NULL, k = 2

Output : 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2: Inp....

prelen computation is the main thing to look forward in this problem. prelen = len - k; But problem with this is in case the length is smaller than the k (rotation number) then this will fail ,....

**
**Given a singly linked list L: L0?L1??Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?
You may not modify the values in the list s nodes, only nodes itself may be changed.

Example 1: Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2: Given 1->2->3->4->5, reorder it to 1->5->2->4->3.....

The main logic here is to reverse second half of the list and then merge the first half and reversed second half. ....

**
**Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example 1: ....

The procedure is in place evenfirst pointer is for maintaining first even node , no alteration is done on it. In the loop We check whether list has ended or not so check even pointer and....

**
**Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 ? a2
?
c1 ? c2 ? c3
?
B: b1 ? b2 ? b3
begin to intersect a....

getCount() procedure is for finding length of linked list. getIntersectionNode() procedure is for finding the longer list s node(say helper node) from where length of both list become equal. retur....

**
**Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input : h....

Applying Flloyd cycle detection algorithm. ....

**
**Remove all elements from a linked list of integers that have value val.

Example :

Input : 1->2->6->3->4->5->6, val = 6

Output : 1->2->3->4->5....

My code is divided into three parts: 1. Populating the vector with node s values not equal to given val. 2. Checking that vector is not empty . 3. Creating a new linked list with the elements of ve....

**
**Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input : 1->1->2

Output : 1->2

Example 2:

Input : 1->1->2->3->3

Output : 1->2->3....

Sorted linked list will have duplicates in continuation so we need to check current node and it s next node s value , so at every iteration two cases arises either 1. same value or 2. not same value....

**
**Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example :

Input : 1->2->4, 1->3->4

Output : 1->1->2->3->4->4 ....

Using the concept of merge sort algorithm . 1.Comparing the current node s value of both lists and assigning the result of recursion to list having current node s value smaller than other , as it ....

**
**Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9
Note:
The linked list will have at least two elements.
All of the nodes values will be un....

The following logic is correct because here node is given as input parameter , otherwise in case of input as value of node we need to iterate nodes one by one maintaining prev node as well. Store t....

**
**

Input : 1->2->3->4->5->NULL

Output : 5->4->3->2->1->NULL
....

Iterative approach Starting with the first conditional check , i.e whether list is empty or having a single node is already reversed. Taking three variable curr(current node), prev(previous node) ....

**
**Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
....

Main idea is from "Floyd Cycle Detection Algorithm" , running two pointers , fast and slow , where fast increments two nodes while slow just one . Two cases arise here depending on length of LL....

**
**delete at a given position....

-....

## #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; struct node *newnode(int n){......

**
**finding min,max....

-....

**
**inserting at kth position....

-....

**
**insert node at end....

-....

**
**insert node at beginning....

-....

**
**Given a linked list, rotate the list to the right by k places, where k is non-negative.....

HINT:finding new head in list after rotating list to right by k positions....

**
**....

using 2nd approach discussed in class....

**
**A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that s why they ask you to help. You re suggested to implement the prototype of site registration system. The system should work on the fo....

We first check if the string is present in the map or nor. If it is not present then we just do cout << s; After this we increment the value of the string in the map. For example: ----------- S....

## #include < bits/stdc++.h > using namespace std; int main(){ int t; cin >> t; map < string,int > m; for (int i=......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

So, we are given an even number of candies. Now, the sister should get maximum kind of varieties. We now, create a map with number and its frequency. A different number here means a different flavour....

## class Solution { public: int distributeCandies(vector < int > & candies) { map < int, int > m; for ( i......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

**
**Given two strings s and t , write a function to determine if t is an anagram of s.

Input :
s = "anagram",
t = "nagaram"

Output : true....

We create two maps m1 and m2 from each string and if m1 is equal to m2, then we say that they are anagrams.
map

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Input : [2,2,1]

Output : 1....

Direct application of map and using an iterator. Given a non-empty array of integers, every element appears twice except for one. Find that single one. ....

## class Solution { public: int singleNumber(vector<int>& v) { map <int, int> m; int a; for (int i=0; i&l......

**
**Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.....

Process: We first sort the two strings in alphabetical order by the sort() method. Then we traverse through the string s looking for matching the character in string t. When there is a mismatch then ,....

## class Solution { public: char findTheDifference(string s, string t) { sort( s.begin(),s.end() ); sort......

**
**In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.....

Process: We keep the track of all elements into a map and then increment each key by one to check the total number of rabbits which are of a particular color. Let us take a = [1,1,1,2,3] as an exam....

## class Solution { public: int numRabbits(vector<int>& answers) { map <int, int> m; for (int i=0; i< answ......

**
**You re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J a....

We firstly create a map of all the characters in J .they all are unique to the initial values are 1.Then next we traverse through each character of the string S, by checking in the map. Next, if we fi....

## class Solution { public: int numJewelsInStones(string J, string S) { map <char,int> m; int count = 0; ......

**
**/*
using map to store each value in a list an then checking if that value is already present in the map then delete that node.
*/
....

....

## #include <iostream> using namespace std; #include <cstdlib> #include <map> #include <algorithm> struct no......

**
**/* print values located at position which is multiple of given k.
traverse and check if (position % k ==0 ) then print that vlaue else continue traversing.
*/
....

....

## #include <iostream> using namespace std; #include <cstdlib> struct node{ int data; struct node *next; ......

**
**/* finding max and min in a list
using brute-force normal method.
store first node value in max/min and then compare each value with list to that valueto find maximumn/minimum in whole list.
*/
....

....

## #include <iostream> using namespace std; #include <stdlib.h> struct node { int data; struct node* next; ......

**
**....

....

**
**/* deletion in singly-linked list
1.deletion at beginning: take a temp =head and then store head=head->next and free(temp)
and now is pointing to old 2nd node.
2. deletion at end:
take prev pointer also and move upto last node(temp->next!=null) and then do prev->next=NULL and free(temp)
3.d....

....

**
**/*
insertion in a single linked list
1.I am creating a node using createnode function and passing value to be aaded into the linked list in the createnode() .
In createnode(), one node is created and its address is stored in struct node* temp and this temp is returned.So ,linked list is rea....

....

## #include <iostream> using namespace std; #include <stdlib.h> struct node { int data; struct node* next;......

**
**Write a program for printing the following in a given linked list:
a. maximum
b. minimum
c. maximum minimum....

....

**
**For a given singly linked list delete a node:
a. at the beginning b.
at the end
c.at a given position k

Input :
k = 3
1 -> 2 -> 5 -> 7 -> 4 -> NULL

Output :
2 -> 5 -> 7 -> 4 -> NULL
1 -> 2 -> 5 -> 7 -> NULL
1 -> 2 -> 7 -> 4 -> NULL....

....

**
**For a given singly linked list insert a node:
a.at the beginning
b.at the end
c.at a given position k

Input :
value=8, k=4
1 -> 2 -> 5 -> 7-> 4 -> NULL

Output :
8 -> 1 -> 2 -> 5 -> 7 -> 4 -> NULL
1 -> 2 -> 5 -> 7 -> 4 -> 8 -> NULL
1 -> 2 -> 5 -> 8 -> 7 -> 4 -> NULL....

....

**
**There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty.

Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0

Example 2: nu....

This question allows us to ask for the median of two ordered arrays, and limits the time complexity to O (m+n), and to see the complexity of the time, it is natural to think that the dichotomy should ....

## class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nu......

**
**To find min,max in linked list....

Only fns are written ,return type is int(revised)....

## //question5 //a.)max int max(Node *head) { int maxm=head->data; Node *ptr=head; while(ptr!=NULL) { i......

**
**To delete node at start,end ,kth position....

only fns are written with return type Node *....

## // question 2 //a.)deletion at start Node *del_at_start(Node *head,int val) { if(head!=NULL) { Node *tmp......

**
**To insert a node at start,end,kth position....

only functions are written with return type Node *....

## //question 1 //a.)insertion at start Node *insert_at_start(Node *head,int val) { Node *tmp=(Node *)malloc(sizeof......

**
**In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.....

With example know relation between it->first and it->second....

## class Solution { public: int numRabbits(vector<int>& answers) { map<int, int> rabbit; map<int, int>......

**
**Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the ....

Calculate number of candies and candy types and work on it.....

**
**Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.....

Use concept of filling from highest to lowest....

## class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { auto......

**
**Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.....

Check count of even characters in string. Check if string length is even or odd.....

## class Solution { public: int longestPalindrome(string s) { map<char, int> M; map<char, int> :: iterat......

**
**An anagram is produced by rearranging the letters of ss into tt. Therefore, if tt is an anagram of ss, sorting both strings will result in two identical strings. Furthermore, if ss and tt have different lengths, tt must not be an anagram of ss and we can return early.....

Check length.Also use maps and compare characters in both strings.....

## class Solution { public: bool isAnagram(string s, string t) { map<char, int> M; map<char, int> :: iter......

**
**Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?....

Use map and clear map after using it.....

## class Solution { public: int singleNumber(vector<int>& nums) { map <int, int> m; map <int, int......

**
**Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordi....

np2 = n*(n-1). If distance matches then increment count and perform n*(n-1)....

## class Solution { public: int getDist(pair <int, int> PAIR1, pair<int, int> PAIR2) { return (PAIR1.first-PAI......

**
**There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is ....

If bricks size is 1,2,1 then have map as 1,1+2,1+2+1. then you will know which location has gap. then you can traverse and find the most repeated element in all horizontal locations of wall.....

## class Solution { public: int leastBricks(vector<vector<int>>& wall) { map<int, int> ele; map<int, ......

**
**Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each

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

Example : Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1....

index....

## class Solution { public: vector twoSum(vector& nums, int target) { unordered_map m; vector res; for (......

**
**Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input : "babad"

Output : "bab" Note: "aba" is also a valid answer.

Example 2:

Input : "cbbd"

Output : "bb"....

This question makes us ask for the longest palindrome string, first of all, what is the palindrome string, is the same string that is reading the reverse reading, such as "Bob", "Level", "noon" and so....

## class Solution { public: string longestPalindrome(string s) { if (s.size() < 2) return s; int n = s.size......

**
**There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.

Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0

Example 2:....

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

Example s: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that ....

The question of the longest, non-repetitive substring is very similar to that of the previous isomorphic Strings, which belongs to the Early Classic topic of Leetcode, and the blogger thinks it can be....

## class Solution { public: int lengthOfLongestSubstring(string s) { int m[256] = {0}, res = 0, left = 0; for......

**
**You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input : (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output : 7 -> 0 -> 8....

This is not a difficult problem, the algorithm is very simple, the data type of the linked list is not difficult. is to create a new list, and then the input of the two linked list from the beginning,....

## class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *res = new ListNode(-1)......