#### Submission in last 7 days

##### (2)

Leetcode.872 Leaf-Similar Trees

###### Auther:-subhojit_rb

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....

Trees....

```
class Solution {
public:
vector<int> t1,t2;
bool leafSimilar(TreeNode* root1, TreeNode* root2) {

lea......

```

Leetcode.98 Validate Binary Search Tree

###### Auther:-subhojit_rb

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. Both the lef....

Trees....

```
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
vector<int......

```

Leetcode.938 Range Sum of BST

###### Auther:-subhojit_rb

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values.

```Example  1:

Input : root = [10,5,15,3,7,null,18], L = 7, R = 15
Output : 32
```
```Example  2:

Input : root = ....
```

Trees....

```
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root==NULL)
return 0;
i......

```

Leetcode.965 Univalued Binary Tree

###### Auther:-subhojit_rb

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.

```Example  1:

Input : [1,1,1,1,1,null,1]
Output : true
```
```Example  2:

Input : [2,2,2,5,2]
Output : false

Note:

The number of nodes in the given tree ....
```

Trees....

```
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if(root==NULL||(root->left==NULL&&root->right==NUL......

```

Leetcode.257 Binary Tree Paths

###### Auther:-subhojit_rb

Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children.

```Example :

Input :

1
/
2     3

5

Output : ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3....
```

Trees....

```
class Solution {
public:

vector<string> binaryTreePaths(TreeNode* root) {

vector<string> S;
......

```

Leetcode.113 Path Sum II

###### Auther:-subhojit_rb

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.

```Example :

Given the below binary tree and sum = 22,

5
/
4   8
/   /
11  13  4
/      /
7    2  5   1
Return:

[
....
```

.....

```
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> a;
vecto......

```

LEETCODE.781 Rabbit in forest

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
map<int,int> umap;

for(int i=0;i<an......

```

LEETCODE.725 Split link list in parts

###### Auther:-SUBHAM543

This problem is related to linklist....

This problem is related to linklist....

```
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {

```

LEETCODE.718 Maximum length of repeated subarray

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int m=A.size();
int n=B.size......

```

LEETCODE.560 Subarray sum equals k

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
map<int,int> umap;
int t=0;
......

```

LEETCODE.557 Reverse word in string

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
string reverseWords(string s) {

string word = "";
string finalString="";
......

```

LEETCODE.554 Brick Wall

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
map<int,int> umap;
for(int i=0......

```

LEETCODE.49 Group Anagrams

###### Auther:-SUBHAM543

This problem is related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:
vector<vector<string> > groupAnagrams(vector<string>& strs) {
vector<vector<......

```

LEETCODE.347 Top K frequent element

###### Auther:-SUBHAM543

This problem was related to HashMap....

This problem is related to HashMap....

```
class Solution {
public:

static int indesc(const pair<int,int> &a,
const pair<int,int> &b)
{
r......

```

LEETCODE.299 Bulls and Cows

###### Auther:-SUBHAM543

Problem 299. Bulls and Cows....

This problem was for HashMap....

```
class Solution {
public:
string getHint(string secret, string guess) {

map<char,int> umap;
int bulls=0......

```

leetcode.111 Minimum Depth of Binary Tree

###### Auther:-M10

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
/
....
```

....

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

```

leetcode.104 Maximum Depth of Binary Tree

###### Auther:-M10

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.

```Example :

Given binary tree [3,9,20,null,null,15,7],

3
/
9  20
/
....
```

....

```
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)return 0;
else
return 1+max(ma......

```

leetcode.100 Same tree

###### Auther:-M10

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]....
```

....

```
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL)return true;
el......

```

leetcode.226 Invert Binary Tree

###### Auther:-M10

Invert a binary tree.

```Example :

Input :

4
/
2     7
/    /
1   3 6   9
Output :

4
/
7     2
/    /
9   6 3   1....
```

....

```
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)return NULL;
TreeNode *temp=......

```

leetcode.235 LCA

###### Auther:-M10

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 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....

....

```
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NU......

```

Leetcode.111 Min Depth of Binary Tree

###### Auther:-subhojit_rb

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
/
....
```

.....

```
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL)
return 0;
int x=minDepth(roo......

```

Leetcode.112 Path Sum

###### Auther:-subhojit_rb

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;
if......

```

Leetcode.226 Invert Binary Tree

###### Auther:-subhojit_rb

Invert a binary tree.

```Example :

Input :

4
/
2     7
/    /
1   3 6   9
Output :

4
/
7     2
/    /
9   6 3   1....
```

.....

```
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)
return NULL;
TreeNod......

```

Leetcode.404 Sum of Left leaves

###### Auther:-subhojit_rb

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.....
```

.....

```
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL)
return 0;
int sum=0;
......

```

Leetcode.101 Symmetric Tree

###### Auther:-subhojit_rb

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....

.....

```
class Solution {
public:
bool isSymmetric(TreeNode* root) {

return equals(root,root);

}
bool ......

```

Leetcode.104 Max Depth of Binary Tree

###### Auther:-subhojit_rb

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.

```Example :

Given binary tree [3,9,20,null,null,15,7],

3
/
9  20
/
....
```

.....

```
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
return 1+max(maxDe......

```

Leetcode.110 Balanced Binary Tree

