├── .DS_Store ├── Arrays ├── 1189_maximum_number_of_balloons.cpp ├── 118_pascals_triangle.cpp ├── 1389_create_target_array_in_the_given_order.cpp ├── 1423_max_points_obtained_from_cards.cpp ├── 283_move_zeros.cpp ├── 48_rotate_image.cpp ├── 75_sort_colours.cpp ├── 977_squares_of_sorted_arr.cpp └── temp ├── Backtracking ├── 51.N-Queens.cpp └── 89. Gray Code ├── Binary Search ├── 1351. Count Negative Numbers in a Sorted Matrix ├── 287_find_the_duplicate_number.cpp ├── 33. Search in Rotated Sorted Array ├── 34.FindFirstandLastPosition.cpp ├── 374. Guess Number Higher or Lower ├── 633. Sum of Square Numbers ├── 852. Peak Index in a Mountain Array └── temp ├── DP ├── 1049. Last Stone Weight II └── 152. Maximum Product Subarray ├── Greedy Algorithm └── temp ├── Hash Maps ├── .DS_Store ├── 1305.AllElementsinTwoBinarySearchTrees.cpp ├── 1_twoSum.cpp ├── 2215_diff2Arrays.cpp ├── 2325_decode_the_message.cpp ├── 242_valid_anagram.cpp ├── 2610.ConvertanArrayIntoa2DArrayWithConditions.cpp ├── 49_group_anagrams.cpp ├── 706_design_hashmap.cpp ├── 771_jewels_and_stones.cpp └── 853.Car_Fleet.cpp ├── Heap └── 347_top_k_frequent_elements.cpp ├── Linked List ├── 138_copy_list_with_random_pointer.cpp ├── 141_linked_list_cycle.cpp ├── 2326_spiral_matrix_4.cpp ├── 234. Palindrome Linked List ├── 61_rotate_list.cpp ├── 86_partition_list.cpp └── 876. Middle of the Linked List.cpp ├── Math & Bit Manipulation └── 191_number_of_1_bits.cpp ├── README.md ├── Sliding Window └── temp ├── Stacks ├── 1047_remove_adj_duplicates.cpp ├── 1544_make_the_string_great.cpp ├── 20_valid_parentheses.cpp ├── 2696. Minimum String Length After Removing Substrings ├── 496_nextGreaterElement.cpp ├── 735_asteroid_collision.cpp └── 844_backspace-string-compare └── Trees ├── .DS_Store ├── 100_same_tree.cpp ├── 101. Symmetric Tree ├── 103_binary_tree_zigzag_level_order_traversal.cpp ├── 104_maximum_depth_of_binary_tree.cpp ├── 106_construct_tree_from_io_po.cpp ├── 110_balanceBT.cpp ├── 116_populating_next_right_pointer.cpp ├── 145_binary_tree_postorder_traversal.cpp ├── 199.BinaryTreeRightSideView.cpp ├── 226_invert_binary_tree.cpp ├── 235_lowest_common_ancestor_of_BST.cpp ├── 404. Sum of Left Leaves ├── 530_min_abs_diff_in_bst.cpp ├── 544_diameter-of-binary-tree.cpp ├── 572_subtree_of_another_tree.cpp ├── 617_mergeBinaryTree.cpp ├── 637_avg_of_levels_in_binary_tree.cpp ├── 662_maximum_width_of_binary_tree.cpp ├── 94_binary_tree_inorder_traversal.cpp ├── 958_check_completeness_of_binary_tree.cpp ├── 98_validate_binary_search_tree.cpp └── 99_recover_bst.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/.DS_Store -------------------------------------------------------------------------------- /Arrays/1189_maximum_number_of_balloons.cpp: -------------------------------------------------------------------------------- 1 | //method 1 2 | 3 | class Solution { 4 | public: 5 | int maxNumberOfBalloons(string text) { 6 | unordered_map mm; 7 | for (char i : text) mm[i] += 1; 8 | return min(mm['b'], min(mm['a'], min(mm['l']/2, min(mm['o']/2, mm['n'])))); 9 | } 10 | }; 11 | 12 | //method 2 13 | 14 | class Solution { 15 | public: 16 | int maxNumberOfBalloons(string text) { 17 | vector freq(5); 18 | for (char i : text){ 19 | switch (i){ 20 | case 'b': 21 | freq[0]++; 22 | break; 23 | case 'a': 24 | freq[1]++; 25 | break; 26 | case 'l': 27 | freq[2]++; 28 | break; 29 | case 'o': 30 | freq[3]++; 31 | break; 32 | case 'n': 33 | freq[4]++; 34 | break; 35 | 36 | } 37 | } 38 | 39 | freq[2] /= 2; 40 | freq[3] /= 2; 41 | 42 | return *min_element(freq.begin(), freq.end()); 43 | 44 | } 45 | }; -------------------------------------------------------------------------------- /Arrays/118_pascals_triangle.cpp: -------------------------------------------------------------------------------- 1 | // link- https://leetcode.com/problems/pascals-triangle/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> generate(int numRows) { 6 | vector> ans; 7 | for(int i=1;i<=numRows;i++){ 8 | vector temp(i); 9 | temp[0]=1; 10 | temp[i-1]=1; 11 | for(int j=1; j createTargetArray(vector& nums, vector& index) 7 | { 8 | vector result; 9 | for(int i=0;i createTargetArray(vector& nums, vector& index) { 19 | vector target(nums.size()); 20 | // we will write some code to modify the index array 21 | for(int i=0;i=0;j--){ 23 | if(index[i]<=index[j]) index[j]++; 24 | } 25 | } 26 | 27 | for(int i=0;i& cardPoints, int k) { 5 | int n=cardPoints.size(); 6 | int start=k-1,end=n-1; 7 | int sum=0; 8 | int max_score=0; 9 | for(int i=0;i=0 && end>start){ 15 | sum+=cardPoints[end]-cardPoints[start]; 16 | max_score=max(max_score,sum); 17 | start--; 18 | end--; 19 | } 20 | 21 | return max_score; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Arrays/283_move_zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int last=0; 5 | int i=0; 6 | for(int i=0;i>& matrix) { 5 | int n=matrix.size(); 6 | //transpose 7 | 8 | for(int i=0;i& nums) { 5 | int left=0;// ensures values before it are 0s. 6 | int right=nums.size()-1; //ensures values after it are 2s. 7 | int i=0;// to traverse array. 8 | while(i<=right){ 9 | if(nums[i]==0){ 10 | swap(nums[i],nums[left]); 11 | i++; 12 | left++; 13 | } 14 | else if (nums[i]==2){ 15 | swap(nums[i],nums[right]); 16 | right--; 17 | //dont increment i here. 18 | } 19 | else{ 20 | i++; //no need to swap when i is pointing to 1. 21 | } 22 | } 23 | } 24 | }; 25 | 26 | 27 | //two pass solution: 28 | class Solution { 29 | public: 30 | void sortColors(vector& nums) { 31 | //to store count: 32 | int zeroes=0; 33 | int ones=0; 34 | int twos=0; 35 | //storing the count of zeroes, ones and twos in first traversal. 36 | for(int i=0;i=zeroes && i sortedSquares(vector& a) { 4 | // i left 5 | //j right 6 | int n=a.size(); 7 | int i=0,j=n-1; 8 | vectorans(n,0); 9 | int k=n-1; 10 | while(i<=j){ 11 | if(abs(a[i])>=abs(a[j])){ 12 | ans[k]=pow(a[i],2); 13 | i++; 14 | } 15 | else{ 16 | ans[k]=pow(a[j],2); 17 | j--; 18 | } 19 | 20 | k--; 21 | } 22 | return ans; 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Arrays/temp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/Arrays/temp -------------------------------------------------------------------------------- /Backtracking/51.N-Queens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool isSafe(int row,int col,vectorboard,int n){ 5 | 6 | //1 r/c 7 | for(int i=0;iboard, 18 | vector>& ans, int n){ 19 | // 0 to n-1 satisfy 20 | 21 | //we have a sol 22 | if(row==n){ 23 | string str=""; 24 | for(int i=0;i sol; 27 | for(int i=0;i> solveNQueens(int n) { 53 | //keeping the queen row-wise 54 | 55 | vector> ans; 56 | vectorboard; //board[i]-> ith row has the queen at board[i] 57 | 58 | solve(0,board,ans,n); 59 | return ans; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /Backtracking/89. Gray Code: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void backtrack(bitset<32>&bits, vector&res, int n){ 5 | if(n==0){ 6 | res.push_back(bits.to_ulong()); 7 | return ; 8 | } 9 | // 0 ->k-1 10 | backtrack(bits,res,n-1); 11 | //flip 12 | bits.flip(n-1); 13 | backtrack(bits,res,n-1); 14 | } 15 | vector grayCode(int n) { 16 | // Approach 1 backtracking 17 | 18 | // 1.choose 2.operation 3.unchoose 19 | 20 | // bitset<32>bits; 21 | // vectorres; 22 | // backtrack(bits,res,n); 23 | // return res; 24 | 25 | //n=1 0,1 [0 1] 26 | 27 | 28 | //n=2 0,1,2,3 29 | //00 01 --- 11 10 --- 0,1,3,2 30 | //10 31 | 32 | 33 | // n=3 34 | //000 001 011 010. --- 110 111 101 100 35 | //100 36 | 37 | 38 | 39 | 40 | // approach 2 - pattern identification 41 | vectorres={0,1}; 42 | for(int i=1;ivec){ 5 | int beg=0,end=vec.size()-1; 6 | while(beg<=end){ 7 | int mid=(beg+end)/2; 8 | // beg=mid+1. -- non neg value 9 | 10 | if(vec[mid]>=0) beg=mid+1; 11 | else end=mid-1; 12 | } 13 | return vec.size()-(end+1); 14 | //end is pointing to the last occ of non neg no. 15 | } 16 | 17 | int countNegatives(vector>& grid) { 18 | int m=grid.size(); 19 | int n= grid[0].size();int ans=0; 20 | 21 | for(int i=0;i& nums) { 4 | int l = 1, h = nums.size()-1; 5 | while(l<=h){ 6 | int mid = l + (h-l)/2; 7 | int count = 0; 8 | for(auto i:nums){ 9 | // all three approaches are valid 10 | // count += i<=mid; 11 | if(i<=mid){ 12 | count++; 13 | } 14 | // count += i<=mid?1:0; 15 | } 16 | if(count<=mid){ 17 | l=mid+1; 18 | } 19 | else{ 20 | h = mid-1; 21 | } 22 | 23 | } 24 | return l; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Binary Search/33. Search in Rotated Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int beg=0,end=nums.size()-1; 5 | int mid=0; 6 | while(beg<=end){ 7 | mid=(beg+end)/2; 8 | if(nums[mid]==target) return mid; 9 | 10 | if(nums[beg]<=nums[mid]){ 11 | 12 | //1st half is sorted 13 | 14 | if(target>=nums[beg] && target<=nums[mid]){ 15 | end=mid-1; 16 | } 17 | else 18 | beg=mid+1; 19 | 20 | } 21 | 22 | else{ 23 | 24 | //2nd half is sorted 25 | 26 | if(target>=nums[mid] && target<=nums[end]){ 27 | beg=mid+1; 28 | } 29 | 30 | else 31 | end=mid-1; 32 | } 33 | 34 | } 35 | 36 | return -1; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Binary Search/34.FindFirstandLastPosition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int binary_search(int target,vector nums){ 4 | int low=0,high=nums.size()-1; 5 | while (low <= high) { 6 | int mid = low + (high - low)/2; 7 | if (nums[mid] < target) { 8 | low = mid + 1; 9 | } else { 10 | high = mid - 1; 11 | } 12 | } 13 | return low; 14 | } 15 | vector searchRange(vector& nums, int target) { 16 | int s = binary_search(target,nums); 17 | int e = binary_search(target+1,nums) - 1; 18 | if(s < nums.size() && nums[s]==target) 19 | return {s,e}; 20 | return {-1,-1}; 21 | } 22 | }; -------------------------------------------------------------------------------- /Binary Search/374. Guess Number Higher or Lower: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param num your guess 4 | * @return -1 if num is higher than the picked number 5 | * 1 if num is lower than the picked number 6 | * otherwise return 0 7 | * int guess(int num); 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int guessNumber(int n) { 13 | 14 | int beg=1,end=n,mid=0; 15 | 16 | while(beg<=end){ 17 | 18 | // mid=(beg+end)/2; 19 | 20 | mid=beg+(end-beg)/2; 21 | if(guess(mid)==0) return mid; 22 | 23 | else if(guess(mid)==-1) end=mid-1; 24 | 25 | else beg=mid+1; 26 | } 27 | 28 | return mid; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Binary Search/633. Sum of Square Numbers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeSquareSum(int c) { 4 | // long long 5 | for(long long int a=0;a*a<=c;a++){ 6 | long long int target= c-a*a; 7 | 8 | int beg=0,end=c-a*a; 9 | 10 | while(beg<=end){ 11 | 12 | long long int mid=beg+(end-beg)/2; 13 | long long int search=mid*mid; 14 | //a=0 15 | //s=1 16 | 17 | if(search>target) end=mid-1; 18 | else if(search < target) beg=mid+1; //b=2 19 | else { 20 | 21 | // we found b such that c-a^2 = b^2 22 | 23 | return true; 24 | } 25 | 26 | } 27 | 28 | } 29 | 30 | return false; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Binary Search/852. Peak Index in a Mountain Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& arr) { 4 | 5 | int beg=0,end=arr.size()-1; 6 | while(beg<=end){ 7 | int mid=(beg+end)/2; 8 | 9 | //arr[mid]& stones){ 6 | if(i==stones.size()){ 7 | return abs(tot-(sum-tot)); 8 | } 9 | if(dp[i][tot]!=-1){ 10 | return dp[i][tot]; 11 | } 12 | 13 | int include= dfs(i+1,tot+stones[i],sum,stones); 14 | int exclude= dfs(i+1,tot,sum,stones); 15 | return dp[i][tot] = min(include,exclude); 16 | } 17 | 18 | int lastStoneWeightII(vector& stones) { 19 | 20 | int sum = accumulate(stones.begin(),stones.end(),0); 21 | memset(dp,-1,sizeof(dp)); 22 | return dfs(0,0,sum,stones); 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /DP/152. Maximum Product Subarray: -------------------------------------------------------------------------------- 1 | int maxProduct(vector& nums) { 2 | int ans = nums[0]; 3 | int cmax=1,cmin=1; 4 | for(int i=0;i &ans){ 15 | if(!root) return; 16 | ans.push_back(root->val); 17 | solve(root->left,ans); 18 | solve(root->right,ans); 19 | } 20 | vector getAllElements(TreeNode* root1, TreeNode* root2) { 21 | vector ans; 22 | solve(root1,ans); 23 | solve(root2,ans); 24 | sort(ans.begin(),ans.end()); 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Hash Maps/1_twoSum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/Hash Maps/1_twoSum.cpp -------------------------------------------------------------------------------- /Hash Maps/2215_diff2Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findDifference(vector& nums1, vector& nums2) { 4 | 5 | unordered_set s1; 6 | unordered_set s2; 7 | vector> ans(2); 8 | for(auto i: nums1){ 9 | s1.insert(i); 10 | } 11 | for(auto i: nums2){ 12 | s2.insert(i); 13 | } 14 | for(auto i : s1){ 15 | if(!s2.count(i)){ 16 | ans[0].push_back(i); 17 | } 18 | } 19 | for(auto i : s2){ 20 | if(!s1.count(i)){ 21 | ans[1].push_back(i); 22 | } 23 | } 24 | return ans; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /Hash Maps/2325_decode_the_message.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeMessage(string key, string message) { 4 | //create mapping 5 | unordered_mapmapping; 6 | 7 | char ch='a'; 8 | for(auto curr:key){ 9 | if(mapping.find(curr)==mapping.end() && curr!=' '){ 10 | 11 | mapping[curr]=ch++; 12 | } 13 | 14 | } 15 | 16 | string ans=""; 17 | 18 | //decode with the help of created map 19 | for(auto curr:message){ 20 | if(curr==' ') 21 | ans=ans+' '; 22 | 23 | else 24 | ans=ans+mapping[curr]; 25 | 26 | } 27 | 28 | return ans ; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Hash Maps/242_valid_anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if(s.size() != t.size()) return false; 5 | 6 | unordered_map counts; 7 | 8 | for(int i=0;i> findMatrix(vector& nums) { 4 | unordered_map freq; 5 | int cnt=0; 6 | for(int i:nums){ 7 | freq[i]++; 8 | cnt=max(cnt,freq[i]); 9 | } 10 | 11 | vector> ans(cnt); 12 | 13 | for(auto e:freq){ 14 | int num_freq = e.second; 15 | int num = e.first; 16 | for(int i=0;i> groupAnagrams(vector& strs) { 7 | unordered_map>umap; 8 | for(auto s:strs){ 9 | string sorted=s; 10 | 11 | sort(sorted.begin(),sorted.end()); 12 | umap[sorted].push_back(s); 13 | } 14 | vector>ans; 15 | for(auto i:umap) ans.push_back(i.second); 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Hash Maps/706_design_hashmap.cpp: -------------------------------------------------------------------------------- 1 | class MyHashMap { 2 | public: 3 | 4 | vector ans; 5 | MyHashMap() { 6 | ans = vector(1e6 + 1, -1); 7 | } 8 | 9 | void put(int key, int value) { 10 | ans[key] = value; 11 | } 12 | 13 | int get(int key) { 14 | return ans[key]; 15 | } 16 | 17 | void remove(int key) { 18 | ans[key] = -1; 19 | } 20 | }; 21 | 22 | -------------------------------------------------------------------------------- /Hash Maps/771_jewels_and_stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numJewelsInStones(string jewels, string stones) { 4 | unordered_map umap; 5 | for(auto i:stones){ 6 | umap[i]++; 7 | } 8 | int ans = 0; 9 | for(char i:jewels){ 10 | ans += umap[i]; 11 | } 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /Hash Maps/853.Car_Fleet.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int carFleet(int target, vector& position, vector& speed) { 4 | int n = position.size(); 5 | if(n == 1) 6 | return 1; 7 | 8 | vector> cars; 9 | 10 | for(int i=0;i=0;i--){ 21 | double time = cars[i].second; 22 | if(time > maxtime){ 23 | maxtime = time; 24 | ans++; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Heap/347_top_k_frequent_elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | unordered_mapum; 5 | for(int i=0; i>v; 9 | for(auto i:um){ 10 | v.push_back({i.first, i.second}); 11 | } 12 | sort(v.rbegin(), v.rend(), [](auto &left, auto &right){ 13 | return left.secondans; 16 | for(auto i:v){ 17 | ans.push_back(i.first); 18 | if(ans.size()==k) 19 | break; 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /Linked List/138_copy_list_with_random_pointer.cpp: -------------------------------------------------------------------------------- 1 | //2 pass solution with time complexity O(n) 2 | 3 | class Solution { 4 | public: 5 | Node* copyRandomList(Node* head) { 6 | map m; 7 | int i=0; 8 | Node* ptr = head; 9 | while (ptr) { 10 | m[ptr] =new Node(ptr->val); 11 | ptr = ptr->next; 12 | } 13 | ptr = head; 14 | while (ptr) { 15 | m[ptr]->next = m[ptr->next]; 16 | m[ptr]->random = m[ptr->random]; 17 | ptr = ptr->next; 18 | } 19 | return m[head]; 20 | } 21 | }; -------------------------------------------------------------------------------- /Linked List/141_linked_list_cycle.cpp: -------------------------------------------------------------------------------- 1 | // link-https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | // Approach 1- Hash map 4 | class Solution { 5 | public: 6 | bool hasCycle(ListNode *head) { 7 | if(!head) return NULL; 8 | unordered_map umap; 9 | ListNode *ptr=head; 10 | while(ptr){ 11 | if(umap[ptr] != 0) return true; 12 | umap[ptr] = 1; 13 | ptr = ptr->next; 14 | } 15 | return false; 16 | } 17 | }; 18 | 19 | // Approach 2- Floyd's Cycle Finding Algorithm (Slow and fast pointer 20 | class Solution { 21 | public: 22 | bool hasCycle(ListNode *head) { 23 | if(!head) return NULL; 24 | ListNode *slow=head, *fast=head->next; 25 | while(slow != fast){ 26 | if(!fast || !fast->next) return false; 27 | fast = fast->next->next; 28 | slow = slow->next; 29 | } 30 | return true; 31 | } 32 | }; -------------------------------------------------------------------------------- /Linked List/2326_spiral_matrix_4.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> spiralMatrix(int m, int n, ListNode* head) { 4 | 5 | int minr=0; 6 | int maxr=m-1; 7 | int minc=0; 8 | int maxc=n-1; 9 | 10 | vector>mat(m,vector(n,-1)); 11 | 12 | ListNode* c=head; 13 | 14 | while(c!=NULL){ 15 | 16 | //left to right 17 | for(int i=minc;i<=maxc && c!=NULL;i++){ 18 | int j=minr; 19 | mat[j][i]=c->val; 20 | c=c->next; 21 | } 22 | minr++; 23 | 24 | //top to bot 25 | for(int i=minr;i<=maxr && c!=NULL;i++){ 26 | int j= maxc; 27 | mat[i][j]=c->val; 28 | c=c->next; 29 | 30 | } 31 | maxc--; 32 | //right to left 33 | 34 | for(int i=maxc;i>=minc && c!=NULL;i-- ){ 35 | int j=maxr; 36 | mat[j][i]=c->val; 37 | c=c->next; 38 | 39 | } 40 | 41 | maxr--; 42 | 43 | //bot to top 44 | 45 | for(int i=maxr;i>=minr && c!=NULL ;i-- ){ 46 | int j=minc; 47 | mat[i][j]=c->val; 48 | c=c->next; 49 | 50 | } 51 | 52 | minc++; 53 | 54 | } 55 | 56 | return mat; 57 | 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Linked List/234. Palindrome Linked List: -------------------------------------------------------------------------------- 1 | bool isPalindrome(ListNode* head) { 2 | //create a new reversed list 3 | //iterate through both 4 | //on first encountering unequal values, return false 5 | 6 | if(head==NULL || head->next==NULL) return true; 7 | 8 | ListNode * rev_head=NULL; 9 | ListNode *ptr=head; 10 | //1 2 2 1 11 | // NULL<-1<-2<-2<-1 12 | while(ptr!=NULL){ 13 | ListNode* temp=new ListNode(ptr->val); 14 | temp->next=rev_head; 15 | rev_head=temp; 16 | ptr=ptr->next; 17 | } 18 | 19 | while(head!=NULL && rev_head!=NULL){ 20 | if(head->val != rev_head->val) return false; 21 | head=head->next; 22 | rev_head=rev_head->next; 23 | 24 | } 25 | 26 | return true; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Linked List/61_rotate_list.cpp: -------------------------------------------------------------------------------- 1 | // link-https://leetcode.com/problems/rotate-list/description/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* rotateRight(ListNode* head, int k) { 6 | 7 | if(!head || !head->next) return head; 8 | ListNode *ptr = head; // list iterator 9 | int size = 1; // to store the size( to be initialised at 1) 10 | 11 | while(ptr->next){ 12 | size++; 13 | ptr = ptr->next; 14 | } 15 | 16 | ptr->next = head; 17 | k = k%size; 18 | 19 | while(size-k>0){ 20 | ptr = ptr->next; 21 | size--; 22 | } 23 | 24 | ListNode* newHead = ptr->next; 25 | ptr->next = NULL; 26 | 27 | return newHead; 28 | } 29 | }; -------------------------------------------------------------------------------- /Linked List/86_partition_list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* partition(ListNode* head, int x) { 14 | ListNode* a = new ListNode(0), *b = new ListNode(0); 15 | ListNode *a1 = a, *b1 = b; 16 | 17 | while(head){ 18 | if(head->valnext = head; 20 | } 21 | else{ 22 | b1 = b1->next = head; 23 | } 24 | head = head->next; 25 | } 26 | b1->next = NULL; 27 | a1->next = b->next; 28 | return a->next; 29 | } 30 | }; -------------------------------------------------------------------------------- /Linked List/876. Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | //1st approach -- finding len and then the mid 15 | 16 | // ListNode * temp=head; 17 | // int len=0; 18 | // while(temp!=NULL){ 19 | // temp=temp->next; 20 | // len++; 21 | 22 | // } 23 | // len=len/2; 24 | // temp=head; 25 | // for(int i=0;inext; 27 | // } 28 | 29 | // return temp; 30 | 31 | //fast->2x slow- 32 | 33 | ListNode * slow=head; 34 | ListNode * fast=head; 35 | 36 | // fast - NULL ..... 37 | while(fast && fast->next){ 38 | slow=slow->next; 39 | fast=fast->next->next; 40 | } 41 | 42 | return slow; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Math & Bit Manipulation/191_number_of_1_bits.cpp: -------------------------------------------------------------------------------- 1 | //Solution 1 2 | class Solution { 3 | public: 4 | int hammingWeight(uint32_t n) { 5 | int c = 0; 6 | while(n){ 7 | c += n%2; 8 | n = n>>1; 9 | } 10 | 11 | return c; 12 | } 13 | }; 14 | 15 | //Solution 2 16 | class Solution { 17 | public: 18 | int hammingWeight(uint32_t n) { 19 | int c = 0; 20 | while(n){ 21 | c++; 22 | n = n&(n-1); 23 | } 24 | 25 | return c; 26 | } 27 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CCS-Coding-Community 2 | 3 | Hello all, 4 | Welcome to the official Github repository of CCS Coding Community which is an initiative by Creative Computing Society to boost the coding culture at TIET. With a community of 1800+ members, 7 proficient mentors and 60+ questions discussed till date,CCS Coding Community is one of the best places to kickstart your DSA journey. At Coding Community,we daily share 2 questions - 1 basic(for those who are just getting started) and 1 advanced(for those who have some knowledge of DSA) and at the end of the day, the solutions are discussed and explained by a mentor on a meet. 5 | 6 | ## Be a part of Coding Community 7 | 8 | - [CCS Coding Community Announcements Group](https://chat.whatsapp.com/E56OsqA9WQ274euqXIkK8K) 9 | - [CCS Coding Community Discussion Group](https://chat.whatsapp.com/IgADOXu7p6v06Asl20Ukhf) 10 | ## Date-wise Questions 11 | 12 | Below is a well compiled list of questions discussed till now for your easy reference 13 | 14 | | Date | Easy Question | Hard Question | 15 | |------------|--------------------------------------|--------------------------------------| 16 | | 2023-11-05 | [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | 17 | | 2023-11-06 | [Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation/) | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | 18 | | 2023-11-07 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/description/) | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/) | 19 | | 2023-11-08 | [Running Sum of 1-D Array](https://leetcode.com/problems/running-sum-of-1d-array/description/) | [Linked List Cycle 2](https://leetcode.com/problems/linked-list-cycle-ii/description/) | 20 | | 2023-11-09 | [Majority Element](https://leetcode.com/problems/majority-element/) | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/) | 21 | | 2023-11-10 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Remove nth node from end of list](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | 22 | | 2023-11-11 | [Two Sum 2 Input Array is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Remove duplicates from sorted linked list](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | 23 | | 2023-11-14 | [Create Target Array in Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/description/) | [Rotate List](https://leetcode.com/problems/rotate-list/description/) | 24 | | 2023-11-15 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/) | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/description/) | 25 | | 2023-11-16 | [Number of 1 bits](https://leetcode.com/problems/number-of-1-bits/) | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | 26 | | 2023-11-17 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) | [Spiral Matrix 4](https://leetcode.com/problems/spiral-matrix-iv/) | 27 | | 2023-11-18 | [Range Sum Query Immutable](https://leetcode.com/problems/range-sum-query-immutable/description/) | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | 28 | | 2023-11-19 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [Same Tree](https://leetcode.com/problems/same-tree/) | 29 | | 2023-11-20 | [Two Sum](https://leetcode.com/problems/two-sum/) | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | 30 | | 2023-11-21 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | 31 | | 2023-11-22 | [Decode the Message](https://leetcode.com/problems/decode-the-message/) | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/) | 32 | | 2023-11-23 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/description/) | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | 33 | | 2023-11-24 | [Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/description/) | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | 34 | | 2023-11-25 | [Design Hashmap](https://leetcode.com/problems/design-hashmap/) | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal) | 35 | | 2023-11-26 | [Product of Array except Self]( https://leetcode.com/problems/product-of-array-except-self/description/) | [Path Sum](https://leetcode.com/problems/path-sum/) | 36 | | 2023-11-27 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | 37 | | 2023-12-26 | [Find the difference of two arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/description/) | [Same Tree ](https://leetcode.com/problems/same-tree/description/) | 38 | | 2023-12-27 | [Find pivot index](https://leetcode.com/problems/find-pivot-index/ ) | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | 39 | | 2023-11-28 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) | 40 | | 2023-11-29 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/submissions/946757218) | 41 | | 2023-12-30 | [Sort Colors](https://leetcode.com/problems/sort-colors/description/) | [Subtree of another tree](https://leetcode.com/problems/subtree-of-another-tree/)| 42 | | 2023-01-02 | [Partition List](https://leetcode.com/problems/partition-list/) | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | 43 | | 2023-01-03 | [Convert an array into a 2D Array](https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/) | [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/description/) | 44 | | 2023-01-04 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| 45 | | 2023-01-05 | [Maximum Points you can obtain from cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/) | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| 46 | -------------------------------------------------------------------------------- /Sliding Window/temp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/Sliding Window/temp -------------------------------------------------------------------------------- /Stacks/1047_remove_adj_duplicates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) {n 4 | string ans=""; 5 | for( auto ch:s){ 6 | if(ans.size()==0 || ans.size()>0 && ans.back()!=ch){ 7 | ans.push_back(ch); 8 | } 9 | else{ 10 | ans.pop_back(); 11 | } 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Stacks/1544_make_the_string_great.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeGood(string s) { 4 | string st; 5 | for(auto &i:s){ 6 | if(st.empty() || (st.back() != i-'a'+'A' && st.back() != i+'a'-'A')) st.push_back(i); 7 | else st.pop_back(); 8 | } 9 | return st; 10 | } 11 | }; -------------------------------------------------------------------------------- /Stacks/20_valid_parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | map umap; 5 | umap[']']='['; 6 | umap['}']='{'; 7 | umap[')']='('; 8 | stack st; 9 | for(auto &i:s){ 10 | if(i=='[' || i=='(' || i=='{'){ 11 | st.push(i); 12 | } 13 | else{ 14 | if(st.empty()) return false; 15 | else{ 16 | if(st.top()==umap[i]){ 17 | st.pop(); 18 | } 19 | else return false; 20 | } 21 | } 22 | } 23 | return st.empty(); 24 | } 25 | }; -------------------------------------------------------------------------------- /Stacks/2696. Minimum String Length After Removing Substrings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minLength(string s) { 4 | string ans=""; 5 | for(int i=0;i nextGreaterElement(vector& nums1, vector& nums2) { 4 | unordered_map mpp; 5 | vector ans(nums1.size(),-1); 6 | stack st; 7 | for(int i=0;ifirst iteration 16 | //[]->first iteration stack 17 | 18 | } 19 | if(mpp.find(current)!=mpp.end()){ 20 | st.push(current); 21 | } 22 | //st->[1] 23 | //st->[4]->2nd iteration 24 | //st->[4,2]->3rd iteration 25 | 26 | 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Stacks/735_asteroid_collision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& ast) { 4 | int n = ast.size(); 5 | stack s; 6 | for(int i=0;i0 || s.empty()) s.push(ast[i]); 8 | else{ 9 | while(!s.empty() && s.top()>0 && s.top() result(s.size()); 23 | // int i = s.size()-1; 24 | for(int i = s.size()-1;i>=0;i--){ 25 | result[i] = s.top(); 26 | s.pop(); 27 | // i--; 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /Stacks/844_backspace-string-compare: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool backspaceCompare(string s, string t) { 4 | stack s1,s2; 5 | for(char ch : s){ 6 | if(ch == '#'){ 7 | if(!s1.empty()) 8 | s1.pop(); 9 | } 10 | else 11 | s1.push(ch); 12 | } 13 | 14 | for(char ch : t){ 15 | if(ch == '#'){ 16 | if(!s2.empty()) 17 | s2.pop(); 18 | } 19 | else 20 | s2.push(ch); 21 | } 22 | 23 | if(s1.empty() && s2.empty()) return true; 24 | if(s1.size() != s2.size()) return false; 25 | 26 | while(!s1.empty() && !s2.empty()){ 27 | if(s1.top() != s2.top()) return false; 28 | s1.pop(); 29 | s2.pop(); 30 | } 31 | return true; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Trees/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/Trees/.DS_Store -------------------------------------------------------------------------------- /Trees/100_same_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSameTree(TreeNode* p, TreeNode* q) { 4 | if(!p && !q) return true; 5 | 6 | if(!p || !q) return false; 7 | 8 | if(p->val != q->val) return false; 9 | 10 | return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); 11 | } 12 | }; -------------------------------------------------------------------------------- /Trees/101. Symmetric Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymmetric(TreeNode* root) { 15 | if(!root) return true; 16 | return helper(root->left,root->right); 17 | 18 | } 19 | 20 | bool helper(TreeNode* p,TreeNode* q){ 21 | if(!p && !q) return true; 22 | else if(!p || !q) return false; 23 | 24 | if(p->val!=q->val) return false; 25 | 26 | return helper(p->right,q->left) && helper(p->left,q->right); 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Trees/103_binary_tree_zigzag_level_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector> ans; 16 | if(!root) 17 | return ans; 18 | 19 | queue q; 20 | q.push(root); 21 | bool rev = false; 22 | while(!q.empty()){ 23 | int s = q.size(); 24 | vector ans2(s,0); 25 | for(int i=0;ival; 30 | }else { 31 | ans2[i] = ptr->val; 32 | } 33 | if(ptr->left) q.push(ptr->left); 34 | if(ptr->right) q.push(ptr->right); 35 | } 36 | ans.push_back(ans2); 37 | rev = !rev; 38 | } 39 | return ans; 40 | } 41 | }; -------------------------------------------------------------------------------- /Trees/104_maximum_depth_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | if(root == NULL) return 0; 5 | int leftDepth = maxDepth(root->left); 6 | int rightDepth = maxDepth(root->right); 7 | 8 | return max(leftDepth, rightDepth)+1; 9 | } 10 | }; -------------------------------------------------------------------------------- /Trees/106_construct_tree_from_io_po.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* build(vector&io,int i_st, int i_en, vector&po,int p_st, int p_en, unordered_map < int, int > &hm){ 4 | if((p_st > p_en) || (i_st > i_en)) 5 | return NULL; 6 | 7 | int root_index = hm[po[p_en]]; 8 | int num_ele = root_index - i_st; 9 | // If root lies at x+1 then 1st x elements of inorder gives us the LEFT SUBTREE 10 | 11 | TreeNode* root = new TreeNode(po[p_en]); 12 | root->left = build(io, i_st, root_index - 1,po, p_st, p_st+num_ele-1, hm); 13 | root->right = build(io, root_index+1,i_en, po, p_st + num_ele, p_en-1, hm); 14 | return root; 15 | } 16 | 17 | TreeNode* buildTree(vector& io, vector& po) { 18 | int p_len = po.size(); 19 | int i_len = io.size(); 20 | if(p_len != i_len) 21 | return NULL; 22 | 23 | unordered_map hm; 24 | 25 | for(int i = 0; i < i_len; i++) 26 | hm[io[i]] = i; 27 | 28 | return build(io, 0, i_len-1, po,0, p_len - 1, hm); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Trees/110_balanceBT.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int height(TreeNode * root){ 15 | if(root==NULL){ 16 | return 0; 17 | } 18 | int left=height(root->left); 19 | int right=height(root->right); 20 | 21 | return 1+max(left,right); 22 | 23 | } 24 | bool isBalanced(TreeNode* root) { 25 | if(root==NULL){ 26 | return true; 27 | } 28 | 29 | bool left=isBalanced(root->left); 30 | bool right= isBalanced(root->right); 31 | if(!left || !right){ 32 | return false; 33 | } 34 | return(abs(height(root->left)-height(root->right))<=1); 35 | 36 | } 37 | }; -------------------------------------------------------------------------------- /Trees/116_populating_next_right_pointer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | Node* left; 7 | Node* right; 8 | Node* next; 9 | 10 | Node() : val(0), left(NULL), right(NULL), next(NULL) {} 11 | 12 | Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} 13 | 14 | Node(int _val, Node* _left, Node* _right, Node* _next) 15 | : val(_val), left(_left), right(_right), next(_next) {} 16 | }; 17 | */ 18 | 19 | class Solution { 20 | public: 21 | Node* connect(Node* root) { 22 | 23 | if(root==NULL) return NULL; 24 | if(root->left!=NULL){ 25 | (root->left)->next=root->right; 26 | } 27 | connect(root->left); 28 | 29 | //go to the left of the next node to the root 30 | if(root->next!=NULL && root->right!=NULL ) 31 | {(root->right)->next=(root->next)->left;} 32 | 33 | connect(root->right); 34 | 35 | return root; 36 | 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Trees/145_binary_tree_postorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | // recursive method 2 | 3 | class Solution { 4 | public: 5 | 6 | void traversal(vector &res, TreeNode* node){ 7 | // Left Right Parent 8 | 9 | if(node->left){ 10 | traversal(res, node->left); 11 | } 12 | 13 | if(node->right){ 14 | traversal(res, node->right); 15 | } 16 | 17 | res.push_back(node->val); 18 | 19 | } 20 | vector postorderTraversal(TreeNode* root) { 21 | vector res; 22 | 23 | if(root){ 24 | traversal(res, root); 25 | } 26 | 27 | return res; 28 | } 29 | }; 30 | 31 | // iterative method 32 | 33 | class Solution { 34 | public: 35 | vector postorderTraversal(TreeNode* root) { 36 | vector res; 37 | stack st; 38 | TreeNode* node = root; 39 | TreeNode* last = NULL; 40 | 41 | while(node || !st.empty()){ 42 | if(node){ 43 | st.push(node); 44 | node = node->left; 45 | }else{ 46 | TreeNode* temp = st.top(); 47 | if(temp->right && temp->right != last){ 48 | node = temp->right; 49 | }else{ 50 | res.push_back(temp->val); 51 | last = temp; 52 | st.pop(); 53 | } 54 | } 55 | } 56 | 57 | return res; 58 | } 59 | }; 60 | 61 | // two stack method 62 | 63 | class Solution { 64 | public: 65 | vector postorderTraversal(TreeNode* root) { 66 | vector res; 67 | stack st1; 68 | stack st2; 69 | TreeNode* node = root; 70 | 71 | if(root){ 72 | st1.push(root); 73 | } 74 | 75 | while(!st1.empty()){ 76 | TreeNode* temp = st1.top(); 77 | st1.pop(); 78 | st2.push(temp); 79 | 80 | if(temp->left){ 81 | st1.push(temp->left); 82 | } 83 | 84 | if(temp->right){ 85 | st1.push(temp->right); 86 | } 87 | } 88 | 89 | while(!st2.empty()){ 90 | res.push_back(st2.top()->val); 91 | st2.pop(); 92 | } 93 | 94 | return res; 95 | } 96 | }; -------------------------------------------------------------------------------- /Trees/199.BinaryTreeRightSideView.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector rightSideView(TreeNode* root) { 15 | vector ans; 16 | if(!root) return ans; 17 | 18 | queue q; 19 | q.push(root); 20 | 21 | while(q.size()>0){ 22 | int s = q.size(); 23 | for(int i=0;ileft) q.push(f->left); 27 | if(f->right) q.push(f->right); 28 | 29 | if(i == s-1) 30 | ans.push_back(f->val); 31 | } 32 | } 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /Trees/226_invert_binary_tree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/creative-computing-society/CCS-Coding-Community/39a80b6e882dc9cda3d95a893d326bde26c7a418/Trees/226_invert_binary_tree.cpp -------------------------------------------------------------------------------- /Trees/235_lowest_common_ancestor_of_BST.cpp: -------------------------------------------------------------------------------- 1 | 2 | //recursive 3 | // keep descending in the tree until the node satisfies BST property 4 | // ie; value of left < node < right 5 | class Solution { 6 | public: 7 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 8 | if(root->val > p->val && root->val > q->val) 9 | return lowestCommonAncestor(root->left,p,q); 10 | if(root->val < p->val && root->val < q->val) 11 | return lowestCommonAncestor(root->right,p,q); 12 | 13 | return root; 14 | } 15 | }; 16 | 17 | //iterative 18 | // same logic 19 | class Solution { 20 | public: 21 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 22 | while(1){ 23 | if(root->val > p->val && root->val > q->val) 24 | root=root->left; 25 | 26 | else if(root->val < p->val && root->val < q->val) 27 | root=root->right; 28 | else 29 | break; 30 | } 31 | return root; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Trees/404. Sum of Left Leaves: -------------------------------------------------------------------------------- 1 | int tot=0; 2 | 3 | void dfs(bool is_left, TreeNode* curr){ 4 | if(curr==NULL) return; 5 | // left + leaf 6 | if(is_left && (curr->left==NULL && curr->right==NULL)){ 7 | tot+=(curr->val); 8 | return ; 9 | } 10 | 11 | dfs(true,curr->left); 12 | dfs(false,curr->right); 13 | 14 | } 15 | 16 | int sumOfLeftLeaves(TreeNode* root) { 17 | dfs(false,root); 18 | return tot; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Trees/530_min_abs_diff_in_bst.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int inorder(TreeNode * root,int & val,int &min_dif){ 5 | 6 | if(root->left!=NULL){ 7 | inorder(root->left,val,min_dif); 8 | } 9 | if(val>=0){ 10 | min_dif=min(min_dif,(root->val)-val); 11 | } 12 | 13 | val=root->val; 14 | 15 | if(root->right!=NULL){ 16 | inorder(root->right,val,min_dif); 17 | } 18 | 19 | 20 | return min_dif; 21 | 22 | } 23 | 24 | int getMinimumDifference(TreeNode* root) { 25 | 26 | int min_dif=INT_MAX, val=-1; 27 | 28 | return inorder(root,val,min_dif); 29 | 30 | 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Trees/544_diameter-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int solve(int &res,TreeNode* root){ 15 | if(!root) return 0; 16 | 17 | int left = solve(res,root->left); 18 | int right = solve(res,root->right); 19 | 20 | res = max(res,left + right); 21 | 22 | return 1 + max(left,right); 23 | } 24 | int diameterOfBinaryTree(TreeNode* root) { 25 | int res = INT_MIN; 26 | solve(res,root); 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /Trees/572_subtree_of_another_tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSubtree(TreeNode* root, TreeNode* subRoot) { 15 | //leetcode- same tree 16 | //edge cases: 17 | if(!subRoot){ 18 | return true; 19 | } 20 | if(!root && subRoot){ 21 | return false; 22 | } 23 | if(isSame(root, subRoot)){ 24 | return true; 25 | } 26 | return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); 27 | } 28 | private: 29 | bool isSame(TreeNode* root1, TreeNode* root2){ 30 | //func to check if two trees are same: 31 | //base cases: 32 | if(!root1 && !root2){ 33 | return true; 34 | } 35 | if(!root1 || !root2){ 36 | return false; 37 | } 38 | if(root1->val ==root2->val){ 39 | if(!isSame(root1->left, root2->left)){ 40 | return false; 41 | } 42 | if (!isSame(root1->right, root2->right)){ 43 | return false; 44 | } 45 | } 46 | else{ 47 | return false; 48 | } 49 | return true; 50 | } 51 | }; -------------------------------------------------------------------------------- /Trees/617_mergeBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), 10 | * right(right) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | TreeNode* helper(TreeNode* root1, TreeNode* root2) { 16 | TreeNode* root = new TreeNode(0); 17 | if (root1 == nullptr && root2 == nullptr) { 18 | return nullptr; 19 | } 20 | if (root1 != nullptr) { 21 | root->val += root1->val; 22 | } 23 | if (root2 != nullptr) { 24 | root->val += root2->val; 25 | } 26 | root->left = helper(root1 ? root1->left : nullptr, 27 | root2 ? root2->left : nullptr); 28 | root->right = helper(root1 ? root1->right : nullptr, 29 | root2 ? root2->right : nullptr); 30 | return root; 31 | } 32 | TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { 33 | return helper(root1, root2); 34 | } 35 | }; -------------------------------------------------------------------------------- /Trees/637_avg_of_levels_in_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map>mp; 4 | 5 | void traverse(TreeNode *r,int level){ 6 | if(r==NULL) return; 7 | //update sum at that level 8 | mp[level].first+=r->val; 9 | //a new node is added so update count 10 | mp[level].second++; 11 | 12 | traverse(r->left,level+1); 13 | traverse(r->right,level+1); 14 | 15 | 16 | } 17 | vector averageOfLevels(TreeNode* root) { 18 | vectorans; 19 | traverse(root,0); 20 | 21 | for(auto i:mp) 22 | ans.push_back(i.second.first/i.second.second); 23 | 24 | 25 | return ans; 26 | } 27 | }; 28 | 29 | 30 | //BFS solution using queue 31 | 32 | class Solution { 33 | public: 34 | vector averageOfLevels(TreeNode* root) { 35 | if (!root) { 36 | return {}; 37 | } 38 | vector avgs; 39 | queue todo; 40 | todo.push(root); 41 | while (!todo.empty()) { 42 | int n = todo.size(); 43 | double sum = 0.0; 44 | for (int i = 0; i < n; i++) { 45 | TreeNode* node = todo.front(); 46 | todo.pop(); 47 | sum += node -> val; 48 | if (node -> left) { 49 | todo.push(node -> left); 50 | } 51 | if (node -> right) { 52 | todo.push(node -> right); 53 | } 54 | } 55 | avgs.push_back(sum / n); 56 | } 57 | return avgs; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Trees/662_maximum_width_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int widthOfBinaryTree(TreeNode* root) { 4 | if(!root) return 0; 5 | long long res = 1; 6 | queue> q; 7 | q.push({root,0}); 8 | while(!q.empty()){ 9 | long long count = q.size(); 10 | int start = q.front().second; 11 | res = max(res, q.back().second-q.front().second+1); 12 | for(int i = 0;i p = q.front(); 14 | long long index = p.second-start; 15 | q.pop(); 16 | if(p.first->left){ 17 | q.push({p.first->left, 2*index+1}); 18 | } 19 | if(p.first->right){ 20 | q.push({p.first->right, 2*index+2}); 21 | } 22 | } 23 | } 24 | return res; 25 | } 26 | }; -------------------------------------------------------------------------------- /Trees/94_binary_tree_inorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | //recursive method 2 | class Solution { 3 | public: 4 | void dfs(vector& tree, TreeNode* root){ 5 | if(root->left){ 6 | dfs(tree, root->left); 7 | } 8 | tree.push_back(root->val); 9 | if(root->right){ 10 | dfs(tree, root->right); 11 | } 12 | } 13 | vector inorderTraversal(TreeNode* root) { 14 | vector res; 15 | if(root) dfs(res, root); 16 | 17 | return res; 18 | 19 | } 20 | }; 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 29 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 30 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 31 | * }; 32 | */ 33 | 34 | //iterative method 35 | class Solution { 36 | public: 37 | vector inorderTraversal(TreeNode* root) { 38 | stack stk; 39 | vector res; 40 | TreeNode* current = root; 41 | 42 | while(!stk.empty() || current != NULL){ 43 | while(current != NULL){ 44 | stk.push(current); 45 | current = current->left; 46 | } 47 | 48 | TreeNode* node = stk.top(); 49 | res.push_back(node->val); 50 | stk.pop(); 51 | current = node->right; 52 | } 53 | 54 | return res; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Trees/958_check_completeness_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isCompleteTree(TreeNode* root) { 4 | queue q; 5 | q.push(root); 6 | 7 | bool flag = false; 8 | 9 | while(!q.empty()){ 10 | TreeNode* front = q.front(); 11 | 12 | if(!front){ 13 | flag = true; 14 | } 15 | else{ 16 | if(flag){ 17 | return false; 18 | } 19 | 20 | q.push(front->left); 21 | q.push(front->right); 22 | 23 | } 24 | 25 | q.pop(); 26 | } 27 | return true; 28 | 29 | } 30 | }; -------------------------------------------------------------------------------- /Trees/98_validate_binary_search_tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidBST(TreeNode* root) { 4 | long prev = (long)INT_MIN-1; 5 | return solve(root, prev); 6 | } 7 | bool solve(TreeNode* root, long &prev){ 8 | if(root->left){ 9 | if(solve(root->left, prev) == false) return false; 10 | } 11 | if(prevval){ 12 | prev = root->val; 13 | } 14 | else{ 15 | return false; 16 | } 17 | if(root->right){ 18 | if(solve(root->right, prev) == false) return false; 19 | } 20 | return true; 21 | } 22 | }; -------------------------------------------------------------------------------- /Trees/99_recover_bst.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | // 2 wrong pairs 5 | 6 | // 2, 1, 3. 1 pair is out of order 7 | // 1, 7, 3, 5, 6, 2, 8, 2 pairs 8 | // 7.3 9 | // 6,2 10 | 11 | // 1st ele of 1st pair and 2nd ele of 2nd pair 12 | 13 | TreeNode * first, *sec , *prev; 14 | 15 | void inorder(TreeNode* root){ 16 | if(root==NULL) return ; 17 | inorder(root->left); 18 | if(prev!=NULL && prev->val > root->val ){ 19 | if(first==NULL){ 20 | first=prev; 21 | } 22 | sec=root; 23 | } 24 | 25 | prev=root; 26 | 27 | inorder(root->right); 28 | } 29 | 30 | 31 | void recoverTree(TreeNode* root) { 32 | first=NULL; 33 | sec=NULL; 34 | prev=NULL; 35 | inorder(root); 36 | 37 | swap(first->val,sec->val); 38 | 39 | } 40 | }; 41 | --------------------------------------------------------------------------------