###### Auther:-subhojit_rb

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
....
```

.....

```
class Solution {
public:
bool isBalanced(TreeNode* root) {

if(root==NULL)
return true;
if(......

```

Leetcode.100 Same Tree

###### Auther:-subhojit_rb

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]....
```

.....

```
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
......

```

Leetcode.anc666 86

###### Auther:-anc666

Partition List....

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.....

```
class Solution {
public ListNode partition(ListNode head, int x) {

// before and after are the two pointers us......

```

Rakesh.anc666 325

###### Auther:-anc666

Put the odd nodes in a linked list and the even nodes in another. Then link the evenList to the tail of the oddList.....

```
public class Solution {
if (head == null) return null;
ListNod......

```

Rakesh.anc666 83

###### Auther:-anc666

Remove Duplicates from Sorted List....

Remove Duplicates from Sorted List....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Rakesh.anc666 237

###### Auther:-anc666

237. Delete Node in a Linked List....

237. Delete Node in a Linked List....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Rakesh.anc666 206

###### Auther:-anc666

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

leetcode.993 cousins in a binary tree

###### Auther:-charank07

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......

```

leetcode.637 average of levels of tree

###### Auther:-charank07

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;

......

```

leetcode.669 trim a bst

###### Auther:-charank07

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;
......

```

Leetcode.palleramkashyap 575. Distribute Candies

###### Auther:-palleramkashyap@gmail.com

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;
......

```

Leetcode.palleramkashyap 242. Valid Anagram

###### Auther:-palleramkashyap@gmail.com

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.

What if ....
```

Map....

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

```

Leetcode.palleramkashyap 202. Happy Number

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 409. Longest Palindrome

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 350. Intersection of Two Arrays II

###### Auther:-palleramkashyap@gmail.com

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;......

```

Leetcode.palleramkashyap 594. Longest Harmonious Subsequence

###### Auther:-palleramkashyap@gmail.com

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;

......

```

Leetcode.palleramkashyap 1. Two Sum

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 599. Minimum Index Sum of Two Lists

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 645. Set Mismatch

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 447. Number of Boomerangs

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 771. Jewels and Stones

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.palleramkashyap 500. Keyboard Row

###### Auther:-palleramkashyap@gmail.com

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 :

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;
......

```

Leetcode.palleramkashyap 720. Longest Word in Dictionary

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.202 Happy Number

###### Auther:-subhojit_rb

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;
......

```

Leetcode.720 Longest Word in Dictionary

###### Auther:-subhojit_rb

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< ......

```

Leetcode.palleramkashyap 387. First Unique Character in a String

###### Auther:-palleramkashyap@gmail.com

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)
{
......

```

Leetcode.palleramkashyap 349. Intersection of Two Arrays

###### Auther:-palleramkashyap@gmail.com

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......

```

Leetcode.645 Set Mismatch

###### Auther:-subhojit_rb

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......

```

Leetcode.771 Jewels and Stones

###### Auther:-subhojit_rb

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)
......

```

Leetcode.500 Keyboard Row

###### Auther:-subhojit_rb

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 :

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......

```

Leetcode.575 Distribute Candies

###### Auther:-subhojit_rb

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......

```

Leetcode.594 Longest Harmonious Subsequence

###### Auther:-subhojit_rb

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 ......

```

Leetcode.599 Minimum Index Sum of Two Lists

###### Auther:-subhojit_rb

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......

```

Leetcode.409 Longest Palindrome

###### Auther:-subhojit_rb

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......

```

Leetcode.387 First Unique Character in a String

###### Auther:-subhojit_rb

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]+......

```

Leetcode.350 Intersection of Two Arrays II

###### Auther:-subhojit_rb

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,......

```

Leetcode.349 Intersection of Two Arrays

###### Auther:-subhojit_rb

```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....

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

map<i......

```

Leetcode.242. Valid Anagram

###### Auther:-subhojit_rb

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(......

```

Leetcode.1 Two Sum

###### Auther:-subhojit_rb

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;
......

```

LEETCODE.70 Climbing Stairs

###### Auther:-Tharun_kumar

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[......

```

LEETCODE.746 Min Cost Climbing Stairs

###### Auther:-Tharun_kumar

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 ==......

```

LEETCODE.198 House Robber

###### Auther:-Tharun_kumar

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......

```

leetcode.53 DP Maximum Subarray

###### Auther:-i_m_arj

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();
......

```

leetcode.53 DP House Robber

###### Auther:-i_m_arj

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[......

```

leetcode.638 DP Shopping Offers

###### Auther:-i_m_arj

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<......

```

leetcode.983 DP Minimum Cost For Tickets

###### Auther:-i_m_arj

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=......

```

leetcode.931 DP Minimum Falling Path Sum

###### Auther:-i_m_arj

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......

```

leetcode.877 DP Stone Game

###### Auther:-i_m_arj

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......

```

leetcode.338 DP Counting Bits

###### Auther:-i_m_arj

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]

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......

```

Leetcode.53 Maximum Subarray

###### Auther:-grv0908

dp....

dp....

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

int currSum = 0;
......

```

Leetcode.70 Climbing Stairs

###### Auther:-grv0908

dp....

dp....

```
class Solution {
public int climbStairs(int n) {

if(n == 0)
return 0;
else if(n == 1)
r......

```

Leetcode.198 House Robber

###### Auther:-grv0908

Dp....

dp....

```
class Solution {
public int rob(int[] nums) {
int max = 0;

if(nums.length == 0)
return max;
......

```

LEETCODE.70 Climbing Stairs

###### Auther:-Tharun_kumar

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[......

```

leetcode.283 Move Zeroes

###### Auther:-bharatparakh

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;
......

```

leetcode.268 Missing Number

###### Auther:-bharatparakh

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)
{
......

```

leetcode.238 Product of Array Except Self

###### Auther:-bharatparakh

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();

......

```

leetcode.219 Contains Duplicate II

###### Auther:-bharatparakh

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<......

```

leetcode.217 Contains Duplicate

###### Auther:-bharatparakh

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;......

```

leetcode.216 Combination Sum III

###### Auther:-bharatparakh

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......

```

leetcode.189 Rotate Array

###### Auther:-bharatparakh

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];
......

```

leetcode.167 Two Sum II - Input array is sorted

###### Auther:-bharatparakh

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;
......

```

leetcode.162 Find Peak Element

###### Auther:-bharatparakh

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;
......

```

leetcode.153 Find Minimum in Rotated Sorted Array

###### Auther:-bharatparakh

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......

```

leetcode.122 Best Time to Buy and Sell Stock II

###### Auther:-bharatparakh

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......

```

leetcode.88 Merge Sorted Array

###### Auther:-bharatparakh

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......

```

leetcode.80 Remove Duplicates from Sorted Array II

###### Auther:-bharatparakh

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();
......

```

leetcode.78 Subsets

###### Auther:-bharatparakh

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) {
......

```

leetcode.75 Sort Colors

###### Auther:-bharatparakh

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......

```

leetcode.66 Plus One

###### Auther:-bharatparakh

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......

```

leetcode.62 Unique Paths

###### Auther:-bharatparakh

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......

```

leetcode.53 Maximum Subarray

###### Auther:-bharatparakh

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......

```

leetcode.35 Search Insert Position

###### Auther:-bharatparakh

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+......

```

leetcode.27 Remove Element

###### Auther:-bharatparakh

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)
{......

```

leetcode.16 3Sum Closest

###### Auther:-bharatparakh

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(......

```

leetcode.1 Two Sum

###### Auther:-bharatparakh

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......

```

LEETCODE.442 Find All Duplicates in an Array

###### Auther:-Tharun_kumar

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 ......

```

LEETCODE.746 Min Cost Climbing Stairs

###### Auther:-Tharun_kumar

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++) {
......

```

LEETCODE.873 Length of Longest Fibonacci Subsequence

###### Auther:-Tharun_kumar

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()......

```

LEETCODE.153 Find Minimum in Rotated Sorted Array

###### Auther:-Tharun_kumar

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(......

```

LEETCODE.16 3Sum Closest

###### Auther:-Tharun_kumar

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());......

```

LEETCODE.75 Sort Colors

###### Auther:-Tharun_kumar

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 = ......

```

LEETCODE.162 Find Peak Element

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.80 Remove Duplicates from Sorted Array II

###### Auther:-Tharun_kumar

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......

```

LEETCODE.670 Maximum Swap

###### Auther:-Tharun_kumar

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......

```

LEETCODE.62 Unique Paths

###### Auther:-Tharun_kumar

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......

```

LEETCODE.287 Find the Duplicate Number

###### Auther:-Tharun_kumar

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[......

```

LEETCODE.667 Beautiful Arrangement II

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.495 Teemo Attacking

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.414 Third Maximum Number

###### Auther:-Tharun_kumar

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_......

```

LEETCODE.189 Rotate Array

###### Auther:-Tharun_kumar

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)
......

```

LEETCODE.581 Shortest Unsorted Continuous Subarray

###### Auther:-Tharun_kumar

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......

```

leetcode.204 count primes

###### Auther:-mn265

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;
......

```

leetcode.290 word pattern

###### Auther:-mn265

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......

```

Assignment SPOJ.3 BABTWR - Tower of Babylon

###### Auther:-i_m_arj

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......

```

Assignment SPOJ.2 BRIDGES

###### Auther:-i_m_arj

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){......

```

leetcode.287 Array Find the Duplicate Number

###### Auther:-i_m_arj

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......

```

leetcode.670 Array Maximum Swap

###### Auther:-i_m_arj

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);
......

```

leetcode.80 Array Remove Duplicates from Sorted Array II

###### Auther:-i_m_arj

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......

```

leetcode.162 Array Find Peak Element

###### Auther:-i_m_arj

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......

```

Assignment.1 DP Rod Cutting Problem

###### Auther:-i_m_arj

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]......

```

Leetcode.300 Longest increasing subsequency

###### Auther:-grv0908

dp....

dp....

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

```

Leetcode.45 Jump Game 2

###### Auther:-grv0908

Dp....

DP....

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

for(i......

```

leetcode.70 DP Climbing Stairs

###### Auther:-i_m_arj

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......

```

leetcode.673 DP Number of Longest Increasing Subsequence

###### Auther:-i_m_arj

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......

```

Leetcode.162 Find Peak Element

###### Auther:-grv0908

Binary Search ....

Array....

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

int s......

```

leetcode .219 contailns duplicate

###### Auther:-mn265

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......

```

Leetcode.7`8 Maximum Len of repeated subarray

###### Auther:-grv0908

Array....

Array....

```
class Solution {
public int findLength(int[] A, int[] B) {

int[][] matrix = new int[A.length + 1][B.length......

```

Leetcode.55 Jump Game

###### Auther:-grv0908

Array....

Array....

```
class Solution {
public boolean canJump(int[] nums) {
int reached = 0;

int i = 0;

while(i ......

```

leetcode.75 Array Sort Colors

###### Auther:-i_m_arj

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<=......

```

leetcode.153 Array Find Minimum in Rotated Sorted Array

###### Auther:-i_m_arj

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......

```

leetcode.873 Array Length of Longest Fibonacci Subsequence

###### Auther:-i_m_arj

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......

```

LEETCODE.605 Can Place Flowers

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.219 Contains Duplicate II

###### Auther:-Tharun_kumar

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......

```

LEETCODE.88 Merge Sorted Array

###### Auther:-Tharun_kumar

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.......

```

LEETCODE.643 Maximum Average Subarray I

###### Auther:-Tharun_kumar

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......

```

LEETCODE.26 Remove Duplicates from Sorted Array

###### Auther:-Tharun_kumar

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();......

```

LEETCODE.747 Largest Number At Least Twice of Others

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.35 Search Insert Position

###### Auther:-Tharun_kumar

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++) {......

```

LEETCODE.724 Find Pivot Index

###### Auther:-Tharun_kumar

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+......

```

LEETCODE.1 Two Sum

###### Auther:-Tharun_kumar

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......

```

leetcode.62 Array Unique Paths

###### Auther:-i_m_arj

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(......

```

LEETCODE.53 Maximum Subarray

###### Auther:-Tharun_kumar

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<......

```

LEETCODE.27 Remove Element

###### Auther:-Tharun_kumar

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.......

```

LEETCODE.697 Degree of an Array

###### Auther:-Tharun_kumar

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......

```

LEETCODE.167 Two Sum II - Input array is sorted

###### Auther:-Tharun_kumar

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......

```

LEETCODE.448 Find All Numbers Disappeared in an Array

###### Auther:-Tharun_kumar

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......

```

LEETCODE.283 Move Zeroes

###### Auther:-Tharun_kumar

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++......

```

LEETCODE.485 Max Consecutive Ones

###### Auther:-Tharun_kumar

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;
......

```

Leetcode.62 Unique Path

###### Auther:-grv0908

Array....

Array....

```
class Solution {
public int uniquePaths(int m, int n) {
int[][] matrix = new int[m][n];

for(int i = 0......

```

Leetcode.55 Jump Game

###### Auther:-grv0908

Array....

Array....

```
class Solution {
public boolean canJump(int[] nums) {
int max = 0;

for(int i = 0; i<nums.length; i+......

```

leetcode.1 two sum

###### Auther:-mn265

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......

```

Leetcode.543 Diameter of Binary Tree

###### Auther:-grv0908

Diameter of BT....

Tree....

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

```

leetcode.414 Array Third Maximum Number

###### Auther:-i_m_arj

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......

```

leetcode.581 Array Shortest Unsorted Continuous Subarray

###### Auther:-i_m_arj

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......

```

leetcode.55 Array Jump Game

###### Auther:-i_m_arj

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......

```

leetcode.667 Array Beautiful Arrangement II

###### Auther:-i_m_arj

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>......

```

Leetcode.124 Maximum sum path

###### Auther:-grv0908

tree....

Tree....

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

```

leetcode.495 Array Teemo Attacking

###### Auther:-i_m_arj

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......

```

leetcode.238 String Product of Array Except Self

###### Auther:-i_m_arj

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();
......

```

leetcode.442 Array Find All Duplicates in an Array

###### Auther:-i_m_arj

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......

```

Leetcode.532 K difference pair

###### Auther:-grv0908

Array....

Array....

```
class Solution {
public int findPairs(int[] nums, int k) {

if(nums.length == 0 || k < 0)
return 0......

```

Leetcode.581 Shortest unsortest subarray

###### Auther:-grv0908

array....

array....

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

```

Leetcode.605 Can place flowers

###### Auther:-grv0908

Array....

Array....

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

```

Leetcode.219 Contains duplication

###### Auther:-grv0908

array....

contains duplicate 2....

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

```

Leetcode.88 Merge Sorted array

###### Auther:-grv0908

Merge sorted array....

Array....

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

i......

```

leetcode.532 Array K-diff Pairs in an Array

###### Auther:-i_m_arj

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) ......

```

leetcode.605 Array Can Place Flowers

###### Auther:-i_m_arj

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();
......

```

leetcode.88 Array Merge Sorted Array

###### Auther:-i_m_arj

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;
......

```

leetcode.230 BST Kth Smallest Element in a BST

###### Auther:-i_m_arj

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......

```

leetcode.165 String Compare Version Numbers

###### Auther:-i_m_arj

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......

```

leetcode.48 String Multiply Strings

###### Auther:-i_m_arj

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......

```

leetcode.890 String Find and Replace Pattern

###### Auther:-i_m_arj

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......

```

leetcode.38 String Count and Say

###### Auther:-i_m_arj

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(......

```

leetcode.459 String Repeated Substring Pattern

###### Auther:-i_m_arj

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......

```

leetcode.151 String Reverse Words in a String

###### Auther:-i_m_arj

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"
```

.....

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

```

leetcode.26 Array Remove Duplicates from Sorted Array

###### Auther:-i_m_arj

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......

```

leetcode.643 Array Maximum Average Subarray I

###### Auther:-i_m_arj

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......

```

leetcode.747 Array Largest Number At Least Twice of Others

###### Auther:-i_m_arj

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......

```

leetcode.35 Array Search Insert Position

###### Auther:-i_m_arj

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=......

```

leetcode.724 Array Find Pivot Index

###### Auther:-i_m_arj

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;
......

```

leetcode.53 Array Maximum Subarray

###### Auther:-i_m_arj

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();
......

```

LEETCODE.125 Valid Palindrome

###### Auther:-Tharun_kumar

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......

```

###### Auther:-Tharun_kumar

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......

```

LEETCODE.537 Complex Number Multiplication

###### Auther:-Tharun_kumar

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......

```

LEETCODE.890 Find and Replace Pattern

###### Auther:-Tharun_kumar

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......

```

LEETCODE.383 Ransom Note

###### Auther:-Tharun_kumar

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......

```

LEETCODE.678 Valid Parenthesis String

###### Auther:-Tharun_kumar

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......

```

LEETCODE.686 Repeated String Match

###### Auther:-Tharun_kumar

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;

......

```

LEETCODE.65 Valid Number

###### Auther:-Tharun_kumar

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......

```

LEETCODE.680 Valid Palindrome II

###### Auther:-Tharun_kumar

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) {
......

```

Leetcode.448 Find all numbers disappeared in array

###### Auther:-grv0908

.....

Array....

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

```

Leetcode.283 Move Zeroes

###### Auther:-grv0908

Move Zeroes....

Arrays....

```
class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
int j = 0;

while(j < nums.len......

```

Leetcode.485 Maximum Consecutive Ones

###### Auther:-grv0908

Max. consecutive ones....

Array....

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

......

```

leetcode.746 Min Cost Climbing Stairs

###### Auther:-i_m_arj

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[......

```

leetcode.66 Array Plus One

###### Auther:-i_m_arj

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......

```

leetcode.27 Array Remove Element

###### Auther:-i_m_arj

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) {

......

```

leetcode.268 Array Missing Number

###### Auther:-i_m_arj

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......

```

leetcode.697 Array Degree of an Array

###### Auther:-i_m_arj

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;
......

```

leetcode.167 ARray Two Sum II - Input array is sorted

###### Auther:-i_m_arj

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......

```

leetcode.448 Array Find All Numbers Disappeared in an Array

###### Auther:-i_m_arj

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();
......

```

leetcode.283 Array Move Zeroes

###### Auther:-i_m_arj

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......

```

leetcode.485 Array Max Consecutive Ones

###### Auther:-i_m_arj

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......

```

Leetcode.554 Brick Wall

###### Auther:-Learnerforever

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......

```

Leetcode.781 Rabbits in Forest

###### Auther:-Learnerforever

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:
unordered_map<int,double> num;
for(aut......

```

Leetcode.451 Sort Characters By Frequency

###### Auther:-Learnerforever

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)
......

```

leetcode.214 String Shortest Palindrome

###### Auther:-i_m_arj

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();
......

```

leetcode .205 Isomorphic Strings

###### Auther:-mn265

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......

```

Leetcode.447 Number of Boomerang

###### Auther:-grv0908

Number of Boomerang....

Map....

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

```

leetcode.32 Longest Valid Parentheses

###### Auther:-bharatparakh

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;
......

```

leetcode.32 String Longest Valid Parentheses

###### Auther:-i_m_arj

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;......

```

leetcode.273 Integer to English Words

###### Auther:-bharatparakh

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......

```

Leetcode.554 Brick Wall

###### Auther:-grv0908

Brick wall....

Map....

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

```

leetcode.645 set mismatch

###### Auther:-mn265

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......

```

Leetcode.451 Sort characters by frequency

###### Auther:-grv0908

Sort characters by frequency....

Map....

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

```

Leetcode.884 Uncommon Words from Two Sentences

###### Auther:-Learnerforever

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);
......

```

Leetcode.771 Jewels and Stones

###### Auther:-Learnerforever

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(......

```

Leetcode.748 Shortest Completing Word

###### Auther:-Learnerforever

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......

```

Leetcode.575 Distribute Candies

###### Auther:-Learnerforever

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......

```

Leetcode.500 Keyboard Row

###### Auther:-Learnerforever

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 :
```

push all char in map ....

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

```

Leetcode.409 Longest Palindrome

###### Auther:-Learnerforever

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)
......

```

Leetcode.389 Find the Difference

###### Auther:-Learnerforever

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......

```

Leetcode.387 First Unique Character in a String

###### Auther:-Learnerforever

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<......

```

Leetcode.349 Intersection of Two Arrays

###### Auther:-Learnerforever

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......

```

leetcode.594 longest harmonious subsequence

###### Auther:-mn265

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......

```

Leetcode.217 Contains Duplicate

###### Auther:-Learnerforever

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......

```

Leetcode.1 Two Sum

###### Auther:-Learnerforever

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;
......

```

Leetcode.205 Isomorphic

###### Auther:-grv0908

Isomorphic String....

MAP....

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

```

Leetcode.43 Multiply Strings

###### Auther:-grv0908

Multiply Strings....

String....

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

```

Leetcode.165 Compare Version Numbers

###### Auther:-grv0908

Compare Version Numbers....

String....

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

```

Leetcode.49 Group Anagrams

###### Auther:-grv0908

Group Anagrams....

Map Strings....

```
class Solution {

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

```

Leetcode.1 Two Sum

###### Auther:-grv0908

Two Sum....

Map....

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

```

Leetcode.645 Set Mismatch

###### Auther:-grv0908

Set Mismatch....

Map....

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

int[......

```

leetcode.202 happy number

###### Auther:-mn265

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) {
......

```

leetcode.537 String Complex Number Multiplication

###### Auther:-i_m_arj

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......

```

leetcode.345 String Reverse Vowels of a String

###### Auther:-i_m_arj

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++)......

```

leetcode.541 String Reverse String II

###### Auther:-i_m_arj

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){
......

```

leetcode.551 String Student Attendance Record I

###### Auther:-i_m_arj

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......

```

leetcode.434 String Number of Segments in a String

###### Auther:-i_m_arj

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......

```

leetcode.443 String String Compression

###### Auther:-i_m_arj

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;
}......

```

leetcode.819 String Most Common Word

###### Auther:-i_m_arj

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......

```

leetcode.606 String Construct String from Binary Tree

###### Auther:-i_m_arj

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....

.....

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

```

leetcode.383 String Ransom Note

###### Auther:-i_m_arj

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;
......

```

leetcode.13 String Roman to Integer

###### Auther:-i_m_arj

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......

```

leetcode.521 String Longest Uncommon Subsequence I

###### Auther:-i_m_arj

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......

```

leetcode.804 String Unique Morse Code Words

###### Auther:-i_m_arj

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={".-......

```

###### Auther:-i_m_arj

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......

```

leetcode.884 Uncommon Words from Two Sentences

###### Auther:-mn265

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;
......

```

Leetcode.151 Reverse words in a string

###### Auther:-grv0908

Reverese words in a string....

String....

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

```

Leetcode.202 Happy Number

###### Auther:-grv0908

Happy Number....

Map....

```
class Solution {

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

```

leetcode .409 longest palindrom

###### Auther:-mn265

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......

```

Leetcode.409 Longest Palindrome

###### Auther:-grv0908

Longest Palindrome....

Map....

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

```

leetcode.387 First Unique Character in a String

###### Auther:-mn265

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......

```

leetcode.575 distribute candies

###### Auther:-mn265

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......

```

leetcode.217 contain duplicate

###### Auther:-mn265

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;
......

```

leetcode.389 Find the Difference

###### Auther:-mn265

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;
......

```

leetcode.349 intersection of two arrays

###### Auther:-mn265

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......

```

leetcode .136 single number

###### Auther:-mn265

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......

```

Leetcode.575 Distribute Candies

###### Auther:-grv0908

Distribute Candies....

Map....

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

......

```

Leetcode.884 Uncommon Words from two Strings

###### Auther:-grv0908

Uncommon Words from two strings....

Map....

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

```

Leetcode.242 Valid Anagram

###### Auther:-Learnerforever

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......

```

Leetcode.136 single number

###### Auther:-Learnerforever

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 ^=......

```

leetcode.686 String Repeated String Match

###### Auther:-i_m_arj

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......

```

leetcode.242 Valid Anagram

###### Auther:-mn265

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.......

```

leetcode.771 jewels and stone

###### Auther:-mn265

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......

```

leetcode.686 Repeated String Match

###### Auther:-bharatparakh

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......

```

Leetcode.389 Find the difference

###### Auther:-grv0908

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......

```

Leetcode.748 Shortest Completing Word

###### Auther:-grv0908

Shortest Completing word....

map....

```
class Solution {

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

```

Leetcode.136 Single Number

###### Auther:-grv0908

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;......

```

Leetcode.349 Intersection of Two Arrays

###### Auther:-grv0908

Intersection of Two Arrays....

Map....

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

```

leetcode.824 String Goat Latin

###### Auther:-i_m_arj

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== ......

```

leetcode.557 String Reverse Words in a String III

###### Auther:-i_m_arj

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>>......

```

leetcode.344 String Reverse String

###### Auther:-i_m_arj

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[......

```

leetcode.790 String To Lower Case

###### Auther:-i_m_arj

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 ......

```

leetcode.125 String Valid Palindrome

###### Auther:-i_m_arj

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)......

```

leetcode.58 String Length of Last Word

###### Auther:-i_m_arj

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)
......

```

leetcode.14 String Longest Common Prefix

###### Auther:-i_m_arj

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 "";
......

```

leetcode.680 String Valid Palindrome II

###### Auther:-i_m_arj

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......

```

leetcode.20 : String Valid Parentheses

###### Auther:-i_m_arj

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=......

```

Leetcode.20 Valid Paranthesis

###### Auther:-grv0908

Valid Paranthesis....

String....

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

```

Leetcode.235 LCA in BST

###### Auther:-grv0908

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 ......

```

Leetcode.98 Validate BST

###### Auther:-grv0908

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......

```

Leetcode.500 Keyboard Row

###### Auther:-grv0908

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......

```

###### Auther:-bharatparakh

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......

```

leetcode.824 Goat Latin

###### Auther:-bharatparakh

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 ......

```

leetcode.709 To Lower Case

###### Auther:-bharatparakh

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......

```

leetcode.680 Valid Palindrome II

###### Auther:-bharatparakh

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(......

```

leetcode.606 Construct String from Binary Tree

###### Auther:-bharatparakh

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....

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

```

leetcode.557 Reverse Words in a String III

###### Auther:-bharatparakh

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)
{
......

```

leetcode.551 . Student Attendance Record I

###### Auther:-bharatparakh

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++)
......

```

leetcode.541 Reverse String II

###### Auther:-bharatparakh

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......

```

leetcode.521 Longest Uncommon Subsequence I

###### Auther:-bharatparakh

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;
......

```

leetcode.520 Detect Capital

###### Auther:-bharatparakh

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 {......

```

leetcode.459 Repeated Substring Pattern

###### Auther:-bharatparakh

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......

```

leetcode.443 String Compression

###### Auther:-bharatparakh

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......

```

leetcode.434 Number of Segments in a String

###### Auther:-bharatparakh

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......

```

leetcode.387 First Unique Character in a String

###### Auther:-bharatparakh

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......

```

leetcode.383 Ransom Note

###### Auther:-bharatparakh

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......

```

leetcode.345 Reverse Vowels of a String

###### Auther:-bharatparakh

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;
......

```

leetcode.344 Reverse String

###### Auther:-bharatparakh

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......

```

leetcode.58 Length of Last Word

###### Auther:-bharatparakh

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......

```

leetcode.49 Group Anagrams

###### Auther:-bharatparakh

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......

```

leetcode.38 Count and Say

###### Auther:-bharatparakh

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)
{
......

```

leetcode.20 Valid Parentheses

###### Auther:-bharatparakh

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......

```

leetcode.14 Longest Common Prefix

###### Auther:-bharatparakh

. Longest Common Prefix....

. Longest Common Prefix....

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

```

leetcode.13 Roman to Integer

###### Auther:-bharatparakh

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;
......

```

LEETCODE.606 Construct String from Binary Tree

###### Auther:-Tharun_kumar

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......

```

LEETCODE.20 Valid Parentheses

###### Auther:-Tharun_kumar

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++) {
......

```

LEETCODE.434 Number of Segments in a String

###### Auther:-Tharun_kumar

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......

```

LEETCODE.14 Longest Common Prefix

###### Auther:-Tharun_kumar

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......

```

LEETCODE.443 String Compression

###### Auther:-Tharun_kumar

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......

```

LEETCODE.459 Repeated Substring Pattern

###### Auther:-Tharun_kumar

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 = "";......

```

LEETCODE.38 Count and Say

###### Auther:-Tharun_kumar

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......

```

LEETCODE.58 Length of Last Word

###### Auther:-Tharun_kumar

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......

```

LEETCODE.345 Reverse Vowels of a String

###### Auther:-Tharun_kumar

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......

```

LEETCODE.819 Most Common Word

###### Auther:-Tharun_kumar

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 &......

```

LEETCODE.541 Reverse String II

###### Auther:-Tharun_kumar

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......

```

LEETCODE.551 Student Attendance Record I

###### Auther:-Tharun_kumar

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++) {
......

```

LEETCODE.387 First Unique Character in a String

###### Auther:-Tharun_kumar

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......

```

LEETCODE.824 Goat Latin

###### Auther:-Tharun_kumar

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......

```

LEETCODE.709 To Lower Case

###### Auther:-Tharun_kumar

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]......

```

LEETCODE.804 Unique Morse Code Words

###### Auther:-Tharun_kumar

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......

```

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.557 Reverse Words in a String III

###### Auther:-Tharun_kumar

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 =......

```

LEETCODE.344 Reverse String

###### Auther:-Tharun_kumar

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......

```

Leetcode.387 First Unique Character in String

###### Auther:-grv0908

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<>();
......

```

leetcode.557 557. Reverse Words in a String III

###### Auther:-Chidananda

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(......

```

leetcode.344 344. Reverse String

###### Auther:-Chidananda

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......

```

leetcode.709 709. To Lower Case

###### Auther:-Chidananda

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 (......

```

leetcode.824 824. Goat Latin

###### Auther:-Chidananda

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......

```

Leetcode.110 Balanced Binary Tree

###### Auther:-msnitish

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-......

```

Leetcode.669 Trim a Binary Search Tree

###### Auther:-msnitish

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;
......

```

LEETCODE.958 check completeness of binary tree

###### Auther:-charank07

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 (......

```

LEETCODE.236 lca of binary tree

###### Auther:-charank07

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)
{

......

```

Leetcode.83 Remove Duplicates from Sorted List

###### Auther:-Learnerforever

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....
```

....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Leetcode.82 Remove Duplicates from Sorted List II

###### Auther:-Learnerforever

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....
```

....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Leetcode.24 Swap Nodes in Pairs

###### Auther:-Learnerforever

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.....
```

....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Leetcode.814 Binary Tree Pruning

###### Auther:-Learnerforever

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.) ....

....

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

```

Leetcode.230 Kth Smallest Element in a BST

###### Auther:-Learnerforever

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 = [....
```

....

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

```

Leetcode.513 Find Bottom Left Tree Value

###### Auther:-Learnerforever

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....
```

....

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

```

Leetcode.110 Balanced Binary Tree

###### Auther:-Learnerforever

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 ....
```

....

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

```

Leetcode.958 Check Completeness of a Binary Tree

###### Auther:-Learnerforever

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....

....

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

```

Leetcode.515 Find Largest Value in Each Tree Row

###### Auther:-Learnerforever

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]....
```

....

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

```

Leetcode.863 All Nodes Distance K in Binary Tree

###### Auther:-Learnerforever

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....
```

....

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

```

Leetcode.572 Subtree of Another Tree

###### Auther:-Learnerforever

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 ....
```

....

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

```

Leetcode.111 Minimum Depth of Binary Tree

###### Auther:-Learnerforever

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
....
```

....

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

```

Leetcode.671 Second Minimum Node In a Binary Tree

###### Auther:-Learnerforever

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 ....

....

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

```

Leetcode.112 Path Sum

###### Auther:-Learnerforever

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....
```

....

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

```

leetcode.814 Binary Tree Pruning

###### Auther:-i_m_arj

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.)....

.....

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

```

leetcode.652 Find Duplicate Subtrees

###### Auther:-i_m_arj

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 *......

```

leetcode.236 Lowest Common Ancestor of a Binary Tree

###### Auther:-i_m_arj

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 ....

.....

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

```

leetcode.513 Find Bottom Left Tree Value

###### Auther:-i_m_arj

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

.....

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

```

LEETCODE.17 Letter Combinations of a Phone Number

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.212 Word Search II

###### Auther:-Tharun_kumar

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) {
......

```

Leetcode.572 Subtree of Another Tree

###### Auther:-msnitish

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))......

```

Leetcode.671 Second Minimum Node in a Binary Tree

###### Auther:-msnitish

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....

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

```

Leetcode.111 Minimum Depth of Binary Tree

###### Auther:-msnitish

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 ......

```

Leetcode.897 Increasing Order Search Tree

###### Auther:-msnitish

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;......

```

Leetcode.977 Squares of a Sorted Array

###### Auther:-msnitish

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......

```

LEETCODE.872 LEAF SIMILAR TREES

###### Auther:-charank07

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......

```

LEETCODE.897 INCREASING ORDER SEARCH TREE

###### Auther:-charank07

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;
......

```

leetcode.543 Diameter of Binary Tree

###### Auther:-bharatparakh

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.....

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

```

leetcode.563 Binary Tree Tilt

###### Auther:-bharatparakh

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.....

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

```

leetcode.617 Merge Two Binary Trees

###### Auther:-bharatparakh

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......

```

leetcode.110 Balanced Binary Tree

###### Auther:-Chidananda

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*......

```

leetcode.111 Minimum Depth of Binary Tree

###### Auther:-Chidananda

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=......

```

leetcode.112 Path Sum

###### Auther:-Chidananda

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......

```

leetcode.572 572. Subtree of Another Tree

###### Auther:-Chidananda

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;
}......

```

leetcode.572 Subtree of Another Tree

###### Auther:-i_m_arj

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.....

.....

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

```

leetcode.112 Path Sum

###### Auther:-i_m_arj

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......

```

leetcode.671 Second Minimum Node In a Binary Tree

###### Auther:-i_m_arj

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....

.....

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

```

leetcode.110 Balanced Binary Tree

###### Auther:-i_m_arj

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.....

.....

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

```

leetcode.111 Minimum Depth of Binary Tree

###### Auther:-i_m_arj

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.....

.....

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

```

leetcode.101 Symmetric Tree

###### Auther:-i_m_arj

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:....

.....

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

```

leetcode.543 Diameter of Binary Tree

###### Auther:-i_m_arj

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 ....
```

.....

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

```

leetcode.563 Binary Tree Tilt

###### Auther:-i_m_arj

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....

.....

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

```

leetcode.104 Maximum Depth of Binary Tree

###### Auther:-i_m_arj

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.....

.....

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

```

leetcode.617 Merge Two Binary Trees

###### Auther:-i_m_arj

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....

.....

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

```

leetcode.129 Sum Root to Leaf Numbers

###### Auther:-bharatparakh

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 ....

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

```

leetcode.226 Invert Binary Tree

###### Auther:-bharatparakh

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....

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

```

leetcode.101 Symmetric tree

###### Auther:-bharatparakh

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.....

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

```

leetcode.100 Same Tree

###### Auther:-bharatparakh

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 .....

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

```

LEETCODE.79 Word Search

###### Auther:-Tharun_kumar

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......

```

LEETCODE.78 Subsets

###### Auther:-Tharun_kumar

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......

```

LEETCODE.22 Generate Parentheses

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.784 Letter Case Permutation

###### Auther:-Tharun_kumar

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......

```

LEETCODE.46 Permutations

###### Auther:-Tharun_kumar

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......

```

LEETCODE.40 Combination Sum II

###### Auther:-Tharun_kumar

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......

```

LEETCODE.216 Combination Sum III

###### Auther:-Tharun_kumar

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......

```

LEETCODE.39 Combination Sum

###### Auther:-Tharun_kumar

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(......

```

LEETCODE.77 Combinations

###### Auther:-Tharun_kumar

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......

```

leetcode.404 Sum of Left Leaves

###### Auther:-i_m_arj

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......

```

leetcode.222 Count Complete Tree Nodes

###### Auther:-i_m_arj

Count Complete Tree Nodes....

.....

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

```

System Design.Q.3 Mungeri Lal medicine shop

###### Auther:-i_m_arj

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 ......

```

System Design.Q.2 Registration system

###### Auther:-i_m_arj

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......

```

System Design.Q.1 Phone directory

###### Auther:-i_m_arj

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......

```

leetcode.226 Invert Binary Tree

###### Auther:-i_m_arj

Invert a binary tree.....

.....

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

```

leetcode.100 Same Tree

###### Auther:-i_m_arj

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.....

.....

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

```

LeetCode.121 Best Time to Buy and Sell Stock

###### Auther:-ramdasmenon

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;
......

```

LeetCode.63 Unique Paths II

###### Auther:-ramdasmenon

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;......

```

LeetCode.90 Subsets II

###### Auther:-ramdasmenon

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......

```

LeetCode.81 Search in Rotated Sorted Array II

###### Auther:-ramdasmenon

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 =......

```

LeetCode.74 Search a 2D Matrix

###### Auther:-ramdasmenon

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 ==......

```

LeetCode.73 Set Matrix Zeroes

###### Auther:-ramdasmenon

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(......

```

LeetCode.122 Best Time to Buy and Sell Stock II

###### Auther:-ramdasmenon

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;
......

```

LeetCode.45 Jump Game II

###### Auther:-ramdasmenon

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......

```

###### Auther:-i_m_arj

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.....

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.402 Remove K Digits

###### Auther:-ramdasmenon

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>......

```

LeetCode.55 Jump Game

###### Auther:-ramdasmenon

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 {
}

public boolean canJump(int[] nums) {
if(nums.leng......

```

LeetCode.140 Word Break II

###### Auther:-ramdasmenon

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......

```

Leetcode.17 Letter Combinations of a Phone Number

###### Auther:-ramdasmenon

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 , "......

```

Leetcode.22 Generate Parentheses

###### Auther:-ramdasmenon

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<>();
......

```

Leetcode.90 Subsets II

###### Auther:-ramdasmenon

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....

```
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> rs = new Ar......

```

Leetcode.212 Word Search II

###### Auther:-ramdasmenon

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......

```

Leetcode.79 Word Search

###### Auther:-ramdasmenon

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......

```

Leetcode.40 Combination Sum II

###### Auther:-ramdasmenon

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&......

```

Leetcode.46 Permutations

###### Auther:-ramdasmenon

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[......

```

Leetcode.216 Combination Sum III

###### Auther:-ramdasmenon

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 = ......

```

Leetcode.494 Target Sum

###### Auther:-ramdasmenon

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......

```

Leetcode.39 Combination Sum

###### Auther:-ramdasmenon

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......

```

Leetcode.77 Combinations

###### Auther:-ramdasmenon

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 ......

```

LeetCode.3 Longest Substring Without Repeating Characters

###### Auther:-ramdasmenon

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......

```

Leetcode.725 725. Split Linked List in Parts

###### Auther:-lucifer_t

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(......

```

leetcode.23 Merge k Sorted Lists

###### Auther:-i_m_arj

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;
/**
* struct ListNode {
*   int val;
*   ListNode *ne......

```

leetcode.25 Reverse Nodes in k-Group

###### Auther:-i_m_arj

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.....

.....

```
using namespace std;
/**
* struct ListNode {
*   int val;
*   ListNode *ne......

```

leetcode.61 Rotate List

###### Auther:-i_m_arj

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....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.143 Reorder List

###### Auther:-i_m_arj

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.....

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.138 Copy List with Random Pointer

###### Auther:-i_m_arj

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......

```

###### Auther:-i_m_arj

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......

```

###### Auther:-i_m_arj

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) *....

.....

```
/**

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : ......

```

###### Auther:-i_m_arj

add one pointer in each node such that the pointer points to the next to next node.(5marks)....

.....

```
struct ListNode {
int val;
ListNode *next,*next2next;
ListNode(int x......

```

###### Auther:-i_m_arj

)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)....

.....

```
struct ListNode {
int val;
int index;
ListNode *next;
ListNode(i......

```

###### Auther:-i_m_arj

1)Add one variable in each node which tells its index.from the first(for first node 1 second node 2 so on).(5marks)....

.....

```
struct ListNode {
int val;
int index;
ListNode *next;
ListNode(i......

```

leetcode.19 Remove Nth Node From End of List

###### Auther:-i_m_arj

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.

Could you do th....
```

.....

```
using namespace std;
/**
* struct ListNode {
*   int val;
*   ListNode *ne......

```

leetcode.86 Partition List

###### Auther:-i_m_arj

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....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.24 Swap Nodes in Pairs

###### Auther:-i_m_arj

```Example :

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

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.725 Split Linked List in Parts

###### Auther:-i_m_arj

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....

.....

```
using namespace std;
/**
* struct ListNode {
*   int val;
*   ListNode *ne......

```

LEETCODE.784 LETTER CASE COMBINATION

###### Auther:-charank07

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)
{

......

```

LeetCode.494 Target Sum

###### Auther:-ramdasmenon

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....

```
class Solution {
private int count = 0;

public int findTargetSumWays(int[] nums, int S) {
findTargetSumWa......

```

Backtracking_Assignment.2 sum in combination or not (with repetition)

###### Auther:-bharatparakh

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......

```

Backtracking_Assignment.1 sum in combination or not

###### Auther:-bharatparakh

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......

```

###### Auther:-i_m_arj

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....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.83 Remove Duplicates from Sorted List

###### Auther:-i_m_arj

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

```Example  1:

Input : 1->1->2
Output : 1->2....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-i_m_arj

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....

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-i_m_arj

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....

.....

```
using namespace std;
/**
* struct ListNode {
*   int val;
*   ListNode *ne......

```

leetcode.445 Merge Two Sorted Lists

###### Auther:-i_m_arj

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....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-ishaangulati8

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 ....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

LeetCode.160 Intersection of Two Linked Lists

###### Auther:-ishaangulati8

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ishaangulati8

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ishaangulati8

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.....

```
/**
* class ListNode {
*   int val;
*   ListNode next;
*   ListNode(int x......

```

LeetCode.83 Remove Duplicates from Sorted List

###### Auther:-ishaangulati8

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

LeetCode.21 Merge Two Sorted Lists

###### Auther:-ishaangulati8

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 ....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

LeetCode.237 Delete Node in a linked list.

###### Auther:-ishaangulati8

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ishaangulati8

Reverse the pointers in the linkedlist.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

LeetCode.876 Middle of the Linked List

###### Auther:-ishaangulati8

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

leetcode.160 Intersection of Two Linked Lists

###### Auther:-i_m_arj

Write a program to find the node at which the intersection of two singly linked lists begins.....

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.299 Bulls and Cows

###### Auther:-i_m_arj

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......

```

leetcode.274 H-Index

###### Auther:-i_m_arj

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......

```

leetcode.3 Longest Substring Without Repeating Characters

###### Auther:-i_m_arj

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......

```

leetcode.452 4Sum II

###### Auther:-i_m_arj

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) {
......

```

leetcode.632 Smallest Range

###### Auther:-i_m_arj

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......

```

leetcode.149 Max Points on a Line

###### Auther:-i_m_arj

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),......

```

leetcode.237 Delete Node in a Linked List

###### Auther:-i_m_arj

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 ....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.876 Middle of the Linked List

###### Auther:-i_m_arj

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....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-i_m_arj

```Example :

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

A linked list can be reversed either iteratively or recursively. Could you implement both?....
```

.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

practice_BackTracking.2 All possible arrangements

###### Auther:-Tharun_kumar

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......

```

practice_BackTracking.1 Printing all binary values of fixed length

###### Auther:-Tharun_kumar

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......

```

LEETCODE.103 Binary Tree Zigzag Level Order Traversal

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.637 Average of Levels in Binary Tree

###### Auther:-Tharun_kumar

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. ....

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

```

LEETCODE.590 N-ary Tree Postorder Traversal

###### Auther:-Tharun_kumar

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......

```

LEETCODE.589 N-ary Tree Preorder Traversal

###### Auther:-Tharun_kumar

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)....

```
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(i......

```

LEETCODE.199 Binary Tree Right Side View

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.402 Remove K Digits

###### Auther:-Tharun_kumar

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 ......

```

LEETCODE.55 Jump Game

###### Auther:-Tharun_kumar

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......

```

LEETCODE.649 Dota2 Senate

###### Auther:-Tharun_kumar

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 &......

```

LEETCODE.134 Gas Station

###### Auther:-Tharun_kumar

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;
}
......

```

Assignment 2.2 All arrangements

###### Auther:-Nabarun

given BBBRRR or similar find all possible arrangements....

seperate modules is self explanatory....

```
public class AllPossibleValues {
HashSet<String> result;
AllPossibleValues()
......

```

Assignment 1 (LeetCode).46 All possible combination

###### Auther:-Nabarun

[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......

```

Leetcode.78 Subsets

###### Auther:-ramdasmenon

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......

```

Leetcode.112 Path Sum

###### Auther:-msnitish

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......

```

Leetcode.543 Diameter of binary tree

###### Auther:-msnitish

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......

```

leetcode.961 N-repeated element in size 2N array

###### Auther:-gkartik1602

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......

```

leetcode.771 jewels and stone

###### Auther:-gkartik1602

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......

```

leetcode.111 minimum depth of binary tree

###### Auther:-charank07

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 ......

```

leetcode.100 Sametree

###### Auther:-charank07

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......

```

leetcode.222 count nodes in tree

###### Auther:-charank07

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;
}
......

```

Leetcode.38 Count and Say

###### Auther:-ramdasmenon

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......

```

Leetcode.830 Positions of Large Groups

###### Auther:-ramdasmenon

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......

```

###### Auther:-ramdasmenon

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.....

simple recursive solution....

```
class Solution {
if(num <= 9) {
return num;
}
int sum = 0;
......

```

Leetcode.136 Single Number

###### Auther:-ramdasmenon

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 ^......

```

Leetcode.884 Uncommon Words from Two Sentences

###### Auther:-ramdasmenon

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......

```

Leetcode.447 Number of Boomerangs

###### Auther:-ramdasmenon

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......

```

Leetcode.690 Employee Importance

###### Auther:-ramdasmenon

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 ......

```

Leetcode.290 Word Pattern

###### Auther:-ramdasmenon

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(......

```

Leetcode.451 Sort Characters By Frequency

###### Auther:-ramdasmenon

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<>();
......

```

Leetcode.347 Top K Frequent Elements

###### Auther:-ramdasmenon

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......

```

Leetcode.676 Implement Magic Dictionary

###### Auther:-ramdasmenon

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......

```

Leetcode.560 Subarray Sum Equals K

###### Auther:-ramdasmenon

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;
......

```

Leetcode.692 Top K Frequent Words

###### Auther:-ramdasmenon

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......

```

Leetcode.554 Brick Wall

###### Auther:-ramdasmenon

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......

```

Leetcode.509 Fibonacci Number

###### Auther:-msnitish

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] ......

```

Leetcode.101 Symmetric Tree

###### Auther:-msnitish

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.....

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

```

Leetcode.145 Binary Tree Postorder Traversal

###### Auther:-msnitish

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 .....

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

```

Leetcode.94 Binary Tree Inorder Traversal

###### Auther:-msnitish

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....

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

```

leetcode.554 Brick Wall

###### Auther:-i_m_arj

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......

```

leetcode.692 Top K Frequent Words

###### Auther:-i_m_arj

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>......

```

leetcode.525 Contiguous Array

###### Auther:-i_m_arj

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......

```

leetcode.560 Subarray Sum Equals K

###### Auther:-i_m_arj

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......

```

Leetcode.114 Flatten Binary Tree to Linked List

###### Auther:-ramdasmenon

Given a binary tree, flatten it to a linked list in-place.....

Use a dummy node....

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

```

Leetcode.155 Min Stack

###### Auther:-ramdasmenon

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......

```

Leetcode.448 Find All Numbers Disappeared in an Array

###### Auther:-ramdasmenon

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<......

```

Leetcode.452 Minimum Number of Arrows to Burst Balloons

###### Auther:-ramdasmenon

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;
......

```

Leetcode.881 Boats to Save People

###### Auther:-ramdasmenon

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;
......

```

Leetcode.435 Non-overlapping Intervals

###### Auther:-ramdasmenon

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......

```

###### Auther:-ramdasmenon

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. ....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

leetcode.881 Boats to Save People

###### Auther:-bharatparakh

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......

```

leetcode.948 Bag of Tokens

###### Auther:-bharatparakh

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......

```

###### Auther:-bharatparakh

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......

```

leetcode.392 Is Subsequence

###### Auther:-bharatparakh

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;
......

```

leetcode.452 Minimum Number of Arrows to Burst Balloons

###### Auther:-bharatparakh

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)
......

```

leetcode.435 Non-overlapping Intervals

###### Auther:-bharatparakh

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......

```

LEETCODE.392 Is Subsequence

###### Auther:-Tharun_kumar

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......

```

LEETCODE.435 Non-overlapping Intervals

###### Auther:-Tharun_kumar

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; } ....

```
/**
* Definition for an interval.
* struct Interval {
*   int start;
*   int end;
*   Interval() : start(0), e......

```

LEETCODE.881 Boats to Save People

###### Auther:-Tharun_kumar

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......

```

LEETCODE.452 Minimum Number of Arrows to Burst Balloons

###### Auther:-Tharun_kumar

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......

```

LEETCODE.948 Bag of Tokens

###### Auther:-Tharun_kumar

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()......

```

###### Auther:-Tharun_kumar

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())......

```

LEETCODE.30 substring with concaenation of all words

###### Auther:-charank07

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......

```

###### Auther:-charank07

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) {

retu......

```

###### Auther:-charank07

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:
......

```

###### Auther:-charank07

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->......

```

###### Auther:-charank07

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 *......

```

LEETCODE.24 swap nodes in pairs

###### Auther:-charank07

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:

{
......

```

leetcode.676 Implement Magic Dictionary

###### Auther:-i_m_arj

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......

```

leetcode.781 Rabbits in Forest

###### Auther:-i_m_arj

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:

unordered_map<i......

```

leetcode.347 Top K Frequent Elements

###### Auther:-i_m_arj

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......

```

leetcode.451 Sort Characters By Frequency

###### Auther:-i_m_arj

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){
......

```

Leetcode.979 Distribute Coins in Binary Tree

###### Auther:-ramdasmenon

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.....

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

```

Leetcode.Gas Station Gas Station

###### Auther:-ramdasmenon

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 <......

```

Leetcode.392 Is Subsequence

###### Auther:-ramdasmenon

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(......

```

leetcode.1 Two Sum

###### Auther:-i_m_arj

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;
......

```

leetcode.290 Word Pattern

###### Auther:-i_m_arj

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;
......

```

leetcode.219 Contains Duplicate II

###### Auther:-i_m_arj

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;
......

```

leetcode.205 Isomorphic Strings

###### Auther:-i_m_arj

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......

```

leetcode.645 Set Mismatch

###### Auther:-i_m_arj

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();
......

```

Leetcode.563 Binary Tree Tilt

###### Auther:-msnitish

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....

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

```

LEETCODE.21 merge two sorted lists

###### Auther:-charank07

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......

```

###### Auther:-charank07

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:
{
return false;
}
......

```

LEETCODE.160 INTERSECTION OF TWO LINKED LISTS

###### Auther:-charank07

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:
......

```

###### Auther:-charank07

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 result;

```

###### Auther:-charank07

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:
{
{
......

```

LEETCODE.203 REmove elements in linked list

###### Auther:-charank07

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) {
if(p1==N......

```

LEETCODE.143 reorder list

###### Auther:-charank07

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:
return;
......

```

Leetcode.12 Integer to Roman

###### Auther:-ramdasmenon

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"}......

```

Leetcode.204 Count Primes

###### Auther:-ramdasmenon

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......

```

Leetcode.693 Binary Number with Alternating Bits

###### Auther:-ramdasmenon

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();......

```

Leetcode.349 Intersection of Two Arrays

###### Auther:-ramdasmenon

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 ==......

```

leetcode.720 Longest Word in Dictionary

###### Auther:-Chidananda

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());
......

```

leetcode.202 202. Happy Number

###### Auther:-Chidananda

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......

```

leetcode.350 Intersection of Two Arrays II

###### Auther:-Chidananda

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<......

```

leetcode.387 First Unique Character in a String

###### Auther:-Chidananda

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;

......

```

leetcode.217 Contains Duplicate

###### Auther:-Chidananda

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())-......

```

leetcode.447 447. Number of Boomerangs

###### Auther:-Chidananda

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.......

```

leetcode.463 463. Island Perimeter

###### Auther:-Chidananda

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;
......

```

leetcode.463 463. Island Perimeter

###### Auther:-Anonymus

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 &&......

```

Leetcode.404 Sum of Left Leaves

###### Auther:-msnitish

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......

```

Leetcode.226 Invert Binary Tree

###### Auther:-msnitish

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;
}
......

```

leetcode.349 Intersection of Two Arrays

###### Auther:-i_m_arj

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....

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

map<i......

```

leetcode.693 Binary Number with Alternating Bits

###### Auther:-i_m_arj

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;
......

```

leetcode.690 Employee Importance

###### Auther:-i_m_arj

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......

```

leetcode.136 Single Number

###### Auther:-i_m_arj

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......

```

leetcode.217 Contains Duplicate

###### Auther:-i_m_arj

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&......

```

leetcode.387 First Unique Character in a String

###### Auther:-i_m_arj

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();......

```

leetcode.599 Minimum Index Sum of Two Lists

###### Auther:-i_m_arj

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) {

......

```

leetcode.350 Intersection of Two Arrays II

###### Auther:-i_m_arj

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......

```

leetcode.202 Happy Number

###### Auther:-i_m_arj

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......

```

leetcode.720 Longest Word in Dictionary

###### Auther:-i_m_arj

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......

```

leetcode.463 Island Perimeter

###### Auther:-i_m_arj

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 ......

```

leetcode.389 Find the Difference

###### Auther:-i_m_arj

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<......

```

leetcode.447 Number of Boomerangs

###### Auther:-i_m_arj

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;......

```

leetcode.349 Intersection of Two Arrays

###### Auther:-i_m_arj

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....

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

map<i......

```

Leetcode.948 Bag of Tokens

###### Auther:-ramdasmenon

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;
......

```

###### Auther:-ramdasmenon

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;......

```

LEETCODE.450 Delete Node in a BST

###### Auther:-Tharun_kumar

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....

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

```

Leetcode.500 Keyboard Row

###### Auther:-ramdasmenon

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){
......

```

Leetcode.242 Valid Anagram

###### Auther:-ramdasmenon

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 ......

```

leetcode.242 Anagram

###### Auther:-Chidananda

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......

```

leetcode.. Keyboard row

###### Auther:-Chidananda

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{
......

```

leetcode.575 Candles

###### Auther:-Chidananda

candie size....

map....

```
class Solution {
public:
map<int, int> can;
int distributeCandies(vector<int>& candies) {
for(int i = ......

```

leetcode.771 JEWELS and STONES

###### Auther:-Chidananda

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;......

```

leetcode.arjmnnit 575. Distribute Candies

###### Auther:-i_m_arj

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......

```

leetcode.arjmnnit Valid Anagram

###### Auther:-i_m_arj

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(),......

```

leetcode.arjmnnit Keyboard Row

###### Auther:-i_m_arj

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 :

```

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{
......

```

leetcode.arjmnnit Uncommon Words from Two Sentences

###### Auther:-i_m_arj

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......

```

leetcode.arjmnnit Jewels and Stones

###### Auther:-i_m_arj

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......

```

leetcode.arjmnnit Longest Palindrome

###### Auther:-i_m_arj

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+......

```

Leetcode.872 Leaf-Similar Trees

###### Auther:-msnitish

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 <......

```

Leetcode.1 Two Sum

###### Auther:-msnitish

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......

```

Leetcode.100 Same tree

###### Auther:-msnitish

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....

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

```

Leetcode.700 Search in a Binary Search Tree

###### Auther:-msnitish

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)......

```

Leetcode.617 Merge Two Binary Trees

###### Auther:-msnitish

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;
......

```

LEETCODE.606 Construct String from Binary Tree

###### Auther:-Tharun_kumar

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)"....

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

```

LEETCODE.124 Binary Tree Maximum Path Sum

###### Auther:-Tharun_kumar

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. ....

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

```

LEETCODE.337 House Robber III

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.105 Construct Binary Tree from Preorder and Inorder Traversal

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.652 Find Duplicate Subtrees

###### Auther:-Tharun_kumar

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. ....

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

```

Leetcode.515 Find Largest Value in Each Tree Row

###### Auther:-ramdasmenon

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

Use depth first search....

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

```

LEETCODE.129 Sum Root to Leaf Numbers

###### Auther:-Tharun_kumar

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....

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

```

LEETCODE.110 Balanced Binary Tree

###### Auther:-Tharun_kumar

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. ....

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

```

LEETCODE.814 Binary tree pruning

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.563 Binary Tree Tilt

###### Auther:-Tharun_kumar

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....

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

```

LEETCODE.515 Find Largest Value in Each Tree Row

###### Auther:-Tharun_kumar

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. ....

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

```

LEETCODE.101 Symmetric Tree

###### Auther:-Tharun_kumar

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....

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

```

Leetcode.637 Average of Levels in Binary Tree

###### Auther:-ramdasmenon

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....

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

```

Leetcode.589 N-ary Tree Preorder Traversal

###### Auther:-ramdasmenon

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() {}

......

```

Leetcode.590 N-ary Tree Postorder Traversal

###### Auther:-ramdasmenon

Given an n-ary tree, return the postorder traversal of its nodes values.....

regular post order traversal....

```
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

......

```

Leetcode.61 Rotate List

###### Auther:-ramdasmenon

Given a linked list, rotate the list to the right by k places, where k is non-negative.....

....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.24 Swap Nodes in Pairs

###### Auther:-ramdasmenon

```Example :

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

Use recursion....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.109 Convert Sorted List to Binary Search Tree

###### Auther:-ramdasmenon

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.....

....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.160 Intersection of Two Linked Lists

###### Auther:-ramdasmenon

Write a program to find the node at which the intersection of two singly linked lists begins.....

....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.138 Copy List with Random Pointer

###### Auther:-ramdasmenon

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......

```

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ramdasmenon

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

use fast and slow pointers....

```
/**
* class ListNode {
*   int val;
*   ListNode next;
*   ListNode(int x......

```

###### Auther:-ramdasmenon

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

use fast and slow pointers....

```
/**
* class ListNode {
*   int val;
*   ListNode next;
*   ListNode(int x......

```

Leetcode.237 Delete Node in a Linked List

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

###### Auther:-ramdasmenon

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.876 Middle of the Linked List

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.82 Remove Duplicates from Sorted List II

###### Auther:-ramdasmenon

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.83 Remove Duplicates from Sorted List

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.19 Remove Nth Node From End of List

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.21 Merge Two Sorted Lists

###### Auther:-ramdasmenon

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....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

Leetcode.23 Merge k Sorted Lists

###### Auther:-ramdasmenon

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.....

```
/**
* public class ListNode {
*   int val;
*   ListNode next;
*   ListNod......

```

LEETCODE.876 MIDDLE OF THE LINKED LIST

###### Auther:-charank07

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:
{
......

```

LEETCODE.86 PARTITION LIST

###### Auther:-charank07

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) {
{
......

```

###### Auther:-ramdasmenon

....

```
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> res = new HashSet<>();
for(S......

```

Leetcode.103 Binary Tree Zigzag Level Order Traversal

###### Auther:-ramdasmenon

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).....

....

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

```

Leetcode.102 Binary Tree Level Order Traversal

###### Auther:-ramdasmenon

Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level).....

....

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

```

Leetcode.257 Binary Tree Paths

###### Auther:-ramdasmenon

Given a binary tree, return all root-to-leaf paths.....

....

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

```

Leetcode.449 Serialize and Deserialize BST

###### Auther:-ramdasmenon

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....

....

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

```

Leetcode.513 Find Bottom Left Tree Value

###### Auther:-ramdasmenon

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....

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

```

Leetcode.98 Validate Binary Search Tree

###### Auther:-ramdasmenon

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....

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

```

Leetcode.129 Sum Root to Leaf Numbers

###### Auther:-ramdasmenon

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....

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

```

Leetcode.199 Binary Tree Right Side View

###### Auther:-ramdasmenon

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....

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

```

Leetcode.Same Tree Same Tree

###### Auther:-ramdasmenon

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....

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

```

Leetcode.145 Binary Tree Postorder Traversal

###### Auther:-ramdasmenon

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

Iterative post order traversal of a binary tree....

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

```

Leetcode.144 Binary Tree Preorder Traversal

###### Auther:-ramdasmenon

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

Iterative pre-order traversal of a BST....

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

```

Leetcode.94 Binary Tree Inorder Traversal

###### Auther:-ramdasmenon

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

Iterative inorder traversal of a Binary Tree using a stack....

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

```

LEETCODE.632 Smallest range

###### Auther:-Tharun_kumar

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......

```

###### Auther:-charank07

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:
{

bool cycle=false;
ListNode *sptr......

```

LEETCODE.82 remove duplicates from sorted linkedlist II

###### Auther:-Anonymus

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* dummy = new ListNod......

```

LEETCODE.61 Rotate list

###### Auther:-charank07

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) {

{
retu......

```

LEETCODE.19 REMOVE Nth node in the linked list

###### Auther:-charank07

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.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LEETCODE.525 contiguos array

###### Auther:-charank07

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......

```

LeetCode.632 Smallest Range(using priority queues)

###### Auther:-lucifer_t

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 = ......

```

LEETCODE.454 4sum 2

###### Auther:-charank07

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 ....

```
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
......

```

leetcode.632 Smallest Range(using two pointer)

###### Auther:-lucifer_t

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......

```

LEETCODE.347 top k frequent elements

###### Auther:-charank07

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 {
......

```

LEETCODE.554 brick wall

###### Auther:-charank07

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()......

```

LEETCODE.554 bricks

###### Auther:-Anonymus

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.....

```
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
if(wall.size() == 0 || wall[0].size()......

```

LEETCODE.274 h-index

###### Auther:-charank07

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);
......

```

LEETCODE.18 four sum

###### Auther:-charank07

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......

```

LEETCODE.617 Merge Two Binary Trees

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.965 Univalued Binary tree

###### Auther:-Tharun_kumar

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....

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

```

LEETCODE.113 PATH SUM 2

###### Auther:-Tharun_kumar

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.....

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

```

LEETCODE.112 PATH SUM

###### Auther:-Tharun_kumar

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.....

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

```

Leetcode.739 Daily Tempratues

###### Auther:-ahujarajat261

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]......

```

Leetcode.347 347. Top K Frequent Elements

###### Auther:-ahujarajat261

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......

```

LEETCODE.149 maximum points on a line.

###### Auther:-charank07

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......

```

LEETCODE.149 maximum points on a line.

###### Auther:-Khh_chaitanya

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......

```

Leetcode.144 Binary Tree Preorder Traversal

###### Auther:-msnitish

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.....

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

```

LEETCODE.676 IMPLEMENT MAGIC DICTIONARY

###### Auther:-charank07

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):
"""
"""
self.di......

```

leetcode.226 invert tree

###### Auther:-vish11

.....

.....

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

```

leetcode.515 large number in every row

###### Auther:-vish11

.....

.....

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

```

leetcode.617 merge two binary trees

###### Auther:-vish11

.....

.....

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

```

leetcode.652 duplicate sub trees

###### Auther:-vish11

.....

.....

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

```

leetcode.814 binary tree pruning

###### Auther:-vish11

.....

.....

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

```

leetcode.965 univalued binary tree

###### Auther:-vish11

.....

.....

```
class Solution {
public:
bool helper(TreeNode *root,int n){
bool z;
if(root->val==n){
z=true;
......

```

Leetcode.205 Isomorphic Strings

###### Auther:-ahujarajat261

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......

```

Leetcode.676 Implement Magic Dictionary

###### Auther:-ahujarajat261

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 ......

```

UVA.12639 Hexagonal Puzzle

###### Auther:-__lazy

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......

```

Leetcode.36 Valid Sudoku

###### Auther:-ahujarajat261

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 ==......

```

Leetcode.965 Univalued Binary Tree

###### Auther:-msnitish

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.....

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

```

Leetcode.104 Maximum Depth of Binary Tree

###### Auther:-msnitish

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......

```

leetcode.437 Path Sum III

###### Auther:-jairam

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......

```

leetcode.113 Path Sum II

###### Auther:-jairam

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......

```

leetcode.112 Path Sum

###### Auther:-jairam

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;
}......

```

LeetCode.108 Convert Sorted Array to Binary Search Tree

###### Auther:-ramdasmenon

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.....

....

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

```

LeetCode.617 Merge Two Binary Trees

###### Auther:-ramdasmenon

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....

....

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

```

LeetCode.226 Invert Binary Tree

###### Auther:-ramdasmenon

Invert a binary tree.....

....

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

```

LeetCode.543 Diameter of Binary Tree

###### Auther:-ramdasmenon

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.....

....

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

```

LeetCode.110 Balanced Binary Tree

###### Auther:-ramdasmenon

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. ....

....

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

```

LeetCode.965 Univalued Binary Tree

###### Auther:-ramdasmenon

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 a binary tree node.
* public class TreeNode {
*   int val;
*   TreeNode left;
*   TreeNod......

```

###### Auther:-vish11

.....

.....

```
/**
* struct ListNode {
*   int val;
*   struct ListNode *next;
* };
*/......

```

leetcode.82 remove duplicates from sorted list

###### Auther:-vish11

.....

.....

```
/**
* struct ListNode {
*   int val;
*   struct ListNode *next;
* };
*/......

```

leetcode.112 sum is k

###### Auther:-vish11

.....

.....

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

```

leetcode.111 min depth of binary tree

###### Auther:-vish11

.....

.....

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

```

leetcode.100 same tree

###### Auther:-vish11

.....

.....

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

```

leetcode.11 container mostwater

###### Auther:-vish11

.....

.....

```
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 ......

```

leetcode.16 3 sum closest

###### Auther:-vish11

.....

.....

```
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......

```

leetcode.954 array of doubled pairs

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
vector<vector<int> >&p=points;
......

```

leetcode.939 min area rectangle

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
vector<vector<int> >&p=points;
......

```

leetcode.781 rabit in forest

###### Auther:-vish11

.....

.....

```
class Solution {
public:
map<int,int......

```

leetcode.560 subarray sum is k

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
vector<int>& n=nums;
map<int,in......

```

leetcode.554 brickwall

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
vector<vector<int>>& w=wall;
......

```

leetcode.447 number of boomerrangs

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
vector<pair<int, int>......

```

leetcode.219 contain duplicate

###### Auther:-vish11

.....

.....

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

```

leetcode.136 single number

###### Auther:-vish11

.....

.....

```
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int>& n=nums;
map<int,int>m;
......

```

leetcode.49 group anagarams

###### Auther:-vish11

group anagarams....

-....

```
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<string>& s......

```

leetcode.299 bulls and cows

###### Auther:-vish11

bulls and cows....

-....

```
class Solution {
public:
string getHint(string secret, string guess) {
string s=secret;
string g=guess;
......

```

LEETCODE.594 largest homographic subsequences

###### Auther:-charank07

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......

```

LEETCODE.438 FIND ALL ANAGRAMS

###### Auther:-charank07

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......

```

LEETCODE.349 INTERSECTION OF ARRAYS

###### Auther:-charank07

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) {

......

```

LEETCODE.290 WORD PATTERN

###### Auther:-charank07

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
......

```

LEETCODE.204 count primes

###### Auther:-charank07

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 ==......

```

LEETCODE.299 BULLS AND COWS

###### Auther:-charank07

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......

```

LEETCODE.187 REPEATED DNA SEQUENCES

###### Auther:-charank07

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......

```

LEETCODE.560 subarray sum=k

###### Auther:-charank07

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......

```

LEETCODE.205 Isomorphic Strings

###### Auther:-charank07

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()......

```

LEETCODE.599 MINIMUM INDEX SUM OF TWO LISTS

###### Auther:-charank07

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) {

......

```

LEETCODE.350 INTERSECTION OF TWO ARRAYS

###### Auther:-charank07

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......

```

leetcode.545 Boundary of a tree

###### Auther:-lucifer_t

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......

```

LeetCode.235 Lowest Common Ancestor of a Binary Search Tree

###### Auther:-ramdasmenon

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.....

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

```

LeetCode.236 Lowest Common Ancestor of a Binary Tree

###### Auther:-ramdasmenon

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 ....

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

```

LeetCode.872 Leaf-Similar Trees

###### Auther:-ramdasmenon

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 ......

```

practice_Tree.8 Inverting a tree

###### Auther:-Tharun_kumar

Invert a tree.(Left becomes right and vice versa)....

Assign left pointer to right and right pointer to left. ....

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

```

practice_Tree.7 Diameter of binary tree

###### Auther:-Tharun_kumar

Find the diameter of the binary tree.....

Mark each diameter in variable sum and update it if it is lesser than current diameter. ....

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

```

practice_Tree.6 Same tree

###### Auther:-Tharun_kumar

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.....

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

```

practice_Tree.5 Maximum depth of tree

###### Auther:-Tharun_kumar

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. ....

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

```

practice_Tree.4 Sum of leaf nodes

###### Auther:-Tharun_kumar

Sum of leaf nodes in tree....

If a node is leaf node then add its value and return the output to the calling node.....

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

```

practice_Tree.3 Sum of elements

###### Auther:-Tharun_kumar

Sum of elements in a tree....

Every node adds its value and returns output to calling node.....

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

```

practice_Tree.2 Counting Leaf nodes

###### Auther:-Tharun_kumar

Count the number of leaf nodes....

Every leaf node adds 1 and returns the output to calling node.....

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

```

practice_Tree.1 Counting Nodes in tree

###### Auther:-Tharun_kumar

Count the number of nodes in tree....

Every node adds 1 which will be returned to calling node.....

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

```

LEETCODE.1 TWO SUM

###### Auther:-charank07

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......

```

LEETCODE.645 SET MISMATCH

###### Auther:-charank07

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,......

```

LEETCODE.720 LONGEST WORD IN DICTIONARY

###### Auther:-charank07

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......

```

LEETCODE.202 HAPPY NUMBER

###### Auther:-charank07

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;
......

```

LEETCODE.387 first unique char in string

###### Auther:-charank07

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......

```

###### Auther:-msnitish

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.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LEETCODE.389 FIND THE DIFFERENCE

###### Auther:-charank07

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......

```

LEETCODE.771 JEWELS AND STONES

###### Auther:-charank07

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;
......

```

LEETCODE.463 ISLAND PERIMETER

###### Auther:-charank07

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......

```

LEETCODE.781 RABBITS IN FOREST

###### Auther:-charank07

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:
map<int, int> M;
map<int, int> :: it......

```

LEETCODE.575 DISTRIBUTE CANDIES

###### Auther:-charank07

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......

```

LEETCODE.447 Number of boomerangs

###### Auther:-charank07

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......

```

LEETCODE.242 valid anagram

###### Auther:-charank07

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......

```

LEETCODE.409 LONGEST PALINDROME

###### Auther:-charank07

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......

```

###### Auther:-msnitish

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]....

```
public:
/** Initialize your data structure here. */
int size;
ListNod......

```

Leetcode.237 Delete Node in a Linked List

###### Auther:-msnitish

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......

```

test_L_L.4 Vallet parking system

###### Auther:-Tharun_kumar

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......

```

test_L_L.3 Playlist

###### Auther:-Tharun_kumar

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......

```

test_L_L.1a,1b Index from first

###### Auther:-Tharun_kumar

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......

```

###### Auther:-bharatparakh

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-kiran_kavuri

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 {
w......

```

leetcode.61 Rotate List

###### Auther:-bharatparakh

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 ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.61 Rotate List

###### Auther:-bharatparakh

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.21 . Merge Two Sorted Lists

###### Auther:-bharatparakh

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....

```
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
{
retur......

```

leetcode.876 Middle of the Linked List

###### Auther:-bharatparakh

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 .....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.430 Flatten a Multilevel Doubly Linked List

###### Auther:-bharatparakh

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......

```

leetcode.237 Delete Node in a Linked List

###### Auther:-bharatparakh

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.....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-bharatparakh

Here reverse list using recursion. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-bharatparakh

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.160 Intersection of Two Linked Lists

###### Auther:-bharatparakh

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.24 Swap Nodes in Pairs

###### Auther:-bharatparakh

Here take one dummy at starting and set curr=dummy .Then iterate until curr->next ! =null and each time swap two nodes. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-bharatparakh

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. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-bharatparakh

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:
int n=0;
ListNode* odd=new ListNode (1);
......

```

###### Auther:-bharatparakh

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) {
{
retur......

```

###### Auther:-bharatparakh

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:
//the distance between head to the start of lo......

```

leetcode.86 Partition List

###### Auther:-bharatparakh

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);
......

```

leetcode.82 Remove Duplicates from Sorted List II

###### Auther:-bharatparakh

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 *dummy=new ListNode(1);

d......

```

leetcode.83 Remove Duplicates from Sorted List

###### Auther:-bharatparakh

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*......

```

leetcode.25 Reverse Nodes in k-Group

###### Auther:-bharatparakh

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) {

```

leetcode.19 Remove Nth Node From End of List

###### Auther:-bharatparakh

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. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Leetcode.876 Middle of the Linked List

###### Auther:-msnitish

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:

```

###### Auther:-shiva9871

reversing....

in this code we reverse the code....

```
**
* struct ListNode {
*   int val;
*   struct ListNode *next;
* };
*/
......

```

leetcode.876 Middle of the Linked List

###### Auther:-jairam

discussed in class....

```
class Solution {
public:
{
......

```

###### Auther:-jairam

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) {
return 0;......

```

leetcode.725 Split Linked List in Parts

###### Auther:-jairam

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;
......

```

###### Auther:-jairam

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);
......

```

leetcode.237 Delete Node in a Linked List

###### Auther:-jairam

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.....

discussed in class....

```
class Solution {
public:
void deleteNode(ListNode* node) {
node->val=node->next->val;
ListNode *tmp=node->......

```

###### Auther:-jairam

discussed in class....

```
class Solution {
public:
{
......

```

###### Auther:-jairam

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....

```
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0,sum;
ListNode *......

```

leetcode.21 Merge Two Sorted Lists

###### Auther:-jairam

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....

```
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
{
retur......

```

###### Auther:-jairam

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

discussed in class....

```
class Solution {
public:
{
return false;
}
......

```

leetcode.160 Intersection of Two Linked Lists

###### Auther:-jairam

Write a program to find the node at which the intersection of two singly linked lists begins.....

discussed in class....

```
class Solution {
public:
......

```

leetcode.24 Swap Nodes in Pairs

###### Auther:-jairam

discussed in class....

```
class Solution {
public:
{
......

```

###### Auther:-jairam

Given a singly linked list, determine if it is a palindrome.....

discussed in class....

```
class Solution {
public:

bool res;

```

###### Auther:-jairam

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....

```
class Solution {
public:
{
......

```

###### Auther:-jairam

Remove all elements from a linked list of integers that have value val.....

discussed in class....

```
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
{
retur......

```

leetcode.147 Insertion Sort List

###### Auther:-jairam

Sort a linked list using insertion sort.....

same procedure as insertion sort....

```
class Solution {
public:
......

```

leetcode.143 Reorder List

###### Auther:-jairam

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....

```
class Solution {
public:
return;
......

```

###### Auther:-jairam

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

.......

```
class Solution {
public:
bool cycle=false;

```

leetcode.86 Partition List

###### Auther:-jairam

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....

```
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
{
......

```

leetcode.83 Remove Duplicates from Sorted List

###### Auther:-jairam

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:
{
......

```

leetcode.82 Remove Duplicates from Sorted List II

###### Auther:-jairam

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:
{
......

```

leetcode.409 Longest Palindrome

###### Auther:-ahujarajat261

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;
}
......

```

LEETCODE.66 PLUS ONE

###### Auther:-Tharun_kumar

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:
ListNode* helperFunc(ListNode* head, ListNode** req) {

```

LEETCODE.86 Partition List

###### Auther:-Tharun_kumar

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.....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

###### Auther:-Tharun_kumar

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.....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

LEETCODE.24 Swap node in pairs

###### Auther:-Tharun_kumar

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

###### Auther:-Tharun_kumar

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.....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

LEETCODE.237 Delete node in linked list

###### Auther:-Tharun_kumar

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....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

###### Auther:-Tharun_kumar

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. ....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

###### Auther:-Tharun_kumar

Using recursion....

```
* struct ListNode {
*   int val;
*   ListNode *next;
*   ......

```

LEETCODE.389 Find the difference

###### Auther:-Tharun_kumar

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;......

```

LEETCODE.771 JEWELS and STONES

###### Auther:-Tharun_kumar

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> jewel;
int count = 0;......

```

LEETCODE.187 Repeated DNA Sequences

###### Auther:-Tharun_kumar

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......

```

LEETCODE.202 HAPPY NUMBER

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.463 ISLAND PERIMETER

###### Auther:-Tharun_kumar

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......

```

LEETCODE.525 CONTIGUOUS ARRAY

###### Auther:-Tharun_kumar

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;
......

```

LEETCODE.299 COWS and BULLS

###### Auther:-Tharun_kumar

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,......

```

LeetCode.148 Sort List

###### Auther:-lt_chitts

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:

......

```

LeetCode.61 Rotate List

###### Auther:-lt_chitts

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 ,....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.143 Reorder List

###### Auther:-lt_chitts

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. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.160 Intersection of Two Linked Lists

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-lt_chitts

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. ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.81 Remove Duplicates from Sorted List

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.21 Merge Two Sorted Lists

###### Auther:-lt_chitts

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 ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.237 Delete Node in a Linked List

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Leet.206 Reverse a singly linked list.

###### Auther:-lt_chitts

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) ....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

LeetCode.876 Middle of the Linked List

###### Auther:-lt_chitts

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

ll.2 delete node at given position

###### Auther:-vish11

delete at a given position....

-....

```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node *newnode(int n){......

```

ll.5 min,max

###### Auther:-vish11

finding min,max....

-....

```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node *newnode(int n){......

```

ll.2 insert at kth position

###### Auther:-vish11

inserting at kth position....

-....

```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node *newnode(int n){......

```

###### Auther:-vish11

insert node at end....

-....

```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node *newnode(int n){......

```

###### Auther:-vish11

insert node at beginning....

-....

```
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node *newnode(int n){......

```

leetcode.61 rotate linked list by k nodes

###### Auther:-jairam

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....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

leetcode.19 delete nth node from end in linked list

###### Auther:-jairam

....

using 2nd approach discussed in class....

```
/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int......

```

Codeforces.4C Registration system

###### Auther:-msnitish

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=......

```

Leetcode.575 Distribute Candies

###### Auther:-msnitish

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......

```

Leetcode.575 Distribute Candies

###### Auther:-msnitish

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......

```

Leetcode.242 Valid Anagram

###### Auther:-msnitish

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 type of map for m1 and m2 ....

```
class Solution {
public:
bool isAnagram(string s, string t) {
map < char, int > m1,m2;
for (int i=0; i&l......

```

Leetcode.136 Single Number

###### Auther:-msnitish

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......

```

Leetcode.389 Find the difference

###### Auther:-msnitish

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......

```

Leetcode.781 Rabbits in a Forest

###### Auther:-msnitish

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:
map <int, int> m;
for (int i=0; i< answ......

```

Leetcode.771 Jewels and Stones

###### Auther:-msnitish

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;
......

```

. delete duplicate nodes

###### Auther:-bharatparakh

/* 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 value at position multiple of k

###### Auther:-bharatparakh

/* 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;
......

```

. find max and min

###### Auther:-bharatparakh

/* 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;
......

```

. reverse a list

###### Auther:-bharatparakh

....

....

```
#include <iostream>
using namespace std;
#include <stdlib.h>
struct node
{

int data;
struct node* next;
......

```

. deletion in a linked list

###### Auther:-bharatparakh

/* 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....

....

```
#include <iostream>
using namespace std;
#include <stdlib.h>
struct node
{

int data;
struct node* next;
......

```

###### Auther:-bharatparakh

/* 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;......

```

practice_L_L.3 MAXIMUM, MINIMUM in LINKED LIST

###### Auther:-Tharun_kumar

Write a program for printing the following in a given linked list: a. maximum b. minimum c. maximum  minimum....

....

```
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
struct node {
int data;
struc......

```

###### Auther:-Tharun_kumar

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....

....

```
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
struct node {
int data;
struc......

```

###### Auther:-Tharun_kumar

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....

....

```
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
struct node {
int data;
struc......

```

LEETCODE.4 Median of Two Sorted Arrays

###### Auther:-genetic_code

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......

```

practice_L_list.5 finding min,max in linked list(revised)

###### Auther:-jairam

To find min,max in linked list....

Only fns are written ,return type is int(revised)....

```
//question5
//a.)max
{
while(ptr!=NULL)
{
i......

```

###### Auther:-jairam

To delete node at start,end ,kth position....

only fns are written with return type Node *....

```

// question 2
//a.)deletion at start
{
{
Node *tmp......

```

###### Auther:-jairam

To insert a node at start,end,kth position....

only functions are written with return type Node *....

```
//question 1
//a.)insertion at start
{

Node *tmp=(Node *)malloc(sizeof......

```

LEETCODE.781 RABBITS IN FOREST

###### Auther:-Tharun_kumar

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:
map<int, int> rabbit;
map<int, int>......

```

LEETCODE.575 DISTRIBUTE CANDIES

###### Auther:-Tharun_kumar

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.....

```
class Solution {
public:
map<int, int> can;
int distributeCandies(vector<int>& candies) {
for(int i = ......

```

LEETCODE.406 QUEUE RECONSTRUCTION BY HEIGHT

###### Auther:-Tharun_kumar

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......

```

LEETCODE.409 LONGEST PALINDROME

###### Auther:-Tharun_kumar

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......

```

LEETCODE. VALID ANAGRAM

###### Auther:-Tharun_kumar

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......

```

LEETCODE.136 SINGLE NUMBER

###### Auther:-Tharun_kumar

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......

```

LEETCODE.447 NUMBER OF BOOMERANGS

###### Auther:-Tharun_kumar

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......

```

LEETCODE.554 BRICK WALL

###### Auther:-Tharun_kumar

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, ......

```

leetcode.1 Two Sum

###### Auther:-kiran_kavuri

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 (......

```

Leetcode.5 Longest Palindromic Substring

###### Auther:-genetic_code

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

```Example  1:
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......

```

Leetcode.4 Median of Two Sorted Arrays

###### Auther:-genetic_code

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:....
```

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......

```

Leetcode.3 [LeetCode] Longest Substring Without Repeating Characters

###### Auther:-Genetic_code2

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......

```

###### Auther:-Genetic_code2

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)......

```