├── .idea ├── .gitignore ├── Daily-Coding-Problem.iml ├── misc.xml ├── modules.xml └── vcs.xml ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── README.md ├── Solution ├── Day-001.cpp ├── Day-002.cpp ├── Day-003.cpp ├── Day-004.cpp ├── Day-005.cpp ├── Day-006.cpp ├── Day-007.cpp ├── Day-008.cpp ├── Day-009.cpp ├── Day-010.cpp ├── Day-011.cpp ├── Day-012.cpp ├── Day-013.cpp ├── Day-014.cpp ├── Day-015.cpp ├── Day-016.cpp ├── Day-017.cpp ├── Day-018.cpp ├── Day-019.cpp ├── Day-020.cpp ├── Day-021.cpp ├── Day-022.cpp ├── Day-023.cpp ├── Day-025.cpp ├── Day-026.cpp ├── Day-027.cpp ├── Day-028.cpp ├── Day-029.cpp ├── Day-030.cpp ├── Day-031.cpp ├── Day-032.cpp ├── Day-033.cpp ├── Day-034.cpp ├── Day-035.cpp ├── Day-036.cpp ├── Day-037.cpp ├── Day-038.cpp ├── Day-039.cpp ├── Day-040.cpp ├── Day-041.cpp ├── Day-042.cpp ├── Day-043.cpp ├── Day-044.cpp ├── Day-045.cpp ├── Day-046.cpp ├── Day-047.cpp ├── Day-048.cpp ├── Day-049.cpp ├── Day-050.cpp ├── Day-051.cpp ├── Day-052.cpp ├── Day-053.cpp ├── Day-054.cpp ├── Day-055.cpp ├── Day-056.cpp ├── Day-057.cpp ├── Day-058.cpp ├── Day-059.cpp ├── Day-060.cpp ├── Day-061.cpp ├── Day-062.cpp ├── Day-063.cpp ├── Day-064.cpp ├── Day-065.cpp ├── Day-068.cpp ├── Day-069.cpp ├── Day-070.cpp ├── Day-071.cpp ├── Day-072.cpp ├── Day-073.cpp ├── Day-074.cpp ├── Day-075.cpp ├── Day-076.cpp ├── Day-077.cpp ├── Day-078.cpp ├── Day-079.cpp ├── Day-080.cpp ├── Day-081.cpp ├── Day-082.cpp ├── Day-083.cpp ├── Day-084.cpp ├── Day-085.cpp ├── Day-086.cpp ├── Day-087.cpp ├── Day-088.cpp ├── Day-089.cpp ├── Day-090.cpp ├── Day-091.py ├── Day-092.cpp ├── Day-093.cpp ├── Day-094.cpp ├── Day-095.cpp ├── Day-096.cpp ├── Day-097.cpp ├── Day-098.cpp ├── Day-099.cpp ├── Day-100.cpp ├── Day-101.cpp ├── Day-102.cpp ├── Day-103.cpp ├── Day-104.cpp ├── Day-105.cpp ├── Day-106.cpp ├── Day-107.cpp ├── Day-108.cpp ├── Day-109.cpp ├── Day-110.cpp ├── Day-111.cpp ├── Day-112.cpp ├── Day-113.cpp ├── Day-114.cpp ├── Day-115.cpp ├── Day-116.cpp ├── Day-117.cpp ├── Day-118.cpp ├── Day-119.cpp ├── Day-120.cpp ├── Day-122.cpp ├── Day-124.cpp ├── Day-128.cpp ├── Day-133.cpp ├── Day-134.cpp ├── Day-136.cpp ├── Day-166.cpp ├── Day-170.cpp ├── Day-178.cpp ├── Day-180.cpp ├── Day-185.cpp ├── Day-191.cpp ├── Day-200.cpp ├── Day-214.cpp ├── Day-221.cpp ├── Day-222.cpp ├── Day-223.cpp ├── Day-224.cpp ├── Day-225.cpp ├── Day-231.cpp ├── Day-232.cpp ├── Day-241.cpp ├── Day-242.cpp ├── Day-244.cpp ├── Day-255.cpp ├── Day-256.cpp ├── Day-257.cpp ├── Day-258.cpp ├── Day-259.cpp ├── Day-260.cpp ├── Day-261.cpp ├── Day-262.cpp ├── Day-263.cpp ├── Day-265.cpp ├── Day-269.cpp ├── Day-272.cpp ├── Day-273.cpp ├── Day-282.cpp ├── Day-285.cpp ├── Day-287.cpp ├── Day-288.cpp ├── Day-340.cpp ├── Day-341.cpp ├── Day-351.cpp ├── Day-362.cpp ├── Day-547.cpp ├── Day-558.cpp ├── Day-559.cpp ├── Day-560.cpp ├── Day-561.cpp ├── Day-562.cpp ├── Day-567.cpp ├── Day-568.cpp ├── Day-574.cpp ├── Day-577.cpp ├── Day-578.cpp ├── Day-579.cpp ├── Day-580.cpp └── Day-582.cpp └── cmake-build-debug ├── .cmake └── api │ └── v1 │ └── query │ ├── cache-v2 │ ├── cmakeFiles-v1 │ ├── codemodel-v2 │ └── toolchains-v1 └── CMakeFiles ├── 3.24.2 ├── CMakeSystem.cmake └── CompilerIdC │ └── CMakeCCompilerId.c ├── CMakeOutput.log └── clion-environment.txt /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/Daily-Coding-Problem.iml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.24) 2 | project(Daily_Coding_Problem) 3 | 4 | set(CMAKE_CXX_STANDARD 14) 5 | 6 | add_executable(Daily_Coding_Problem ) 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | * Be professional. 2 | * Be responsible. 3 | * Be welcoming. 4 | * Be kind. 5 | * Be respectful of other viewpoints and ideas. 6 | * Be supportive and look out for each other. 7 | -------------------------------------------------------------------------------- /Solution/Day-001.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vector< int > result(2 , -1); 5 | map< int, int > temp; 6 | int totalSize = static_cast(nums.size()); 7 | for( int index = 0; index < totalSize; ++index ) { 8 | if(temp.find( nums[ index ] ) != temp.end() ){ 9 | result[0] = index; 10 | result[1] = temp[ nums[ index ] ]; 11 | break; 12 | } 13 | temp[ target - nums[ index ] ] = index; 14 | } 15 | return result; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Solution/Day-002.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | const size_t n= nums.size(); 5 | vectorans(n,1); 6 | int answer =1; 7 | for(size_t i=0;i=0;--i){ 16 | if(i!=0){ 17 | temp = nums[i]; 18 | nums[i] = ans[i-1]*answer; 19 | answer*=temp; 20 | }else{ 21 | nums[i] = answer; 22 | } 23 | } 24 | return nums; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Solution/Day-003.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Codec { 11 | queueq; 12 | TreeNode* desr(void) { 13 | if (q.empty()) { 14 | return nullptr; 15 | } 16 | string temp = q.front(); 17 | q.pop(); 18 | if (temp =="&") { 19 | return nullptr; 20 | } 21 | TreeNode* root = new TreeNode(atoi(temp.c_str())); 22 | root -> left = desr(); 23 | root -> right = desr(); 24 | return root; 25 | } 26 | string s; 27 | void h_ser(TreeNode* root) { 28 | if (root == nullptr) { 29 | s += "&/"; 30 | return ; 31 | } 32 | s += to_string(root->val) + "/"; 33 | h_ser(root->left); 34 | h_ser(root->right); 35 | } 36 | public: 37 | 38 | // Encodes a tree to a single string. 39 | string serialize(TreeNode* root) { 40 | s = ""; 41 | h_ser(root); 42 | return s; 43 | } 44 | 45 | // Decodes your encoded data to tree. 46 | TreeNode* deserialize(string data, int index = 0) { 47 | string temp{}; 48 | for (int i=0; iserialize(root); 64 | // TreeNode* ans = deser->deserialize(tree); 65 | // return ans; 66 | -------------------------------------------------------------------------------- /Solution/Day-004.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This problem was asked by Stripe. Given an array of integers, 3 | * find the first missing positive integer in linear time and constant space. 4 | * 5 | * In other words, find the lowest positive integer that does not exist in the array. 6 | * The array can contain duplicates and negative numbers as well. 7 | * 8 | * For example, the input [3, 4, -1, 1] should give 2. 9 | * 10 | * The input [1, 2, 0] should give 3. 11 | * 12 | * You can modify the input array in-place. 13 | * 14 | */ 15 | /* 16 | * 1. We can do simply with N^2 time complexity just search for each element form 1 17 | * 18 | * 2. We can use un_ordered map & can do it in O(n) but it require extra O(n) space 19 | * 20 | * 3. if array doesn't contain duplicate and negative number then we can use formula n*(n+1)/2 and 21 | * subtract those number present in the array at last we will remain with the lowest number not 22 | * present in the array 23 | * 24 | * 4. now let's separate the negative and positive element and then mark the index at element as -ve 25 | * now the first +ve index is our answer 26 | * 27 | */ 28 | #include 29 | using namespace std; 30 | int main(void){ 31 | int n; 32 | cin>>n; 33 | vectorv(n); 34 | for(auto &itr:v){ 35 | cin>>itr; 36 | itr--; 37 | } 38 | auto itr = partition(v.begin() , v.end() , [](int a){return a>=0;}); 39 | for(auto i = v.begin(); i!=itr; ++i){ 40 | if(*i>=v.size()) 41 | continue; 42 | v.at(*i) = -v.at(*i); 43 | } 44 | int counter = 0; 45 | for(auto i = v.begin();counter<(int)v.size()&&i!=itr; ++i){ 46 | if(v.at(counter)>0){ 47 | cout< 24 | using namespace std; 25 | paircons(int a, int b){ 26 | return make_pair(a,b); 27 | } 28 | int car(pairp){ 29 | return p.first; 30 | } 31 | int cdr(pairp){ 32 | return p.second; 33 | } 34 | int main(void){ 35 | cout< 2 | #include 3 | using namespace std; 4 | struct NODE{ 5 | public: 6 | int data; 7 | NODE *npx; // reference as Next Previous Xor 8 | }; 9 | NODE* Xor(NODE*a , NODE*b){ 10 | return (NODE*)((uintptr_t)a ^ (uintptr_t)b); 11 | } 12 | NODE* PREV = NULL; // store address of previous NODE form last NODE 13 | NODE* END = NULL; // store address of last Node 14 | NODE* NEXT = NULL; // store address of upcoming Node (isn't interesting :) 15 | void add(NODE**HEAD , int value){ 16 | NODE *new_node = new NODE(); 17 | 18 | new_node -> data = value; 19 | 20 | if(*HEAD!=NULL){ 21 | END->npx = Xor(PREV , new_node); 22 | PREV = END; 23 | END = new_node; 24 | END->npx = Xor(PREV , NEXT); 25 | }else{ 26 | new_node->npx = Xor(PREV , NEXT); 27 | *HEAD = new_node; 28 | END = new_node; 29 | } 30 | 31 | return ; 32 | } 33 | NODE * get(int index ,NODE *HEAD){ 34 | NODE * current = HEAD; 35 | NODE * Prev = NULL; 36 | NODE * Next = NULL; 37 | int i=1; 38 | while(inpx , Prev); 41 | Prev = current; 42 | current = Next; 43 | } 44 | return current; 45 | } 46 | void print(NODE*HEAD){ 47 | NODE * current = HEAD; 48 | NODE * Prev = NULL; 49 | NODE * Next = NULL; 50 | while(current!=NULL){ 51 | cout<data<<' '; 52 | Next = Xor(current->npx , Prev); 53 | Prev = current; 54 | current = Next; 55 | } 56 | cout<data==30); 72 | cout<data< 14 | using namespace std; 15 | int main(void){ 16 | string s; 17 | cin>>s; 18 | vectordp(s.size()+1,0); 19 | for(int i=0;i<=(int)s.size();++i){ 20 | if(i==0){ 21 | dp[i] = 1; 22 | continue; 23 | } 24 | if(s[i]!=0){ 25 | dp[i]=dp[i-1]; 26 | } 27 | int x = s[i-1]-'0'; 28 | x*=10; 29 | x+=(s[i]-'0'); 30 | if(x>=10 and x<=26){ 31 | dp[i]+=((i-2)>=0)?dp[i-2]:1; 32 | } 33 | } 34 | cout< 22 | using namespace std; 23 | struct Node{ 24 | Node*left; 25 | Node*right; 26 | int data; 27 | Node():left(nullptr),right(nullptr),data(0){} 28 | }; 29 | int counter{}; 30 | bool unival(Node*root){ 31 | if(root==nullptr){ 32 | return true; 33 | } 34 | bool ok = true; // let this be a unival tree 35 | bool left = unival(root->left); 36 | bool right = unival(root->right); 37 | ok &=left; 38 | ok &=right; 39 | if(!ok)/*if either left or right is not uni-value*/{ 40 | return ok; 41 | } 42 | if(root->left && root->left->data !=root->data){ 43 | return false; 44 | } 45 | if(root->right && root->right->data !=root->data){ 46 | return false; 47 | } 48 | counter++; 49 | return true; 50 | } 51 | int main(void){ 52 | // tree formation 53 | Node*root = new Node(); 54 | root->data = 0; 55 | Node*n1 = new Node(); 56 | n1->left = nullptr; 57 | n1->right= nullptr; 58 | n1->data = 1; 59 | root->left = n1; 60 | 61 | Node*n2 = new Node(); 62 | n2->data = 0; 63 | root->right= n2; 64 | 65 | Node*n3 = new Node(); 66 | Node*n4 = new Node(); 67 | n2->right = n3; n3->data = 0; 68 | n2->left = n4; n4->data = 1; 69 | Node*n5 = new Node(); 70 | Node*n6 = new Node(); 71 | n4->right = n5; 72 | n4->left = n6; 73 | n5->data = 1; 74 | n6->data = 1; 75 | // counting uni-value trees 76 | unival(root); 77 | cout< 17 | using namespace std; 18 | int main(void){ 19 | int number_of_element; 20 | cin>>number_of_element; 21 | vectorelement(number_of_element); 22 | for(auto &itr:element){ 23 | cin>>itr; 24 | } 25 | int including(0) , excluding(0); // consider these as state of dp . HOW ? 26 | // take including as max sum we get till now including this element 27 | // take excluding as max sum we get till now excluding this element 28 | // 29 | // initially both of them are 0. 30 | // 31 | // so in next state what will be our including simple max(including , excluding+current_element) 32 | // 33 | // what will be excluding ; simple the including we got till now because we excluded the current element 34 | // and the max sum we achieved till now is the same as present in the including variable 35 | // 36 | // but how take care of 0 and negative number ????? 37 | // 38 | // simple you can just ignore them they are not going to contribute to answer in any way ;) 39 | // 40 | 41 | for(int current_Index=0;current_Index 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | void test_function(void){ 7 | cout<<"This is testing function "<t ,unsigned int period){ 13 | 14 | std::this_thread::sleep_for(std::chrono::milliseconds(period)); 15 | 16 | t(); 17 | 18 | return; 19 | } 20 | 21 | int main(void){ 22 | timer_function(test_function , 3000); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Solution/Day-011.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Twitter. 3 | 4 | Implement an autocomplete system. 5 | 6 | That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. 7 | 8 | For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. 9 | 10 | Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. 11 | 12 | 13 | */ 14 | #include 15 | using namespace std; 16 | struct Node{ 17 | Node*alphabets[26]; 18 | bool isEnd; // for the end of word 19 | Node(){ 20 | for(int i=0;i<26;++i){ 21 | alphabets[i] = nullptr; 22 | } 23 | isEnd = false; 24 | } 25 | }; 26 | void addword(Node*root,string s){ 27 | Node*t_Node=root; 28 | for(int i=0; i<(int)s.size(); ++i){ 29 | int index = s[i]-'a'; 30 | if(t_Node->alphabets[index]==nullptr){ 31 | t_Node->alphabets[index]=new Node(); 32 | } 33 | t_Node = t_Node->alphabets[index]; 34 | } 35 | t_Node->isEnd = true; 36 | return; 37 | } 38 | bool last(Node*temp){ 39 | for(int i=0;i<26;++i){ 40 | if(temp->alphabets[i]!=nullptr){ 41 | return false; 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | void util(Node*root , string ans){ 48 | if(root->isEnd){ 49 | cout<alphabets[i]!=nullptr){ 56 | ans.push_back(char((int)'a'+i)); 57 | util(root->alphabets[i],ans); 58 | ans.pop_back(); 59 | } 60 | } 61 | } 62 | void autocomplete(Node*root ,string search_Pattern){ 63 | struct Node*temp = root; 64 | for(int i=0;i<(int)search_Pattern.size();++i){ 65 | int index = search_Pattern[i]-'a'; 66 | if(temp->alphabets[index]==nullptr){ 67 | return; 68 | } 69 | temp=temp->alphabets[index]; 70 | } 71 | if(last(temp)){ 72 | cout< 26 | using namespace std; 27 | int main(void){ 28 | int x; // number of stairs can be climbed 29 | cin>>x; // 2 by default 30 | vectorpossible(x); 31 | for(auto &itr:possible){ 32 | cin>>itr; 33 | } 34 | int n; // final stair 35 | cin>>n; 36 | vectordp(n+2); 37 | for(int i=1;i<=n;++i){ 38 | dp[i]=0; 39 | for(auto &itr:possible){ 40 | if(itr==i){ 41 | dp[i]+=1; 42 | } 43 | if(itr>i){ 44 | break; 45 | } 46 | dp[i]+=(i-itr>=0)?dp[i-itr]:0; 47 | } 48 | } 49 | cout< 26 | using namespace std; 27 | int main(void){ 28 | string s; 29 | int k ; 30 | cin>>s>>k; 31 | int i=0 , j=0 , t_max =0 , mx = 1; 32 | arrayfrequency; 33 | fill(frequency.begin() , frequency.end() , 0); 34 | int t_frequency = 0; 35 | while(i<(int)s.size() && j<(int)s.size()){ 36 | if(t_frequency<=k)/*case where distinct element are in range*/{ 37 | if(frequency[s[j]-'a']==0)/*this means that s[j] is not encounter before so this is distinct character for us*/{ 38 | t_frequency++; 39 | } 40 | frequency[s[j]-'a']++; // simple frequency counter 41 | if(t_frequency<=k)/*case where number of distinct character goes out of scope*/{ 42 | mx = max(mx , abs(i-j-1)); 43 | j++; 44 | } 45 | }else/*this will handle the out of scope case*/{ 46 | frequency[s[i]-'a']--; 47 | if(frequency[s[i]-'a']==0)/*this means that s[i] is vanished from our selected string so we can say that we have only 48 | (n-1) distinct character left */{ 49 | t_frequency--; 50 | } 51 | i++; 52 | mx = max(mx , abs(i-j-1)); // choose the max length of string 53 | } 54 | } 55 | cout< P(__) = PI*(r*r) / 4(r*r) 18 | * ==> P(__) = PI/4 19 | * ==> 4*P(__) = PI 20 | */ 21 | 22 | #include 23 | using namespace std; 24 | int main(void){ 25 | srand(time(NULL)); 26 | double C{},R{}; // C = Point generated inside the Circle & R is point generated inside Rectangle 27 | for(int i=0;i<100000;++i){ 28 | double x = double((rand()%(100000+1))/100000.0f); 29 | double y = double((rand()%(100000+1))/100000.0f); 30 | if(x*x+y*y<=1.0f){ 31 | C++; 32 | } 33 | R++; 34 | } 35 | cout<<"Expected Value of PI = "< 24 | using namespace std; 25 | int main(void){ 26 | srand(time(NULL)); 27 | int current_Element = NULL; 28 | double probability = 0; 29 | int n; 30 | cin>>n; // number of elements ; don't worry we are not going to use to calculate the probability of selection 31 | int element_Processed={0}; 32 | while(n--){ 33 | srand(time(NULL)); 34 | int element; 35 | cin>>element; // 36 | if(element_Processed == 0){ 37 | element_Processed++; 38 | current_Element = element; 39 | probability = 1.0f; 40 | continue; 41 | }else if(rand()%2==1)/*case when element should be replaced*/{ 42 | current_Element = element; 43 | } 44 | probability = (probability * (1.0f - double(1.0f/double(element_Processed+1.0f)))); 45 | element_Processed++; 46 | } 47 | printf("Element %d is chosen with probability %.3f",current_Element , probability); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Solution/Day-016.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This problem was asked by Twitter. 3 | 4 | You run an e-commerce website and want to record the last N order ids in a log. 5 | Implement a data structure to accomplish this, with the following API: 6 | 7 | record(order_id): adds the order_id to the log 8 | get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. 9 | You should be as efficient with time and space as possible. 10 | * 11 | */ 12 | 13 | 14 | /* 15 | * let me know if you got any better idea : offamitkumar@gmail.com 16 | */ 17 | #include 18 | using namespace std; 19 | vectorLog; 20 | void record(int order_id){ 21 | Log.emplace_back(order_id); 22 | } 23 | int get_last(int i){ 24 | assert((int)Log.size()>=i); 25 | return Log.at((int)Log.size()-(i-1)-1); 26 | } 27 | int main(void){ 28 | int n; // number of order 29 | cin>>n; 30 | while(n--){ 31 | int order_id; 32 | cin>>order_id; 33 | record(order_id); 34 | } 35 | cout< 22 | using namespace std; 23 | int main(void){ 24 | int n;// size of array 25 | cin>>n; 26 | vectorv(n); 27 | for(auto &itr:v){ 28 | cin>>itr; 29 | } 30 | int k; // window size 31 | cin>>k; 32 | int i=0; 33 | dequeq; 34 | for(i=0;i 15 | using namespace std; 16 | int main(void){ 17 | int n , m; cin>>n>>m; 18 | vector>v(n,vector(m,0)); 19 | for(int i=0;i>v[i][j]; 22 | } 23 | } 24 | int k=m; // number of colors 25 | vector>dp(n+1,vector(k,0)); 26 | // dp[i][j] = cost of building ith house with jth color 27 | for(int j=0;j 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. 8 | 9 | In this example, assume nodes with the same value are the exact same node objects. 10 | 11 | Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. 12 | * 13 | * 14 | * 15 | * 16 | */ 17 | #include 18 | using namespace std; 19 | 20 | struct Node { 21 | int data; 22 | struct Node *next; 23 | }; 24 | int length(struct Node *head) { 25 | int len = 0; 26 | while(head != NULL) { 27 | len++; 28 | head = head->next; 29 | } 30 | return len; 31 | } 32 | struct Node* findMergePoint(struct Node *A, struct Node *B) { 33 | int m = length(A); 34 | int n = length(B); 35 | int d = n - m; 36 | if(m > n) { 37 | struct Node* temp = A; 38 | A = B; 39 | B = temp; 40 | d = m - n; 41 | } 42 | int i; 43 | for(i=0;inext; 45 | } 46 | while(A != NULL && B != NULL) { 47 | if(A == B) { 48 | return A; 49 | } 50 | A = A->next; 51 | B = B->next; 52 | } 53 | return NULL; 54 | } 55 | int main() 56 | { 57 | struct Node *head1 = NULL, *head2 = NULL; 58 | struct Node *temp[7]; 59 | for(int i=0;i<7;i++) { 60 | temp[i] = (Node *)malloc(sizeof(Node)); 61 | } 62 | temp[0]->data = 4; 63 | temp[0]->next = temp[1]; 64 | temp[1]->data = 6; 65 | temp[1]->next = temp[2]; 66 | temp[2]->data = 7; 67 | temp[2]->next = temp[3]; 68 | temp[3]->data = 1; 69 | temp[3]->next = NULL; 70 | temp[4]->data = 9; 71 | temp[4]->next = temp[5]; 72 | temp[5]->data = 3; 73 | temp[5]->next = temp[6]; 74 | temp[6]->data = 5; 75 | temp[6]->next = temp[2]; 76 | 77 | head1 = temp[0]; 78 | head2 = temp[4]; 79 | struct Node *C = findMergePoint(head1, head2); 80 | cout<data; 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Solution/Day-021.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This problem was asked by Snapchat. 3 | 4 | Given an array of time intervals (start, end) for classroom lectures 5 | (possibly overlapping), find the minimum number of rooms required. 6 | 7 | For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. 8 | * 9 | * 10 | */ 11 | #include 12 | using namespace std; 13 | bool compare(paira,pairb){ 14 | return a.first>v; 18 | v.push_back({30,75}); 19 | v.push_back({0,50}); 20 | v.push_back({60,150}); 21 | sort(v.begin(),v.end(),compare); 22 | int counter{},max_end_time=-1;//initially it is -1 23 | for(auto&[start_time,end_time]:v){ 24 | if(max_end_time==-1){ 25 | max_end_time=end_time; 26 | counter=1; 27 | }else{ 28 | if(max_end_time>start_time){ 29 | counter++; 30 | }else{ 31 | max_end_time=end_time; 32 | } 33 | } 34 | } 35 | cout<(s.size()); 5 | int col = static_cast(p.size()); 6 | vector< vector< bool > > dp(row+1 ,vector< bool >( col+1 , false ) ); 7 | dp[ 0 ] [ 0 ] = true; 8 | for(int i =1; i <= col; ++i ) { 9 | if( p[ i-1 ] == '*' ) { 10 | dp[0][i] = dp[ 0 ][ i-2 ]; 11 | } 12 | } 13 | for(int i =1; i <= row; ++i ) { 14 | for(int j=1; j <= col; ++j){ 15 | if( p[ j-1 ] == s[ i-1 ] or p[ j-1 ] == '.' ) { 16 | dp[ i ][ j ] = dp[ i-1 ][ j-1 ]; 17 | }else if( p[ j-1 ] == '*'){ 18 | dp[ i ][ j ] = dp[ i ][ j-2 ]; 19 | if(p[ j-2 ] == '.' || p[ j-2 ] == s[ i-1 ]){ 20 | dp[ i ][ j ] = dp[i][j] | dp[i-1][j]; 21 | } 22 | } 23 | } 24 | } 25 | return dp.back().back(); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Solution/Day-026.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a singly linked list and an integer k, remove the kth last element from the list. 3 | * k is guaranteed to be smaller than the length of the list. 4 | 5 | The list is very long, so making more than one pass is prohibitively expensive. 6 | 7 | Do this in constant space and in one pass. 8 | */ 9 | 10 | /* 11 | * Idea is to use two pointer Here & Tortoise , where Tortoise will first move K+1 node ahead and then both will move with 12 | * at once , when Tortoise pointer hit null then we have to delete the Here+1 node 13 | */ 14 | #include 15 | using namespace std; 16 | struct Node{ 17 | int data; 18 | Node *next; 19 | }; 20 | void print(Node*root){ 21 | Node*temp= root; 22 | while(temp!=NULL){ 23 | cout<data<<" "; 24 | temp= temp->next; 25 | } 26 | puts(""); 27 | return; 28 | } 29 | 30 | Node* get_node(int value){ 31 | Node *temp = new Node(); 32 | temp->next = NULL; 33 | temp->data = value; 34 | return temp; 35 | } 36 | Node* add(Node *root , int value){ 37 | if(root==NULL){ 38 | return get_node(value); 39 | }else{ 40 | root->next = add(root->next , value); 41 | return root; 42 | } 43 | } 44 | void remove(Node*root , int k ){ 45 | Node* here = root , *tor = root; // tortoise & here 46 | ++k; 47 | while(k--){ 48 | tor = tor->next; 49 | } 50 | while(tor!=NULL){ 51 | tor = tor->next; 52 | here = here->next; 53 | } 54 | here->next = here->next->next; 55 | return; 56 | } 57 | int main(int argc , char *argv[]){ 58 | // write you code here 59 | Node *root = NULL; 60 | root = add(root , 10); 61 | root = add(root , 20); 62 | root = add(root , 30); 63 | root = add(root , 40); 64 | root = add(root , 50); 65 | root = add(root , 60); 66 | print(root); 67 | remove(root , 2); /// will delete 50 68 | print(root); 69 | remove(root,1); 70 | print(root); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Solution/Day-027.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | This problem was asked by Facebook. 4 | 5 | Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). 6 | 7 | For example, given the string "([])[]({})", you should return true. 8 | 9 | Given the string "([)]" or "((()", you should return false. 10 | 11 | */ 12 | 13 | class Solution { 14 | 15 | stacktemp; 16 | 17 | public: 18 | 19 | bool isValid(string s) { 20 | 21 | for(auto&itr:s){ 22 | 23 | if(itr == '(' || itr == '[' || itr == '{') { 24 | 25 | temp.push(itr); 26 | 27 | } else{ 28 | 29 | if(temp.size() == 0){ 30 | 31 | return false; 32 | 33 | } 34 | 35 | if( itr == ')' ){ 36 | 37 | if( temp.top() != '(' ) { 38 | 39 | return false; 40 | 41 | }else{ 42 | 43 | temp.pop(); 44 | 45 | } 46 | 47 | }else if( itr == ']' ){ 48 | 49 | if( temp.top() != '[' ) { 50 | 51 | return false; 52 | 53 | }else { 54 | 55 | temp.pop(); 56 | 57 | } 58 | 59 | }else if( itr == '}' ) { 60 | 61 | if( temp.top() != '{' ) { 62 | 63 | return false; 64 | 65 | }else { 66 | 67 | temp.pop(); 68 | 69 | } 70 | } 71 | } 72 | } 73 | return temp.size() == 0; 74 | } 75 | }; 76 | 77 | int main( void ) { 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Solution/Day-029.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Amazon. 3 | 4 | Run-length encoding is a fast and simple method of encoding strings. 5 | The basic idea is to represent repeated successive characters as a single count and character. 6 | For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". 7 | 8 | Implement run-length encoding and decoding. 9 | You can assume the string to be encoded have no digits and consists solely of alphabetic characters. 10 | You can assume the string to be decoded is valid. 11 | 12 | * 13 | * 14 | * 15 | */ 16 | #include 17 | using namespace std; 18 | string encode(string &s){ 19 | string res=""; 20 | for(int i=0;i<(int)s.size();++i){ 21 | int j = i; 22 | int counter{}; 23 | while(s[i]==s[j]){ 24 | ++counter; 25 | ++j; 26 | } 27 | res += to_string(counter) + s[i]; 28 | i = (j-1); 29 | } 30 | return res; 31 | } 32 | string decode(string &s){ 33 | string res = ""; 34 | for(int i=0;i<(int)s.size();++i){ 35 | int counter{}; 36 | while(s[i]>='0' && s[i]<='9'){ 37 | counter = (counter*10)+int(int(s[i])-int('0')); 38 | ++i; 39 | } 40 | res += string(counter , s[i]); 41 | } 42 | return res; 43 | } 44 | int main(void){ 45 | string text = "AAAABBBCCDAA"; 46 | string encoded_string = encode(text); 47 | cout< 25 | 26 | using namespace std; 27 | 28 | int main(void){ 29 | int size_of_array; 30 | cin >> size_of_array; 31 | 32 | vector< int > height_array ( size_of_array ); 33 | 34 | for(auto &height : height_array){ 35 | cin >> height; 36 | } 37 | 38 | int max_level{} , left = 0 , right = size_of_array - 1 , ans{}; 39 | 40 | while(left < right){ 41 | 42 | int lower_height = height_array.at( height_array.at(left) < height_array.at(right) ? left++ : right-- ); // take the lower 43 | 44 | max_level = max( max_level , lower_height ); // max-level/height we have seen so far 45 | 46 | ans += (max_level - lower_height); 47 | } 48 | 49 | cout << ans << '\n' ; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Solution/Day-031.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | This problem was asked by Google. 4 | 5 | The edit distance between two strings refers to the minimum number of character 6 | insertions, 7 | deletions, 8 | and substitutions 9 | required to change one string to the other . 10 | For example, the edit distance between “kitten” and “sitting” is three: substitute the “k” for “s”, 11 | substitute the “e” for “i”, and append a “g”. 12 | 13 | Given two strings, compute the edit distance between them. 14 | */ 15 | /* 16 | * This is well-known dynamic programming problem. 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | int main(void){ 22 | string a , b; 23 | cin >> a >> b; 24 | vector< vector< int > > dp ((int)b.size() + 1 , vector((int)a.size()+1)); 25 | for(int i=0; i < (int) a.size(); ++i){ 26 | dp[i][0] = i; 27 | } 28 | 29 | for(int i=0; i < (int) b.size(); ++i){ 30 | dp[0][i] = i; 31 | } 32 | 33 | for(int i{1}; i < (int) a.size() ; ++i){ 34 | for(int j{1}; j < (int) b.size(); ++j){ 35 | if(a[i-1] == b[i-1]){ 36 | dp[i][j] = dp[i-1][j-1]; 37 | }else{ 38 | dp[i][j] = min( { dp[i-1][j] , dp[i-1][j-1] , dp[i][j-1] } ) + 1; 39 | } 40 | } 41 | } 42 | cout << dp[(int)a.size() - 1][(int)b.size() - 1] << '\n' ; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Solution/Day-033.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | priority_queue, greater>mn; // min of greater values 3 | priority_queue, less>mx; // max of lesser values 4 | public: 5 | MedianFinder() { 6 | 7 | } 8 | 9 | void addNum(int num) { 10 | if (mn.empty()) mn.push(num); 11 | else if (mx.empty()){ 12 | if (mn.top() > num) { 13 | mx.push(num); 14 | } else { 15 | mx.push(mn.top()); 16 | mn.pop(); 17 | mn.push(num); 18 | } 19 | } 20 | else if (num < mx.top()) mx.push(num); 21 | else mn.push(num); 22 | 23 | if ((int)mx.size() -(int) mn.size() >= 2) { 24 | mn.push(mx.top()); 25 | mx.pop(); 26 | } else if ((int)mn.size() -(int) mx.size() >=2) { 27 | mx.push(mn.top()); 28 | mn.pop(); 29 | } 30 | } 31 | 32 | double findMedian() { 33 | if ((mn.size() + mx.size())&1) { 34 | if (mn.size() > mx.size()) { 35 | return mn.top(); 36 | } else{ 37 | return mx.top(); 38 | } 39 | } else { 40 | return (mx.top() + mn.top())/2.0; 41 | } 42 | } 43 | }; 44 | 45 | /** 46 | * Your MedianFinder object will be instantiated and called as such: 47 | * MedianFinder* obj = new MedianFinder(); 48 | * obj->addNum(num); 49 | * double param_2 = obj->findMedian(); 50 | */ 51 | -------------------------------------------------------------------------------- /Solution/Day-034.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Quora. 3 | 4 | Given a string, find the palindrome that can be made by inserting the fewest 5 | number of characters as possible anywhere in the word. 6 | 7 | If there is more than one palindrome of minimum length that can be made, 8 | return the lexicographically earliest one (the first one alphabetically). 9 | 10 | For example, given the string "race", you should return "ecarace", 11 | since we can add three letters to it (which is the smallest amount to make a palindrome). 12 | 13 | There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically. 14 | 15 | As another example, given the string "google", you should return "elgoogle". 16 | 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | bool palin(string s){ 22 | int i=0 , j=(int)s.size()-1; 23 | while(iright.size()){ 41 | return right; 42 | }else if(left.size()right){ 46 | return right; 47 | }else{ 48 | return left; 49 | } 50 | } 51 | } 52 | int main(void){ 53 | string s , rev; 54 | cin >> s; 55 | cout<& nums) { 4 | const int n = (int)nums.size(); 5 | int one=0,zero=0, two=n-1; 6 | while(one <= two){ 7 | if(nums[one] == 2 && one < two){ 8 | swap(nums[two] , nums[one]); 9 | --two; 10 | }else if(nums[one] == 0 && one > zero){ 11 | swap(nums[zero] , nums[one]); 12 | ++zero; 13 | }else{ 14 | ++one; 15 | } 16 | } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Solution/Day-036.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 | int ans; 14 | bool isAnsFound; 15 | int tempCounter; 16 | void getans(TreeNode* root , int k){ 17 | if(isAnsFound){ 18 | return; 19 | } 20 | if(root->right!=nullptr){ 21 | getans(root->right , k); 22 | } 23 | tempCounter++; 24 | if(k==tempCounter){ 25 | isAnsFound = true; 26 | ans = root -> val; 27 | tempCounter++; 28 | return; 29 | } 30 | if(!isAnsFound && root->left != nullptr){ 31 | getans(root->left , k); 32 | } 33 | if(k==tempCounter){ 34 | isAnsFound = true; 35 | ans = root -> val; 36 | return; 37 | } 38 | } 39 | public: 40 | int kthSmallest(TreeNode* root) { 41 | tempCounter =0; 42 | ans = -1; 43 | isAnsFound = false; 44 | getans(root , 2); 45 | return ans; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Solution/Day-037.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Google. 3 | 4 | The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. 5 | 6 | For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. 7 | 8 | You may also use a list or array to represent a set. 9 | 10 | */ 11 | 12 | 13 | /* 14 | * you could use vector < vector > and sort them in last to get a list of list 15 | * 16 | */ 17 | #include 18 | using namespace std; 19 | int main(int argc , char *argv[]){ 20 | // write you code here 21 | vector< int > arr {1 , 2 , 3}; 22 | int bit = (1 << (int)arr.size()); 23 | for(int i{}; i < bit; ++i){ 24 | vector< int > element; 25 | for(int j=0; j<(int)arr.size(); ++j){ 26 | if(i&(1< 13 | using namespace std; 14 | bitset<40>column , d1 , d2; // d1 -> diagonal 1 & d2 -> diagonal 2 15 | int NQueen(int n , int current){ 16 | if(current == n){ 17 | return 1; 18 | } 19 | 20 | int ways{}; 21 | 22 | for(int i=0; i>n; 39 | cout << NQueen(n , 0) << '\n'; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Solution/Day-040.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Google. 3 | 4 | Given an array of integers where every integer occurs three times except for one integer, 5 | which only occurs once, find and return the non-duplicated integer. 6 | 7 | For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19. 8 | 9 | Do this in O(N) time and O(1) space. 10 | */ 11 | #include 12 | using namespace std; 13 | int main(int argc , char *argv[]){ 14 | // write you code here 15 | vector< int > array_1 { 6, 1, 3, 3, 3, 6, 6 }; 16 | vector< int > array_2 { 13, 19, 13, 13 }; 17 | vector< int > bit(30, 0); // if values goes higher then take a largest bit - array 18 | for(auto&itr: array_1){ 19 | for(int i=0; i < 30; ++i){ 20 | if(itr&(1< 2 | using namespace std; 3 | vectorans; 4 | bool get_sum(int k , vector&arr , int current_index){ 5 | if(current_index>(int)arr.size()){ 6 | return false; 7 | } 8 | if(k==0){ 9 | return true; 10 | } 11 | if(k<0){ 12 | return false; 13 | } 14 | if(get_sum(k-arr[current_index],arr,current_index+1)){ 15 | ans.push_back(arr[current_index]); 16 | return true; 17 | }else { 18 | return get_sum(k,arr,current_index+1); 19 | } 20 | } 21 | int main(int argc , char *argv[]){ 22 | // write you code here 23 | int k = 24; 24 | vectorarr{12 , 1 , 61 , 5 , 9 , 2}; 25 | ans.clear(); 26 | if(get_sum(k , arr , 0)){ 27 | for(auto&itr:ans){ 28 | cout< 2 | using namespace std; 3 | class Stack{ 4 | private: 5 | vectortemp_stack; 6 | vectormax_stack; 7 | public: 8 | void push(int x){ 9 | temp_stack.push_back(x); 10 | if(max_stack.size()==0){ 11 | max_stack.push_back(x); 12 | }else{ 13 | int t = move(max_stack.back()); 14 | max_stack.push_back(std::max(t,x)); 15 | } 16 | } 17 | void pop(void){ 18 | try{ 19 | if(temp_stack.size()==0){ 20 | throw "Emtpy Stack"; 21 | } 22 | temp_stack.pop_back(); 23 | max_stack.pop_back(); 24 | }catch(const char *s){ 25 | cout< A[j] but i < j. That is, a smaller element appears after a larger element. 6 | 7 | Given an array, count the number of inversions it has. Do this faster than O(N^2) time. 8 | 9 | You may assume each element in the array is distinct. 10 | 11 | For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). 12 | 13 | The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. 14 | 15 | 16 | */ 17 | #include 18 | using namespace std; 19 | int inv_counter{}; 20 | void merge(vector&v, int start , int end){ 21 | vectortemp(v.size(),0); 22 | int mid = (start+end)/2; 23 | int i{start} , j{(start+end)/2+1} ,k{}; 24 | while(i<=mid && j<=end){ 25 | if(v[i]>v[j]){ 26 | inv_counter+=(mid-i+1); 27 | temp[k++]=v[j++]; 28 | }else{ 29 | temp[k++]=v[i++]; 30 | } 31 | } 32 | while(i<=mid){ 33 | temp[k++] = v[i++]; 34 | } 35 | while(j<=end){ 36 | temp[k++] = v[j++]; 37 | } 38 | k = 0; 39 | for(int i{start};i<=end;++i){ 40 | v[i] = temp[k++]; 41 | } 42 | } 43 | void count_inversion(vector&v , int start , int end){ 44 | if(start>=end){ 45 | return; 46 | } 47 | int mid{(start+end)/2}; 48 | count_inversion(v,start,mid); 49 | count_inversion(v,mid+1,end); 50 | merge(v,start,end); 51 | } 52 | int main(int argc , char *argv[]){ 53 | // write you code here 54 | vectorv{2,4,1,3,5}; 55 | count_inversion(v,0,4); 56 | cout< 11 | using namespace std; 12 | inline bool palin(string ans){ 13 | int i=0 , j=(int)ans.size()-1; 14 | while(iright.size()){ 31 | return left; 32 | }else{ 33 | return right; 34 | } 35 | assert(false); 36 | } 37 | int main(void){ 38 | string s; 39 | cin>>s; 40 | cout< 10 | using namespace std; 11 | int main(void){ 12 | vectorarr = { 9, 11, 8, 5, 7, 10 }; 13 | int buy=arr[0]; 14 | int profit{}; 15 | for(auto&sell:arr){ 16 | profit = max(profit , sell-buy); 17 | buy = min(buy , sell); // we will buy current stock as it have minimum price then the current we have 18 | // and try to sell this one 19 | // why this works : 20 | // let's say we buy 9 and sell it at price of 11 then we get a profit of 2 21 | // but next largest value we can see is 10 so we are going to sell our stock [9] at price of 10 by making a profit of 1 22 | // what if we buy a stock which have minimum price value and also appear before the price at which we want to sell the current stock. 23 | // so to automate this current algorithm will work fine 24 | } 25 | cout< 24 | using namespace std; 25 | struct Node{ 26 | char value; 27 | Node* leftNode; 28 | Node* rightNode; 29 | }; 30 | Node* getNewNode(int x){ 31 | Node* temp = new Node(); 32 | temp->value = x; 33 | temp->leftNode = nullptr; 34 | temp->rightNode = nullptr; 35 | return temp; 36 | } 37 | int preOrderIndex; 38 | Node* formTree(vector&preorder , vector&inorder , int start , int end , unordered_map&index){ 39 | if(start>end){ 40 | return nullptr; 41 | } 42 | 43 | Node* root = getNewNode(preorder[ preOrderIndex ]); // set the root 44 | if(start==end){ 45 | preOrderIndex++; 46 | return root; 47 | } 48 | // now we have to look for next root which we can find with index 49 | int middle = index[ preorder[ preOrderIndex++ ] ]; 50 | 51 | root->leftNode = formTree(preorder , inorder , start , middle-1 , index); 52 | root->rightNode = formTree(preorder , inorder , middle+1 , end , index); 53 | 54 | return root; 55 | } 56 | Node* binaryTree(vector&preorder , vector&inorder) { 57 | preOrderIndex = 0; 58 | unordered_mapindex; // for fast search 59 | for( int i{}; i < (int) inorder.size() ; ++i ){ 60 | index[ inorder[ i ] ] = i; 61 | } 62 | return formTree(preorder , inorder, 0, (int)inorder.size()-1 , index); 63 | } 64 | 65 | void preOrder(Node*root){ 66 | if(root==nullptr){ 67 | return; 68 | } 69 | cout<value<<' '; 70 | preOrder(root->leftNode); 71 | preOrder(root->rightNode); 72 | return; 73 | } 74 | 75 | int main(void){ 76 | vector preorder { 'a', 'b', 'd', 'e', 'c', 'f', 'g' }; 77 | vector inorder { 'd', 'b', 'e', 'a', 'f', 'c', 'g' }; 78 | Node* root = binaryTree(preorder , inorder); 79 | preOrder(root); 80 | cout<<'\n'; 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Solution/Day-049.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This problem was asked by Amazon. 4 | 5 | Given an array of numbers, find the maximum sum of any contiguous subarray of the array. 6 | 7 | For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. 8 | 9 | Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements. 10 | 11 | Do this in O(N) time. 12 | 13 | */ 14 | #include 15 | using namespace std; 16 | int getMaxSum(vector & arr){ 17 | int max_sum{} , temp_sum{}; 18 | for(auto&itr:arr){ 19 | temp_sum+=itr; 20 | if(temp_sum>0){ 21 | max_sum = max(temp_sum , max_sum); 22 | }else{ 23 | temp_sum = 0; 24 | } 25 | } 26 | return max_sum; 27 | } 28 | int main(void){ 29 | 30 | vector arr1 = { 34, -50, 42, 14, -5, 86 }; 31 | vector arr2 = { -5, -1, -8, -9 }; 32 | cout<< getMaxSum(arr1) << '\n'; 33 | cout<< getMaxSum(arr2) << '\n'; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Solution/Day-050.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Microsoft. 3 | 4 | Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. 5 | 6 | Given the root to such a tree, write a function to evaluate it. 7 | 8 | For example, given the following tree: 9 | 10 | * 11 | / \ 12 | + + 13 | / \ / \ 14 | 3 2 4 5 15 | 16 | You should return 45, as it is (3 + 2) * (4 + 5). 17 | */ 18 | #include 19 | using namespace std; 20 | struct Node{ 21 | string value; 22 | Node* left; 23 | Node* right; 24 | 25 | Node(): left{nullptr} , right{nullptr} { }; 26 | }; 27 | 28 | double solExpression( Node* root ) { 29 | if(root == nullptr){ 30 | return 0.0f; 31 | } 32 | 33 | double leftAns = solExpression(root -> left); 34 | double rightAns = solExpression(root -> right); 35 | 36 | if(root -> value == "+"){ 37 | return leftAns + rightAns; 38 | } 39 | 40 | if(root -> value == "-"){ 41 | return leftAns - rightAns; 42 | } 43 | 44 | if(root -> value == "*"){ 45 | return leftAns * rightAns; 46 | } 47 | 48 | if(root -> value == "/"){ 49 | return leftAns / rightAns; 50 | } 51 | 52 | return std::stof(root->value); 53 | 54 | } 55 | 56 | int main(void){ 57 | Node*root = new Node(); 58 | root -> value = "*"; 59 | 60 | root -> left = new Node(); 61 | root -> left -> value = "+"; 62 | 63 | root -> left -> left = new Node(); 64 | root -> left -> left -> value = "3"; 65 | 66 | root -> left -> right = new Node(); 67 | root -> left -> right -> value = "2"; 68 | 69 | root -> right = new Node(); 70 | root -> right -> value = "+"; 71 | 72 | root -> right -> left = new Node(); 73 | root -> right -> left -> value = "4"; 74 | 75 | root -> right -> right = new Node(); 76 | root -> right -> right -> value = "5"; 77 | 78 | 79 | double ans = solExpression(root); 80 | 81 | if(ans - (int)ans==0){ 82 | cout << ans ; 83 | }else{ 84 | cout << fixed << setprecision(2) << ans; 85 | } 86 | cout << '\n'; 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /Solution/Day-051.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This problem was asked by Facebook. 4 | 5 | Given a function that generates perfectly random numbers between 1 and k (inclusive), 6 | where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps. 7 | 8 | It should run in O(N) time. 9 | 10 | Hint: Make sure each one of the 52! permutations of the deck is equally likely. 11 | 12 | */ 13 | #include 14 | using namespace std; 15 | int main(void){ 16 | srand(time(NULL)); 17 | 18 | vector v = {1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; 19 | 20 | for(int i=0;i<(int)v.size()-1;++i){ 21 | int new_position = rand()%(v.size()-i-1); 22 | swap(v[i] , v[new_position]); 23 | } 24 | 25 | for(auto&itr:v){ 26 | cout< 16 | using namespace std; 17 | 18 | class LRUCache { 19 | list>deQ; // take it as dequeue {key , value} 20 | unordered_map>::iterator> keyValue; 21 | int Capacity; 22 | public: 23 | 24 | LRUCache(int capacity):Capacity(capacity){} 25 | 26 | int get(int key) { 27 | if(keyValue.find(key)==keyValue.end()){ 28 | return -1; 29 | }else{ 30 | int value = keyValue[key]->second; 31 | deQ.erase(keyValue[key]); 32 | deQ.push_front(make_pair(key , value)); 33 | keyValue[key] = deQ.begin(); 34 | return value; 35 | } 36 | } 37 | void set(int key, int value) { 38 | if(keyValue.find(key)!=keyValue.end()){ 39 | // key is already present 40 | deQ.erase(keyValue[key]); 41 | }else if(Capacity == deQ.size()){ 42 | keyValue.erase(deQ.back().first); 43 | //cout< 11 | using namespace std; 12 | template 13 | struct Queue{ 14 | private: 15 | stack< Object > enq; 16 | stack< Object > deq; 17 | public: 18 | void enqueue( Object value ) { 19 | enq.push( value ); 20 | } 21 | 22 | Object dequeue( void ) { 23 | while( !enq.empty() ) { 24 | deq.push( enq.top() ); 25 | enq.pop(); 26 | } 27 | 28 | Object element = deq.top(); 29 | deq.pop(); 30 | 31 | while( !deq.empty() ) { 32 | enq.push( deq.top() ); 33 | deq.pop(); 34 | } 35 | 36 | return element; 37 | } 38 | 39 | }; 40 | int main(void){ 41 | Queue q; 42 | q.enqueue(100); 43 | q.enqueue(200); 44 | cout< 38 | using namespace std; 39 | int grid[9][9]; 40 | pair getFreeBox( void ) { 41 | for(auto i = 0; i< 9; ++i){ 42 | for(auto j=0; j<9; ++j){ 43 | if(grid[i][j] == 0){ 44 | return make_pair(i,j); 45 | } 46 | } 47 | } 48 | return make_pair(-1 , -1); 49 | } 50 | bool isToPlace(pair&p , int k){ 51 | // is row safe 52 | int row= p.first; 53 | int col = p.second; 54 | for(int i=0;i<9; ++i){ 55 | if(grid[row][i] == k){ 56 | return false; 57 | } 58 | } 59 | for(int i=0;i<9; ++i){ 60 | if(grid[i][col]==k){ 61 | return false; 62 | } 63 | } 64 | // is box safe 65 | int x = row - (row % 3); 66 | int y = col - (col % 3); 67 | for(auto i = 0; i<3; ++i){ 68 | for(auto j=0; j<3; ++j){ 69 | if(grid[i+x][j+y] == k){ 70 | return false; 71 | } 72 | } 73 | } 74 | return true; 75 | } 76 | bool sol(void){ 77 | pairp = getFreeBox(); 78 | if(p.first == -1 ){ 79 | return true; 80 | } 81 | for(int i=1; i<=9; ++i){ 82 | if(isToPlace(p , i)){ 83 | grid[p.first][p.second] = i; 84 | if(sol()){ 85 | return true; 86 | } 87 | grid[p.first][p.second] = 0; 88 | } 89 | } 90 | return false; 91 | } 92 | int main(void){ 93 | freopen("input" , "r" , stdin); 94 | for(auto i = 0; i<9; ++i){ 95 | for(auto j = 0; j<9; ++j){ 96 | cin>>grid[i][j]; 97 | } 98 | } 99 | if(sol()){ 100 | for(auto i = 0; i<9; ++i){ 101 | for(auto j = 0; j<9; ++j){ 102 | cout< 12 | using namespace std; 13 | 14 | class Solution { 15 | unordered_mapdec; 16 | unordered_mapenc; 17 | int index = 0; 18 | public: 19 | 20 | string encode(string longUrl) { 21 | enc[longUrl]=index; 22 | dec[to_string(index)]= longUrl; 23 | ++index; 24 | return to_string(index-1); 25 | } 26 | 27 | string decode(string shortUrl) { 28 | return dec[shortUrl]; 29 | } 30 | }; 31 | 32 | int main(void){ 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Solution/Day-056.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This problem was asked by Google. 4 | 5 | Given an undirected graph represented as an adjacency matrix and an integer k, 6 | 7 | write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using at most k colors. 8 | 9 | 10 | ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 11 | 12 | This seems to be a NP problem. I tried to find answer on web 13 | only information i got is , this problem is checking about if given number 14 | k is less then or equal chromatic number of given graph; 15 | 16 | It tried to find some better solution but didn't get any ;( 17 | 18 | if you find any better approach please mail me: offamitkumar@gmail.com 19 | 20 | ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 21 | 22 | */ 23 | #include 24 | using namespace std; 25 | vectorvisited; // might possible that graph not connected 26 | vectorcolor; // stored the color of each node , -1 represent no coloring is done yet 27 | bool iscolorable(vector>&graph , int currentNode , const int &k){ 28 | visited[currentNode] = true; 29 | for(int itr=0;itr<4;++itr){ 30 | if(graph[currentNode][itr] == 0){ 31 | continue; 32 | } 33 | if(color[itr] == color[currentNode]){ // if color match with adjacent vertex 34 | return false; 35 | } 36 | if(color[itr] == -1){ // let's color it 37 | for(int i=0;i > graph = { 59 | {0, 1, 1, 1}, 60 | {1, 0, 1, 1}, 61 | {1, 1, 0, 1}, 62 | {1, 1, 1, 0} 63 | }; 64 | int k = 3; // number of colors 65 | bool ispossible = true; 66 | for(int i=0;i 14 | using namespace std; 15 | /* 16 | * we will choose each word greedily. 17 | */ 18 | vectorans; 19 | bool sol(string &s , const int &k){ 20 | stringstream ss(s); 21 | string temp; 22 | while(ss>>s){ 23 | if(s.size()>k) return false; // this can't be adjusted to given word limits 24 | if(temp.size()+s.size()+1<=k){ 25 | if(temp.size()==0){ 26 | temp+=s; 27 | }else{ 28 | temp+=" "+s; 29 | } 30 | }else{ 31 | ans.push_back(temp); 32 | temp =s; 33 | } 34 | } 35 | if(temp.size()>0){ 36 | ans.push_back(temp); 37 | } 38 | return true; // if answer possible then return true 39 | } 40 | int main(void){ 41 | string s = "the quick brown fox jumps over the lazy dog"; 42 | int k = 10; 43 | if(sol(s ,k)){ 44 | for(auto &itr:ans){ 45 | cout< 20 | using namespace std; 21 | class Solution { 22 | public: 23 | int search(vector& arr, int target) { 24 | if(!arr.size()) 25 | return -1; // consider -1 as NULL here 26 | auto get = [&](int start , int end)->int{ 27 | int mid ; 28 | if(arr[start] == target){ 29 | return start; 30 | }else if(arr[end] == target){ 31 | return end; 32 | } 33 | while(start<=end){ 34 | mid = (start+end)/2; 35 | if(arr[mid] == target){ 36 | return mid; 37 | } 38 | if(arr[start] <= arr[mid]){ // we assumed that this is sorted 39 | if(target>=arr[start] and target<=arr[mid]){ 40 | end = mid-1; 41 | }else{ 42 | start = mid+1; 43 | } 44 | }else if(arr[mid]<=target and target<=arr[end]){ // we now assume that [mid , end] portion is sorted and target value is there 45 | start = mid+1; 46 | }else{ // [start , mid] is not sorted and if [start , mid] isn't sorted than we claim that [mid+1 , end] will be sorted and if target isn't present there , now we will look for the target in unsorted portion 47 | end = mid-1; 48 | } 49 | } 50 | return -1; 51 | 52 | }; 53 | return get(0 , arr.size()-1); 54 | } 55 | }; 56 | 57 | int main(void){ 58 | Solution s1; 59 | vectorv = {4,5,6,7,0,1,2}; 60 | int target = 0; 61 | assert(s1.search(v , target) == 4); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Solution/Day-059.cpp: -------------------------------------------------------------------------------- 1 | // 2 | This problem was asked by Google. 3 | 4 | Implement a file syncing algorithm for two computers over a low-bandwidth network. What if we know the files in the two computers are mostly the same? 5 | 6 | // this question is based on implementation of merkle tree . 7 | // you can check about it on google. 8 | // it might get update in future. 9 | -------------------------------------------------------------------------------- /Solution/Day-060.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Facebook. 3 | 4 | Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same. 5 | 6 | For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. 7 | 8 | Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it up into two subsets that add up to the same sum. 9 | 10 | * 11 | */ 12 | class Solution { 13 | unordered_mapdp; 14 | bool dfs(vector&n , int index , int target){ 15 | if(dp.find(target)!=dp.end()){ 16 | return dp[target]; 17 | } 18 | if(index>=n.size() or target<0)return false; 19 | dp[target] = false; 20 | for(auto i=index;i<(int)n.size(); ++i){ 21 | if(dfs(n , i+1 , target - n[i])){ 22 | dp[target] = true; 23 | return dp[target]; 24 | } 25 | } 26 | return dp[target]; 27 | } 28 | public: 29 | bool canPartition(vector& nums) { 30 | int sum = accumulate(nums.begin() , nums.end() , 0); 31 | if(sum%2 or nums.size() == 1){ 32 | return false; 33 | }else if(nums.size()==0){ 34 | return true; 35 | } 36 | sort(nums.begin() , nums.end()); 37 | dp[0] = true; 38 | return dfs(nums , 0 , sum/2); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Solution/Day-061.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem was asked by Google. 3 | 4 | Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. 5 | 6 | Do this faster than the naive method of repeated multiplication. 7 | 8 | For example, pow(2, 10) should return 1024. 9 | */ 10 | 11 | class Solution { 12 | public: 13 | double myPow(double x, long long n) { 14 | double ans =1.0f; 15 | if(n>0){ 16 | while(n){ 17 | //double a =1; 18 | if(n&1){ 19 | ans*=x; 20 | } 21 | x*=x; 22 | n>>=1; 23 | } 24 | }else{ 25 | n = abs(n); 26 | while(n){ 27 | if(n&1){ 28 | ans/=x; 29 | } 30 | x*=x; 31 | n>>=1; 32 | cout<>grid(m , vector(n,0)); 24 | grid[0][0] = 1; 25 | for(int i=0;i>visited; 22 | vector>dir{{-1, 0}, {0, -1}, {0, 1},{1, 0}}; 23 | int row , col; 24 | bool dfs(vector>&grid , string &word ,int r , int c , int index = 1){ 25 | if(index == (int)word.size()){ 26 | return true; 27 | } 28 | if(index > (int)word.size()){ 29 | return false; 30 | } 31 | if(r>=row || c >=col){ 32 | return false; 33 | } 34 | visited[r][c] = true; 35 | for(auto &itr: dir){ 36 | if(r+itr.first <0 or r+itr.first>=row){ 37 | continue; 38 | } 39 | if(c+itr.second <0 or c+itr.second>=col){ 40 | continue; 41 | } 42 | if(grid[r+itr.first][c+itr.second]==word[index]){ 43 | if(visited[r+itr.first][c+itr.second]==false && dfs(grid , word , r+itr.first, c+itr.second , index+1)){ 44 | return true; 45 | } 46 | } 47 | } 48 | visited[r][c] = false; 49 | return false; 50 | } 51 | public: 52 | bool exist(vector>& board, string word) { 53 | row = board.size(); 54 | col = board[0].size(); 55 | visited.resize(row , vector(col , false)); 56 | for(int i=0;i 21 | using namespace std; 22 | vector>jump{{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{1,-2},{-1,-2}}; 23 | vector>grid; 24 | bool valid(int x , int y , int n){ 25 | if(x>n || y>n || x<1 || y<1){ 26 | return false; 27 | } 28 | if(grid[x][y] == true ) 29 | return false; 30 | return true; 31 | } 32 | long long count_ways(int x , int y , int n ,int move_number = 1){ 33 | if(move_number == n*n){ 34 | return 1; 35 | } 36 | int ways_counter{}; 37 | if(x>n || y>n || x<1 || y<1){ 38 | return ways_counter; 39 | } 40 | grid[x][y] = true; 41 | for(int k=0;k<(int)jump.size();++k){ 42 | if(valid(x+jump.at(k).first , y+jump.at(k).second , n)){ 43 | ways_counter+=count_ways(x+jump.at(k).first , y+jump.at(k).second , n , move_number+1 ); 44 | } 45 | } 46 | grid[x][y] = false; 47 | return ways_counter; 48 | } 49 | int main(void){ 50 | int n; cin>>n; 51 | grid.assign(n+1 , vector(n+1,false)); 52 | long long counter{}; 53 | for(int i=1;i<=n;++i){ 54 | for(int j=1;j<=n;++j){ 55 | counter+=count_ways(i,j,n); 56 | } 57 | } 58 | cout<> dir= { 41 | { 0, 1} , 42 | { 1, 0} , 43 | {0, -1} , 44 | {-1, 0} 45 | }; 46 | vector>visited; 47 | public: 48 | vector spiralOrder(vector>& matrix) { 49 | vectorans; 50 | if(matrix.size()==0 || matrix[0].size() == 0){ 51 | return ans; 52 | } 53 | int C = matrix[0].size(); 54 | int R = matrix.size(); 55 | 56 | visited.assign(R , vector(C , false)); 57 | int r,c,d; 58 | r = c = d = 0; 59 | 60 | for(int tr,tc, _=0;_<(R*C);++_){ 61 | tr = r + dir[d].first; 62 | tc = c + dir[d].second; 63 | ans.push_back(matrix[r][c]); 64 | visited[r][c] = true; 65 | if(tc>=0 and tc=0 and tr p1 , pair< int , int> p2 ) { 3 | if(p1.first + p1.second == p2.first + p2.second){ 4 | return true; 5 | } 6 | if(p1.first - p1.second == p2.first - p2.second){ 7 | return true; 8 | } 9 | return false; 10 | } 11 | public: 12 | /* 13 | * else solution can be if we create a map of every diagonal then for every co-ordinated 14 | * we will update the particular key value, at last we can count the pair by simple 15 | * combination trick. 16 | * Time Complexity : O(N*log(N)+N); ( N -> traversing all pair of co-ordinated ) 17 | * Space Complexity: O(N) 18 | * 19 | */ 20 | int getAttackingPair( vector< pair< int , int > > &bishop ) { // O(N^2) 21 | int n = static_cast< int >( bishop.size() ); 22 | int counter{}; 23 | for( int i{}; i < n; ++i ) { 24 | for( int j = i+1; j < n; ++j ) { 25 | if( attacking(bishop[i] , bishop[j]) ) { 26 | ++counter; 27 | } 28 | } 29 | } 30 | return counter; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Solution/Day-069.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumProduct(vector& nums) { 4 | int max1 , max2 , max3; 5 | int min1 , min2; 6 | max1 = max2 = max3 = numeric_limits::min(); 7 | min1 = min2 = numeric_limits::max(); 8 | for(auto&itr:nums){ 9 | if(itr>=max1){ 10 | max3 = max2; 11 | max2 = max1; 12 | max1 = itr; 13 | }else if(itr>=max2){ 14 | max3 = max2; 15 | max2 = itr; 16 | }else if(itr>=max3){ 17 | max3 = itr; 18 | } 19 | if(itr<=min1){ 20 | min2 = min1; 21 | min1 = itr; 22 | }else if(itr<=min2){ 23 | min2 = itr; 24 | } 25 | } 26 | return std::max({max1*max2*max3 , min1*min2*max1}); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Solution/Day-070.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int getNextPerfectNumber(int n){ 4 | auto temp_sum = 0; 5 | auto temp = n; 6 | while(n){ 7 | temp_sum += (n%10); 8 | n /= 10; 9 | } 10 | return temp*10+(10 - temp_sum); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Solution/Day-071.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | private: 3 | int rand5(void)const noexcept{ 4 | srand(time(NULL)); 5 | return rand()%5+1; 6 | } 7 | public: 8 | int rand7(void)noexcept{ 9 | int generatedNumber = -1; 10 | while(true){ 11 | generatedNumber = (rand5()-1)*5+rand5(); 12 | if(generatedNumber<=21){ 13 | return generatedNumber%7+1; 14 | } 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Solution/Day-072.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class InfinitePathException:std::exception{ 4 | public: 5 | const char* what() const throw(){ 6 | return "Detected Cycle, No Answer Possible"; 7 | } 8 | }; 9 | 10 | class Solution{ 11 | private: 12 | mapfreqCounter; 13 | setvisited; 14 | map>graph; 15 | int maxPathValue; 16 | void createGraph(vector>&edges){ 17 | for(auto&edge:edges){ 18 | auto&& source = edge[0]; 19 | auto&& destination = edge[1]; 20 | graph[ source ].push_back(destination); 21 | } 22 | } 23 | void dfs(const string&pathCharacters , int currentNode){ 24 | freqCounter[ pathCharacters[currentNode] ]++; 25 | visited.insert(currentNode); 26 | for(auto&itr:graph[currentNode]){ 27 | if(visited.count(itr)){ 28 | throw InfinitePathException(); 29 | }else{ 30 | dfs(pathCharacters , itr); 31 | } 32 | } 33 | maxPathValue = std::max(maxPathValue , freqCounter[ pathCharacters[ currentNode ] ]); 34 | visited.erase(currentNode); 35 | freqCounter[ pathCharacters[currentNode] ]--; 36 | } 37 | public: 38 | int getMaxValuePath(const string &pathCharacters , vector>&edge){ 39 | maxPathValue = numeric_limits::min(); 40 | createGraph(edge); 41 | for(auto&itr:graph){ // we need to check dfs from each node as there can be situation like A(1)->A(0)->A(2)->A(3) 42 | try{ 43 | dfs(pathCharacters , itr.first); 44 | }catch(...){ 45 | throw; 46 | } 47 | } 48 | if(maxPathValue == numeric_limits::min()){ 49 | assert(false); 50 | }else{ 51 | return maxPathValue; 52 | } 53 | } 54 | }; 55 | int main(void){ 56 | 57 | string s = "ABACA"; 58 | vector>edges1; 59 | edges1.push_back({0,1}); 60 | edges1.push_back({0,2}); 61 | edges1.push_back({2,3}); 62 | edges1.push_back({3,4}); 63 | Solution s1; 64 | try{ 65 | cout<>edges2; 71 | s = "A"; 72 | edges2.push_back({0,0}); 73 | try{ 74 | cout<next==nullptr){ 15 | return head; 16 | } 17 | ListNode* oldHead = head , *newHead = head , *newEnd = head ,*nextNode = head ->next; 18 | while(nextNode!=nullptr){ 19 | newHead = nextNode; 20 | nextNode = newHead ->next; 21 | newHead->next = oldHead; 22 | newEnd->next = nextNode; 23 | oldHead = newHead; 24 | } 25 | return newHead; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Solution/Day-074.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | private: 3 | int counter{}; 4 | public: 5 | int getAppearingValue( int n , int x ) { 6 | counter = 0; 7 | for(int i=1; i<=n and i<=sqrt(x);++i){ 8 | if(!(x%i)){ 9 | counter+=(x/i <= n); 10 | counter+=(x/i!=i and x/i<=n and i<=n); 11 | } 12 | } 13 | return counter; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Solution/Day-075.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | const int array_size = static_cast(nums.size()); 5 | if(!array_size){ 6 | return 0; 7 | } 8 | vectordp(array_size , 1); 9 | for(int i=0; inums[j]) 12 | dp[i] = max(dp[j]+1 , dp[i]); 13 | } 14 | } 15 | return *max_element(dp.begin() , dp.end()); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Solution/Day-076.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDeletionSize(vector& A) { 4 | int col = static_cast(A[0].size()); 5 | int row = static_cast(A.size()); 6 | int required_deletion{}; 7 | for ( int c{}; c < col; ++c ) { 8 | for ( int r{}; r < row-1; ++r ) { 9 | if(A[r][c] > A[r+1][c]){ 10 | ++required_deletion; 11 | break; 12 | } 13 | } 14 | } 15 | return required_deletion; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Solution/Day-077.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static bool compare(vector&a , vector&b){ 3 | return a[0] < b[0]; 4 | } 5 | public: 6 | vector> merge(vector>& intervals) { 7 | sort(intervals.begin() , intervals.end() , compare); 8 | vector>res; 9 | int n = static_cast(intervals.size()); 10 | for(int i=0;i=intervals[i+1][0]){ 14 | current_largest_end = max(intervals[i+1][1] , current_largest_end); 15 | current_min_start = min(intervals[i+1][0] , current_min_start); 16 | ++i; 17 | } 18 | res.push_back({current_min_start , current_largest_end}); 19 | } 20 | return res; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Solution/Day-078.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 | using Heap = set>; 12 | class Solution { 13 | public: 14 | ListNode* mergeKLists(vector& lists) { 15 | Heap h; 16 | ListNode* temp, *res; 17 | temp = res = nullptr; 18 | const int &k = lists.size(); 19 | for (int i = 0; i < k; ++i) { 20 | if (lists[i] != nullptr) { 21 | h.insert(make_pair(lists[i] -> val, lists[i])); 22 | } 23 | } 24 | while (h.empty() == false) { 25 | ListNode* x = (*h.begin()).second; 26 | if (res == nullptr) { 27 | res = temp = x; 28 | } else { 29 | temp -> next = x; 30 | temp = temp -> next; 31 | } 32 | h.erase(h.begin()); 33 | if (x -> next != nullptr) { 34 | x = x -> next; 35 | h.insert(make_pair(x -> val, x)); 36 | } 37 | } 38 | return res; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Solution/Day-079.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPossibility(vector& nums) { 4 | int counter{}; 5 | const int n = static_cast(nums.size()); 6 | for (int i = 0; i < n-1; ++i) { 7 | if(nums[i] > nums[i+1] && counter) { 8 | return false; 9 | } 10 | if(nums[i] > nums[i+1]) { 11 | if( i>0 && nums[i+1] < nums[i-1] ) { 12 | nums[i+1] = nums[i]; 13 | }else{ 14 | nums[i] = nums[i+1]; 15 | } 16 | ++counter; 17 | } 18 | } 19 | return true; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /Solution/Day-080.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * char val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val('0'), left(nullptr), right(nullptr) {} 8 | * TreeNode(char x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(char x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | int deepest_height; 14 | char character; 15 | void getDeepestHeight(TreeNode* root, int current_height) { 16 | if (root == nullptr) { 17 | return ; 18 | } 19 | if (deepest_height < current_height) { 20 | deepest_height = current_height; 21 | character = root -> val; 22 | } 23 | getDeepestHeight(root -> right, current_height+1); 24 | getDeepestHeight(root -> left, current_height+1); 25 | } 26 | public: 27 | char maxDepth(TreeNode* root) { 28 | deepest_height=0; 29 | getDeepestHeight(root, 1); 30 | return character; 31 | } 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /Solution/Day-081.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector dialer = { 3 | "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" 4 | }; 5 | vectorresult; 6 | void getString(string &digits, int index, string currentString) { 7 | if (index >= digits.size()) { 8 | result.push_back(currentString); 9 | return; 10 | } 11 | for (auto & itr: dialer[digits[index]-'0']) { 12 | getString(digits, index+1, currentString+itr); 13 | } 14 | return ; 15 | } 16 | public: 17 | vector letterCombinations(string digits) { 18 | result.clear(); 19 | if (digits.size() != 0) { 20 | getString(digits, 0, ""); 21 | } 22 | return result; 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /Solution/Day-082.cpp: -------------------------------------------------------------------------------- 1 | class Reader{ 2 | private: 3 | string raw_data; 4 | string buffer; 5 | int processed_till; 6 | string read7(){ 7 | int start = processed_till; // point from where we have to read the file 8 | int end = min(processed_till+7, (int)raw_data.size()); 9 | int old_start_point = start; 10 | processed_till = end; // updated till where file is read 11 | // so that next time we can start from the same point 12 | return raw_data.substr(old_start_point, end); 13 | } 14 | public: 15 | Reader(const string & refString): raw_data(refString), buffer(""), processed_till(0) { } 16 | string readN(int n) { 17 | while (int(buffer.size()) < n) { 18 | string get_char = read7(); 19 | if (get_char == "") { // no more characters are remaining 20 | break; 21 | } 22 | buffer += get_char; 23 | } 24 | int end_point = min((int)buffer.size(), n); 25 | string to_be_returned = buffer.substr(0, end_point); 26 | if(end_point <= (int)buffer.size()){ 27 | buffer = buffer.substr(end_point, (int)buffer.size()); 28 | } 29 | return to_be_returned; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Solution/Day-083.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 | TreeNode* invertTree(TreeNode* root) { 15 | if(root == nullptr) { 16 | return nullptr; 17 | } 18 | TreeNode*temp = root->left; 19 | root -> left = root -> right; 20 | root -> right = temp; 21 | invertTree(root -> left); 22 | invertTree(root -> right); 23 | return root; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Solution/Day-084.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int row,col; 3 | vector>visited; 4 | void dfs(int i,int j, vector>&grid){ 5 | if(i<0 || i>=row || j<0 || j>=col || visited[i][j] || grid[i][j]!='1'){ 6 | return; 7 | } 8 | visited[i][j] = true; 9 | dfs(i+1,j,grid); 10 | dfs(i-1,j,grid); 11 | dfs(i,j+1,grid); 12 | dfs(i,j-1,grid); 13 | } 14 | public: 15 | int numIslands(vector>& grid) { 16 | row = (int)grid.size(); 17 | if(!row) 18 | return 0; 19 | col = (int)grid[0].size(); 20 | visited.assign(row,vector(col,false)); 21 | int counter{}; 22 | for(int i=0;ist; 6 | for(int i=0;i::min()){ 6 | if(divisor == 1){ 7 | return dividend; 8 | }else if(divisor == -1){ 9 | return numeric_limits::max(); 10 | } 11 | } 12 | divisor = (divisor > 0) ? -divisor : divisor; 13 | dividend = (dividend > 0) ? -dividend : dividend; 14 | int best_quotient = 0, temp=1 , quotient = divisor; 15 | while(quotient >=INT_MIN>>1 and dividend <= quotient + quotient){ 16 | quotient += quotient; 17 | temp <<= 1; 18 | } 19 | while(dividend <= divisor) { 20 | if(dividend <= quotient) { 21 | dividend -= quotient; 22 | best_quotient += temp; 23 | } 24 | quotient >>=1; 25 | cout << quotient << '\n'; 26 | temp >>= 1; 27 | } 28 | return sign < 0 ? -best_quotient : best_quotient; 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /Solution/Day-089.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 isValidBST(TreeNode* root, const std::optional &min_value=LLONG_MIN , const std::optional&max_value=LLONG_MAX) { 15 | if(root == nullptr){ 16 | return true; 17 | } 18 | // according to DCP question binary search tree node can have equal value 19 | if(root -> val > max_value.value() || root->val < min_value.value()){ 20 | return false; 21 | } 22 | return isValidBST(root->right,root->val,max_value) && isValidBST(root->left,min_value,root->val); 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /Solution/Day-090.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | vectorincluded; 5 | public: 6 | int generateRandomNumber(const array&excluded, const int &n) { 7 | setexclude(excluded.begin(), excluded.end()); 8 | for(int i = 0;i(included.size()); 14 | 15 | 16 | // random number generation 17 | std::random_device rnd; 18 | std::mt19937 rng(rnd()); 19 | std::uniform_int_distribution distribution(0,inclusion_size); 20 | return included[distribution(rng)]; 21 | } 22 | }; 23 | int main(void){ 24 | array exclude{2, 8, 11, 19, 23}; 25 | Solution s1; 26 | cout << s1.generateRandomNumber(exclude, 30) << '\n'; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Solution/Day-091.py: -------------------------------------------------------------------------------- 1 | # it will print 9 , as first for loop exit at 9 2 | # so 'i' will have value 9 at the end of for loop & all lambda function use 3 | # i as their return value 4 | functions = [] 5 | for i in range(10): 6 | functions.append(lambda : i) 7 | i = 0 8 | for f in functions: 9 | print(f()) 10 | i = i + 1 11 | -------------------------------------------------------------------------------- /Solution/Day-092.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | private: 5 | setid; 6 | mapin_deg; 7 | map>graph; 8 | vector Sort(void){ 9 | vectorres; 10 | while(!id.empty()){ 11 | string current = *(id.begin()); 12 | id.erase(current); 13 | res.push_back(current); 14 | for(auto&itr:graph[current]){ 15 | in_deg[itr]--; 16 | if(in_deg[itr]==0){ 17 | id.insert(itr); 18 | } 19 | } 20 | } 21 | return res; 22 | } 23 | public: 24 | vector topologicalSort(map>&cID){ 25 | // C++ map maintain sorted already so we don't have to sort the courses 26 | // If it wasn't map then we have to first sort the course , then their pre-requisites 27 | for(auto&courses:cID){ 28 | if(courses.second.size() == 0){ 29 | id.insert(courses.first); 30 | }else{ 31 | for(auto&itr:courses.second){ 32 | graph[itr].insert(courses.first); 33 | } 34 | } 35 | in_deg[courses.first] = courses.second.size(); 36 | } 37 | return Sort(); 38 | } 39 | }; 40 | int main(void){ 41 | map> cID{ 42 | {"CSC300" , {"CSC100" , "CSC200"}}, 43 | {"CSC200" , {"CSC100"}}, 44 | {"CSC100" , {}} 45 | }; 46 | Solution s1; 47 | vectorv = s1.topologicalSort(cID); 48 | for(auto&itr:v){ 49 | cout << itr << ' '; 50 | } 51 | cout << '\n'; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Solution/Day-093.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * 4 | * struct TreeNode { 5 | * int val; 6 | * TreeNode *left; 7 | * TreeNode *right; 8 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | private: 13 | struct Node{ 14 | bool isBST; 15 | int ans; 16 | int min_value; 17 | int max_value; 18 | }; 19 | Node getBST(TreeNode * root){ 20 | if(root == nullptr){ 21 | return {1,0,INT_MAX,INT_MIN}; 22 | } 23 | Node left = getBST(root->left); 24 | Node right = getBST(root->right); 25 | Node currentNode; 26 | if(left.isBST==false || right.isBST==false || left.max_value>root->val || right.min_value <= root->val) { 27 | currentNode.isBST = false; 28 | currentNode.ans = max(left.ans , right.ans); 29 | return currentNode; 30 | } 31 | currentNode.isBST = true; 32 | currentNode.ans = left.ans + right.ans + 1; 33 | currentNode.min_value = root->left != nullptr ? left.min_value : root->val; 34 | currentNode.max_value = root->right != nullptr ? right.max_value : root -> val; 35 | return currentNode; 36 | } 37 | public: 38 | int maxSizeBST(TreeNode *root) { 39 | Node Ans = getBST(root); 40 | return Ans.ans; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /Solution/Day-094.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 | int intAns; 14 | int dfs(TreeNode* root){ 15 | if(root == nullptr){ 16 | return 0; 17 | } 18 | int intLeftSum = dfs(root -> left); 19 | int intRightSum = dfs(root -> right); 20 | //cout << intLeftSum << " : " << intRightSum << '\n'; 21 | intAns = max(intAns , intRightSum + intLeftSum + root -> val); 22 | return max(0, root->val + max(intLeftSum , intRightSum)); 23 | } 24 | public: 25 | int maxPathSum(TreeNode* root) { 26 | intAns = INT_MIN; 27 | dfs(root); 28 | return intAns; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Solution/Day-095.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | int last = (int)nums.size()-2; 5 | while(last >= 0 && nums[last] >= nums[last+1]){ 6 | last--; 7 | } 8 | if(last < 0){ 9 | sort(nums.begin() , nums.end()); 10 | return; 11 | } 12 | for(int i=nums.size()-1;i>last;--i){ 13 | if(nums[i] > nums[last]){ 14 | swap(nums[i] , nums[last]); 15 | break; 16 | } 17 | } 18 | reverse(nums.begin()+last+1 , nums.end()); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Solution/Day-096.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bitset<100>visited; 3 | vector>res; 4 | int n; 5 | void generatePermutation(vector& nums , vector&temp){ 6 | if((int)temp.size() == n){ 7 | res.push_back(temp); 8 | return; 9 | } 10 | for(int i=0;i> permute(vector& nums) { 22 | n = (int)nums.size(); 23 | visited.reset(); 24 | vectortemp; 25 | generatePermutation(nums, temp); 26 | return res; 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /Solution/Day-097.cpp: -------------------------------------------------------------------------------- 1 | class TimeMap { 2 | public: 3 | /** Initialize your data structure here. */ 4 | unordered_map>>mp; 5 | TimeMap() { 6 | 7 | } 8 | 9 | void set(string key, string value, int timestamp) { 10 | mp[key].push_back(make_pair(value , timestamp)); 11 | } 12 | 13 | string get(string key, int timestamp) { 14 | const auto &v = mp[key]; 15 | if(v.size()==0){ 16 | return ""; 17 | } 18 | auto c = upper_bound(v.begin() , v.end() , 19 | [](int val , auto &p){ 20 | return val < p.second; 21 | } 22 | ); 23 | return c.second; 24 | } 25 | }; 26 | 27 | /** 28 | * Your TimeMap object will be instantiated and called as such: 29 | * TimeMap* obj = new TimeMap(); 30 | * obj->set(key,value,timestamp); 31 | * string param_2 = obj->get(key,timestamp); 32 | */ 33 | 34 | -------------------------------------------------------------------------------- /Solution/Day-098.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector>visited; 3 | vector>dir{{-1, 0}, {0, -1}, {0, 1},{1, 0}}; 4 | int row , col; 5 | bool dfs(vector>&grid , string &word ,int r , int c , int index = 1){ 6 | if(index == (int)word.size()){ 7 | return true; 8 | } 9 | if(index > (int)word.size()){ 10 | return false; 11 | } 12 | if(r>=row || c >=col){ 13 | return false; 14 | } 15 | //cerr<=row){ 19 | continue; 20 | } 21 | if(c+itr.second <0 or c+itr.second>=col){ 22 | continue; 23 | } 24 | //cerr<>& board, string word) { 36 | row = board.size(); 37 | col = board[0].size(); 38 | visited.resize(row , vector(col , false)); 39 | for(int i=0;is; 3 | public: 4 | int longestConsecutive(vector& nums) { 5 | for(auto&itr: nums){ 6 | s.insert(itr); 7 | } 8 | int best_ans {}; 9 | for(auto&itr:s){ 10 | if(s.find(itr-1)==s.end()){ 11 | int current = itr; 12 | int temp_ans = 1; 13 | while(s.find(current+1)!=s.end()){ 14 | ++temp_ans; 15 | ++current; 16 | } 17 | best_ans = max(temp_ans , best_ans); 18 | } 19 | } 20 | return best_ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Solution/Day-100.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int findMinSteps(vector>&points){ 4 | int step_counter{}; 5 | const int &n = (int)points.size(); 6 | for(int i=0;i 2 | using namespace std; 3 | class Solution{ 4 | vectorisPrime; 5 | void sieve(int n){ 6 | isPrime.assign(n+2 , true); 7 | isPrime[0] = isPrime[1] = false; 8 | for(int i=2;i<=n/2;++i){ 9 | if(isPrime[i]){ 10 | for(int j=i*i;j<=n;j+=i){ 11 | isPrime[j]=false; 12 | } 13 | } 14 | } 15 | return; 16 | } 17 | public: 18 | vectorprimeNumber(int n){ 19 | sieve(n); 20 | for(int i=2;i<=n;++i){ 21 | if(isPrime[i] && n-i>0 && isPrime[n-i]){ 22 | return {i,n-i}; 23 | } 24 | } 25 | assert(false); 26 | } 27 | }; 28 | int main(void){ 29 | Solution s1; 30 | vector v = s1.primeNumber(4); 31 | cout << v[0] <<" "<< v[1] << '\n'; 32 | vector i = s1.primeNumber(99); 33 | cout << i[0] <<" "<< i[1] << '\n'; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Solution/Day-102.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | vector continuousArray(vector&nums , int k){ 6 | dequeq; 7 | int start = 0 , end_ =0; 8 | const int &n = (int)nums.size(); 9 | int sum{}; 10 | while(end_ < n){ 11 | if(sum == k){ 12 | vectorres(q.begin() , q.end()); 13 | return res; 14 | } 15 | if(sum > k){ 16 | q.pop_front(); 17 | sum-=nums[start++]; 18 | }else{ 19 | q.push_back(nums[end_]); 20 | sum+=nums[end_++]; 21 | } 22 | } 23 | assert(false); 24 | } 25 | }; 26 | int main(void){ 27 | vectorv = {1,2,3,4,5}; 28 | Solution s; 29 | vectorres = s.continuousArray(v , 9); 30 | for(auto&itr:res){ 31 | cout << itr << ' '; 32 | } 33 | cout << '\n'; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Solution/Day-103.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | string minWindow(const string &s , const string &pattern){ 6 | unordered_mapst,pt; 7 | for(auto&itr:pattern){ 8 | pt[itr]++; 9 | } 10 | int start = 0 , end_ = s.size(), i=0; 11 | int min_window =INT_MAX; 12 | string ans; 13 | int win_size=0; 14 | listq; 15 | while(i= (int)pattern.size()){ 22 | while(start < i && (pt.find(s[start])==pt.end() || st[s[start]]-1>=pt[s[start]])){ 23 | st[s[start]]--; 24 | q.pop_front(); 25 | ++start; 26 | } 27 | string temp(q.begin() , q.end()); 28 | if(ans.size()==0 || temp < ans){ 29 | ans = temp; 30 | } 31 | min_window = min(min_window , i - start +1); 32 | } 33 | ++i; 34 | } 35 | return ans; 36 | } 37 | }; 38 | int main(void){ 39 | Solution s1; 40 | cout << s1.minWindow("figehaeci","aei") << '\n'; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Solution/Day-104.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 | bool isPalindrome(ListNode* head) { 14 | stacks; 15 | ListNode* temp = head; 16 | while(temp!=NULL){ 17 | s.push(temp->val); 18 | temp=temp->next; 19 | } 20 | temp = head; 21 | while(temp!=NULL){ 22 | if(s.top() != temp->val){ 23 | return false; 24 | } 25 | s.pop(); 26 | temp = temp->next; 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Solution/Day-105.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | using namespace chrono; 5 | 6 | function Debounced(function&f , int period){ 7 | static auto created = high_resolution_clock::now(); 8 | function fn = [=,&f](){ 9 | auto now = high_resolution_clock::now(); 10 | if (duration_cast(now - created).count() > period){ 11 | f(); 12 | } 13 | // created = now; // mark the last call of the function 14 | 15 | // For debouncing uncomment the above line, So we will mark the time for last 16 | // call made to this function and would call it again only if time difference is greater 17 | // then the period provided 18 | }; 19 | return fn; 20 | } 21 | 22 | int main(void){ 23 | int x = 0; 24 | function f = [&x](){ 25 | x++; 26 | }; 27 | 28 | auto dbf = Debounced(f, 500); 29 | for (int i = 0; i < 10; ++i) { 30 | dbf(); 31 | } 32 | // we can't call this function until 500ms period is over. 33 | if (x != 0) { 34 | throw std::runtime_error("Expected x not to change since it's debounced for 500ms"); 35 | } 36 | std::this_thread::sleep_for(milliseconds(501)); // 500 (inclusive) is threshold so let the 37 | // thread sleep for 501ms 38 | 39 | // now we can call this function as many time we want 40 | for (int i = 0; i < 10; ++i) { 41 | dbf(); 42 | } 43 | if (x != 10) { 44 | throw std::runtime_error("Expected x to be incremented 10 times"); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Solution/Day-106.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int max_jump = nums[0]; 5 | int n = nums.size(); 6 | for(int i=0;i= n-1){ 9 | return true; 10 | } 11 | } 12 | return false; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Solution/Day-107.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> levelOrder(TreeNode* root) { 15 | queueq; 16 | q.push(root); 17 | TreeNode *tempNode = nullptr; 18 | q.push(tempNode); 19 | vector>res; 20 | if(root==nullptr){return res;} 21 | vectorans; 22 | while(q.size()){ 23 | TreeNode*t = q.front(); q.pop(); 24 | if(t == nullptr){ 25 | if(q.size()) 26 | q.push(tempNode); 27 | if(ans.size()) 28 | res.push_back(ans); 29 | ans.clear(); 30 | continue; 31 | } 32 | ans.push_back(t->val); 33 | if(t->left != nullptr){ 34 | q.push(t->left); 35 | } 36 | if(t->right != nullptr){ 37 | q.push(t->right); 38 | } 39 | } 40 | return res; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Solution/Day-108.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool rotateString(string A, string B) { 4 | return (A.size() == B.size() && (A+A).find(B)!=string::npos); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Solution/Day-109.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int swapBits(unsigned int a){ 4 | // 0xAAAAAA will extract the odd bits which will be shifted to right 5 | // 0x555555 will extract the even bits which will be shifted to left 6 | return ((a&(0xAAAAAAAAAAA))>>1)|((a&(0x5555555555))<<1); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Solution/Day-110.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 | vectorres; 14 | void dfs(TreeNode* root , string path){ 15 | if(root==nullptr){ 16 | return; 17 | } 18 | if(path.size()>0){ 19 | path+="->"; 20 | } 21 | path+=to_string(root->val); 22 | if(root->left == nullptr && root->right == nullptr){ 23 | res.emplace_back(path); 24 | return; 25 | } 26 | dfs(root->left , path); 27 | dfs(root->right , path); 28 | } 29 | public: 30 | vector binaryTreePaths(TreeNode* root) { 31 | dfs(root , ""); 32 | return res; 33 | } 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /Solution/Day-111.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findAnagrams(string s, string p) { 4 | std::map f; 5 | for(auto&itr:p){ 6 | f[itr]++; 7 | } 8 | std::vector ans; 9 | int left{} , right{} , counter = p.size(); 10 | while(right <(int)s.size()){ 11 | if(f[s[right++]]-- >= 1) counter --; 12 | if(counter==0)ans.push_back(left); 13 | if(right-left == (int)p.size() && f[s[left++]]++>=0)counter++; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Solution/Day-112.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if(root == nullptr){ 14 | return nullptr; 15 | } 16 | if(root->val == p->val || root->val == q->val){ 17 | return root; 18 | } 19 | auto t1 = lowestCommonAncestor(root->left , p , q); 20 | auto t2 = lowestCommonAncestor(root->right , p , q); 21 | if(t1 != nullptr && t2 != nullptr){ 22 | return root; 23 | }else if(t1 != nullptr){ 24 | return t1; 25 | }else{ 26 | return t2; 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Solution/Day-113.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | reverse(s.begin() , s.end()); 5 | for(int i=0,j=0;i<(int)s.size();++i){ 6 | if(s[i]==' '){ 7 | if(i == 0){ 8 | continue; 9 | } 10 | reverse(s.begin()+j, s.begin()+i); 11 | j = i+1; 12 | } 13 | if(i+1==s.size()){ 14 | reverse(s.begin()+j , s.begin()+i+1); 15 | } 16 | } 17 | 18 | 19 | // if there were no redundant space then we don't require below operations and we can 20 | // return 's'. But as redundant spaces are given in leetcode problem, I guess we can't 21 | // do better. 22 | 23 | string res; 24 | int i = 0; 25 | int j = (int)s.size()-1; 26 | while(i<(int)s.size() && s[i]==' '){ 27 | ++i; 28 | } 29 | while(j>i && s[j]==' '){ 30 | --j; 31 | } 32 | while(i<=j){ 33 | if(s[i]==' ' && s[i-1]==' '){ 34 | ++i; 35 | continue; 36 | } 37 | res+=s[i]; 38 | ++i; 39 | } 40 | return res; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Solution/Day-114.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 19/03/23. 3 | // 4 | #include "stack" 5 | #include "queue" 6 | #include "vector" 7 | #include "iostream" 8 | 9 | using namespace std; 10 | 11 | bool isAlpha(const char &ch) { 12 | return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); 13 | } 14 | 15 | string reverseString(const string &str) { 16 | stack words; // alphabetic words 17 | queue delimiters; // continuous string of delimiters 18 | int start{}, end{}; 19 | bool beginningByDelimiter{false}; 20 | while (end < (int) str.size()) { 21 | if (isAlpha(str[start])) { 22 | while (end < (int) str.size() && isAlpha(str[end])) { 23 | end++; 24 | } 25 | words.push(str.substr(start, end - start)); 26 | } else { 27 | if (start == 0) { 28 | beginningByDelimiter = true; 29 | } 30 | while (end < (int) str.size() && !isAlpha(str[end])) { 31 | end++; 32 | } 33 | delimiters.push(str.substr(start, end - start)); 34 | } 35 | start = end; 36 | } 37 | 38 | // We have separated the word & delimiters from the string. 39 | // only confusion is where to start build our result string. 40 | // i.e. what should appended first a word or a delimiter ? 41 | // for this we'll use beginningByDelimiter variable :-) 42 | string result{}; 43 | while (!words.empty() || !delimiters.empty()) { 44 | if (beginningByDelimiter) { 45 | result += delimiters.front(); 46 | delimiters.pop(); 47 | beginningByDelimiter = false; 48 | } else { 49 | if (!words.empty()) { 50 | result += words.top(); 51 | words.pop(); 52 | } 53 | if (!delimiters.empty()) { 54 | result += delimiters.front(); 55 | delimiters.pop(); 56 | } 57 | } 58 | } 59 | return result; 60 | } 61 | 62 | int main() { 63 | vector testStrings = {"hello/world:here", "hello/world:here/", "hello//world:here", 64 | "//hello//", "//hello//world//here//"}; 65 | // Let's test 66 | for (auto &str: testStrings) { 67 | cout << "Input: " << str << " Output: " << reverseString(str) << endl; 68 | } 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Solution/Day-115.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 20/03/23. 3 | // 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | 9 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | 11 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | 13 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 14 | }; 15 | 16 | class Solution { 17 | bool isExactTreeMatch(TreeNode*p, TreeNode*q) { 18 | // copy and replace content of "isSameTree" with this code to get a solution for leetcode. 19 | if (p == nullptr && q == nullptr) { 20 | return true; 21 | } else if (p == nullptr or q == nullptr) { 22 | return false; 23 | } 24 | if (p -> val != q->val) { 25 | return false; 26 | } 27 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 28 | } 29 | public: 30 | // using below function as helper method as checker for subtree matching. 31 | bool isSameTree(TreeNode *p, TreeNode *q) { 32 | if (isExactTreeMatch(p,q)) { 33 | return true; 34 | } 35 | // check right subtree. 36 | if (q->left && isSameTree(p, q->left)) { 37 | return true; 38 | } 39 | // check left subtree 40 | if (q->right && isSameTree(p, q->right)) { 41 | return true; 42 | } 43 | return false; 44 | } 45 | }; -------------------------------------------------------------------------------- /Solution/Day-116.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 25/03/23. 3 | // 4 | 5 | class Node { 6 | private: 7 | Node*left = nullptr; 8 | Node*right = nullptr; 9 | bool isLeftEvaluated = false; 10 | bool isRightEvaluated = false; 11 | public: 12 | Node() = default; 13 | Node* getLeft() { 14 | if (!isLeftEvaluated) { 15 | left = new Node(); 16 | isLeftEvaluated = true; 17 | } 18 | return left; 19 | } 20 | 21 | Node* getRight() { 22 | if (!isRightEvaluated) { 23 | right = new Node(); 24 | isRightEvaluated = true; 25 | } 26 | return right; 27 | } 28 | }; 29 | 30 | Node* generate() { // will generate the binary tree in O(1) 31 | return new Node(); 32 | } -------------------------------------------------------------------------------- /Solution/Day-117.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 05/07/23. 3 | // 4 | #include "queue" 5 | 6 | using namespace std; 7 | 8 | //struct TreeNode { 9 | // int val; 10 | // TreeNode *left; 11 | // TreeNode *right; 12 | // 13 | // TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | // 15 | // TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | // 17 | // TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 18 | //}; 19 | 20 | 21 | /* 22 | * This question focus over BFS the solution is for maximum sum as followed for LeetCode 23 | * But question actually asks for minimum, So it will need to tweak ">" to "<" at line 45 and 24 | * and INT_MIN to INT_MAX at line 29 25 | */ 26 | class Solution { 27 | public: 28 | int maxLevelSum(TreeNode *root) { 29 | int max_sum{INT_MIN}, max_sum_level{1}, current_level = 1; 30 | if (!root) 31 | return max_sum_level; 32 | queue q; 33 | q.push(root); 34 | while (!q.empty()) { 35 | int temp_sum{}; 36 | int level_size = static_cast(q.size()); 37 | for (int i=0; ival; 39 | root = q.front(); q.pop(); 40 | if (root->left) 41 | q.push(root->left); 42 | if (root->right) 43 | q.push(root->right); 44 | } 45 | if (temp_sum > max_sum) { 46 | max_sum = temp_sum; 47 | max_sum_level = current_level; 48 | } 49 | current_level++; 50 | } 51 | return max_sum_level; 52 | } 53 | }; -------------------------------------------------------------------------------- /Solution/Day-118.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 06/07/23. 3 | // 4 | #include "vector" 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector sortedSquares(vector &nums) { 11 | vectorans(nums.size()); 12 | int left = 0, right = static_cast(nums.size()-1), current = right; 13 | while (current >= 0) { 14 | int leftPosSquare = nums.at(left) * nums.at(left); 15 | int rightPosSquare = nums.at(right) * nums.at(right); 16 | leftPosSquare > rightPosSquare ? left ++ : right --; 17 | ans.at(current--) = max(leftPosSquare, rightPosSquare); 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Solution/Day-119.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 07/07/23. 3 | // 4 | 5 | #include "iostream" 6 | #include "vector" 7 | 8 | using namespace std; 9 | 10 | vector getSortestInterval(vector>&intervals) { 11 | int start = intervals[0][1]; 12 | int end = start; 13 | bool startFound = false; 14 | for (int i=1; i < static_cast(intervals.size()); ++i){ 15 | auto itr = intervals.at(i); 16 | if (!startFound) { 17 | if (itr.at(0) < start and itr.at(1) < start) { 18 | start = itr.at(1); 19 | } else { 20 | startFound = true; 21 | } 22 | } else { 23 | end = max(end, itr.at(0)); 24 | } 25 | } 26 | return {start, end}; 27 | } 28 | 29 | int main() { 30 | vector>intervals = {{0, 3}, 31 | {2, 6}, 32 | {3, 4}, 33 | {6, 9} 34 | }; 35 | vector res = getSortestInterval(intervals); 36 | cout << res.at(0) << endl << res.at(1) << endl; 37 | if (res.at(0) == 3 and res.at(1) == 6) { 38 | cout << "passed" << endl; 39 | } else { 40 | cout << "failed" << endl; 41 | } 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Solution/Day-120.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Amit Kumar on 12/07/23. 3 | // 4 | 5 | #include "iostream" 6 | #include "string" 7 | 8 | using namespace std; 9 | 10 | enum State { 11 | NotInitialized, Odd, Even 12 | }; 13 | 14 | class ModifiedSingleton { 15 | 16 | string instanceName; 17 | 18 | ModifiedSingleton() = default; 19 | 20 | explicit ModifiedSingleton(string name) : instanceName(std::move(name)) {} 21 | 22 | public: 23 | ModifiedSingleton(ModifiedSingleton &ms) = delete; 24 | 25 | static ModifiedSingleton &getInstance() { 26 | static ModifiedSingleton instanceOne; 27 | static ModifiedSingleton instanceTwo; 28 | 29 | static State currentState = State::NotInitialized; 30 | 31 | if (currentState == State::NotInitialized) { 32 | currentState = State::Odd; 33 | instanceOne = ModifiedSingleton("First Instance"); 34 | instanceTwo = ModifiedSingleton("Second Instance"); 35 | } 36 | 37 | if (currentState == State::Odd) { 38 | currentState = State::Even; 39 | return instanceTwo; 40 | } else { 41 | currentState = State::Odd; 42 | return instanceOne; 43 | } 44 | } 45 | 46 | friend ostream &operator<<(ostream &out, const ModifiedSingleton &ms) { 47 | out << ms.instanceName; 48 | return out; 49 | } 50 | 51 | }; 52 | 53 | int main() { 54 | for (int i = 1; i < 10; ++i) { 55 | cout << ((i&1) ? "Odd Call: " : "Even Call: "); 56 | cout << ModifiedSingleton::getInstance() << endl; 57 | } 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Solution/Day-122.cpp: -------------------------------------------------------------------------------- 1 | int solve(vector>& matrix) { 2 | for(int i=0; i 8 | using namespace std; 9 | class Soltuion { 10 | public: 11 | int getExpValue( int n) { 12 | return ceil(double(log2(n))); 13 | } 14 | }; 15 | signed main(void){ 16 | int n; cin >> n; 17 | Soltuion s; 18 | cout << s.getExpValue(n) << '\n'; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Solution/Day-128.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void tower_of_hanoi(int n , int s , int h , int d) { 4 | if (n == 1) { 5 | cout << "move " << s << " to " << d << '\n'; 6 | return; 7 | } 8 | tower_of_hanoi(n-1,s,d,h); 9 | cout << "move " << s << " to " << d << '\n'; 10 | tower_of_hanoi(n-1,h,s,d); 11 | } 12 | void solve( int n) { 13 | // 1-> source 14 | // 2-> helper 15 | // 3-> destination 16 | tower_of_hanoi(n, 1,2,3); 17 | } 18 | signed main(void){ 19 | int n = 3; 20 | solve(n); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Solution/Day-133.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct Node { 3 | int data; 4 | Node *left; 5 | Node *right; 6 | 7 | Node(int val) { 8 | data = val; 9 | left = right = NULL; 10 | } 11 | }; 12 | */ 13 | 14 | class Solution{ 15 | Node*temp; 16 | bool found = false; 17 | bool next=false; 18 | void dfs(Node* root ,Node *x) { 19 | if (root==nullptr) return; 20 | if (found) { 21 | return ; 22 | } 23 | if (root->data == x->data) { 24 | next = true; 25 | dfs(root->right, x); 26 | return; 27 | } 28 | if (root->left == nullptr && root->right==nullptr) { 29 | if (next) { 30 | temp = root; 31 | next = false; 32 | found = true; 33 | } 34 | return ; 35 | } 36 | dfs(root->left , x); 37 | if (next) { 38 | temp = root; 39 | next = false; 40 | found = true; 41 | } 42 | dfs(root->right , x); 43 | } 44 | public: 45 | // returns the inorder successor of the Node x in BST (rooted at 'root') 46 | Node * inOrderSuccessor(Node *root, Node *x) { 47 | dfs(root ,x); 48 | if (next) { 49 | temp = nullptr; 50 | } 51 | return temp; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Solution/Day-134.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class SparseArray{ 4 | maparr; 5 | public: 6 | void init(vector&arr , int n) { 7 | for (int i=0; iarr[i] = arr[i]; 9 | } 10 | return; 11 | } 12 | void set(int index , int value) { 13 | this->arr[index] = value; 14 | return; 15 | } 16 | int get(int index) { 17 | return arr[index]; 18 | } 19 | }; 20 | signed main(void){ 21 | vectorarr = {1,0,0,0,2,0,0,0,3,0,0,0,4}; 22 | SparseArray s; 23 | s.init(arr, arr.size()); 24 | s.set(1,1000); 25 | cout << s.get(1) << '\n'; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Solution/Day-136.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int maxAns; 4 | int area(vector&his) { 5 | int a{}; 6 | stacks; 7 | int i=0; 8 | for(; i>& matrix) { 34 | if (matrix.size() ==0 || matrix[0].size()==0){ 35 | return 0; 36 | } 37 | maxAns = 0; 38 | vectorhistogram(matrix[0].size()); 39 | for(int row=0; row &getList() const; 16 | * }; 17 | */ 18 | 19 | class NestedIterator { 20 | vectorans; 21 | int current_index =0; 22 | public: 23 | void init(vector &nestedList) { 24 | for (int i=0; i &nestedList) { 33 | ans.clear(); 34 | current_index = 0; 35 | init(nestedList); 36 | } 37 | 38 | int next() { 39 | return ans.at(current_index++); 40 | } 41 | 42 | bool hasNext() { 43 | return current_index != ans.size(); 44 | } 45 | }; 46 | 47 | /** 48 | * Your NestedIterator object will be instantiated and called as such: 49 | * NestedIterator i(nestedList); 50 | * while (i.hasNext()) cout << i.next(); 51 | */ 52 | 53 | -------------------------------------------------------------------------------- /Solution/Day-178.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Let's just say we got first throw result as 5 then : 4 | 1. If we consider next number will be same as required , i.e. for the first game we 5 | will get 6 and for second game we will get 5 then probabilities are similar, 6 | 1/6 for winning the first game and 1/6 for winning the second game. 7 | 8 | 2. Now comes the interesting part , let's just say you did not get the required number this time , i.e. you will not 9 | get 6 for first game and you are not going to get 5 for second game , in this move. 10 | 11 | Then for the first game you might receive {1,2,3,4,5} then probability of starting the game 12 | from very beginning is 4/6 -> because if you receive 5 as your number in next move you just need a 6. 13 | 14 | But for the Second game, you might receive {1,2,3,4,6} then probability of starting the game from very 15 | beginning is 5/6, as whatever the number you receive you have to start the game from beginning and now you need 16 | atleast one more move then previous game. 17 | 18 | Thus mathematically it's very likely that you will have to pay less cost if you play the first game!! 19 | 20 | 21 | 22 | IF YOU FOUND SOMETHING WRONG HERE , PLEASE MAIL ME: offamitkumar@gmail.com 23 | SUGGESTION & DOUBTS ARE WELCOMED ;) 24 | 25 | */ 26 | #include 27 | using namespace std; 28 | int total_play = 10000; 29 | int play(int a , int b) { 30 | random_device rand_dev; 31 | mt19937 generator(rand_dev()); 32 | uniform_int_distribution uni_int(1,6); 33 | int current = uni_int(generator); 34 | int thrown {1}; 35 | while (true) { 36 | int next = uni_int(generator); 37 | thrown++; 38 | if (current == a && next == b) { 39 | return thrown; 40 | } 41 | current = next; 42 | } 43 | } 44 | signed main(void){ 45 | double score_one{} , score_two{}; 46 | for (int i=0; i 2 | using namespace std; 3 | #define int int64_t 4 | void interleave (stack&s) { 5 | queueq; 6 | while (!s.empty()) { 7 | q.push(s.top()); s.pop(); 8 | } 9 | int f = q.size(); 10 | int n = f/2+(f&1); 11 | for (int i=0; is; 46 | for (int i=5; i>=1; --i) { 47 | s.push(i); 48 | } 49 | interleave(s); 50 | while (!s.empty()) { 51 | cout << s.top() << '\n'; 52 | s.pop(); 53 | } 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Solution/Day-185.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Rectangle{ 4 | public: 5 | pairtop_left; 6 | int length, height; 7 | Rectangle(int a, int b, int c ,int d) : top_left(a,b) , length(c) , height(d){} 8 | }; 9 | class Solution{ 10 | private: 11 | public: 12 | int overlappingArea(Rectangle&r1 , Rectangle&r2) { 13 | pairbr1 , br2; // bottom right corner for r1 and r2 rectangle 14 | br1.first = r1.top_left.first + r1.length; 15 | br1.second = r1.top_left.second - r1.height; 16 | br2.first = r2.top_left.first + r2.length; 17 | br2.second = r2.top_left.second - r2.height; 18 | return max(min(br1.first , br2.first) - max(r1.top_left.first , r2.top_left.first),0) * max(min(r1.top_left.second , r2.top_left.second) - max(br1.second , br2.second),0); 19 | } 20 | }; 21 | int main(void){ 22 | Rectangle r1(1,4,3,3) , r2(0,5,4,3); 23 | Solution s; 24 | cout << s.overlappingArea(r1 , r2) << '\n'; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Solution/Day-191.cpp: -------------------------------------------------------------------------------- 1 | bool compare(vector&a, vector&b) { 2 | return a.at(1) < b.at(1); 3 | } 4 | class Solution { 5 | public: 6 | int eraseOverlapIntervals(vector>& intervals) { 7 | sort(intervals.begin(), intervals.end(), compare); 8 | int counter{}; 9 | const int &n = intervals.size(); 10 | int current_end = 0; 11 | for (int i=0; i 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | vector stabbingPoints(vector>&inter) { 6 | sort(inter.begin() , inter.end() , [](paira , pairb) { 7 | if (a.second == b.second) { 8 | return a.first < b.second; 9 | } else { 10 | return a.second < b.second; 11 | } 12 | }); 13 | vectorans; 14 | int last = numeric_limits::min(); 15 | for(int i=0; i> interval = {{1,4},{4,5},{7,9},{9,12}}; 26 | Solution s; 27 | vectorans = s.stabbingPoints(interval); 28 | for(const auto&itr:ans) { 29 | cout << itr << ' '; 30 | } 31 | cout << '\n'; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Solution/Day-214.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | int findMaxConsecutiveOnes(const bitset<66>& nums) { 6 | int max_{} , t{}; 7 | for(int i=0; i<(int)nums.size(); ++i){ 8 | if(nums[i]){ 9 | t++; 10 | }else{ 11 | if(t > max_){ 12 | max_ = t; 13 | } 14 | t = 0; 15 | } 16 | } 17 | if(t > max_){ 18 | max_ = t; 19 | } 20 | return max_; 21 | } 22 | }; 23 | 24 | int main(void){ 25 | Solution s; 26 | int num; cin >> num; 27 | cout << s.findMaxConsecutiveOnes(bitset<66>(num)) << '\n'; 28 | } 29 | -------------------------------------------------------------------------------- /Solution/Day-221.cpp: -------------------------------------------------------------------------------- 1 | /* This problem was asked by Zillow. 2 | * Let's define a "sevenish" number to be one which is either a power of 7, 3 | * or the sum of unique powers of 7. 4 | * The first few sevenish numbers are 1, 7, 8, 49, and so on. 5 | * 6 | * Create an algorithm to find the nth sevenish number. 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | long long nth_Sevenish_number(array&power_of_7,const int &number){ 13 | int mask = 1; 14 | long long ans{}; 15 | for(int i=0;i<30;++i){ 16 | if(number&mask){ 17 | ans+=power_of_7.at(i); 18 | } 19 | mask<<=1; 20 | } 21 | return ans; 22 | } 23 | 24 | int main(void){ 25 | arraypower_of_7; 26 | for(int i=0;i(power_of_7.size());++i){ 27 | if(i==0){ 28 | power_of_7.at(i) = 1; 29 | }else{ 30 | power_of_7.at(i) = power_of_7.at(i-1)*7; 31 | } 32 | } 33 | int number; 34 | cin>>number; 35 | cout< 24 | using namespace std; 25 | int main(void){ 26 | string path; 27 | cin>>path; 28 | istringstream t_path(path); 29 | string extract; 30 | // we can use stack it will make complex solution 31 | // so we can use vector to simplify the solution 32 | vectordirectories; 33 | string absolute_path=""; 34 | while(getline(t_path , extract , '/')){ 35 | if(extract=="" or extract==".") 36 | continue; 37 | if(extract!="..")/* we have to move a directory up if it is true */{ 38 | directories.emplace_back(extract); 39 | }else if(!directories.empty()){ 40 | directories.pop_back(); 41 | } 42 | } 43 | if(directories.empty()){ 44 | absolute_path = "/"; 45 | } 46 | for(auto &directory:directories){ 47 | absolute_path+="/"+directory; 48 | } 49 | cout<<"Standard Path is : "< 12 | using namespace std; 13 | struct Node{ 14 | public: 15 | int value; 16 | Node *left_Node; 17 | Node *right_Node; 18 | Node():value(0),left_Node{nullptr},right_Node{nullptr}{} // constructor 19 | }; 20 | Node* insert(Node* root , int value){ 21 | if(!root){ 22 | root = new Node(); 23 | root->value = value; 24 | root->left_Node = nullptr; 25 | root->right_Node= nullptr; 26 | }else{ 27 | if(root->value < value){ 28 | root->right_Node = insert(root->right_Node , value); 29 | }else if(root->value > value){ 30 | root->left_Node = insert(root->left_Node , value); 31 | } 32 | } 33 | return root; 34 | } 35 | void print_PreOrder(Node* root){ 36 | if(root==nullptr) 37 | return; 38 | print_PreOrder(root->left_Node); 39 | cout<value<<' '; 40 | print_PreOrder(root->right_Node); 41 | } 42 | 43 | 44 | // O(1) Space Complexity Solution (Pre-Order) 45 | void print_PreOrder(Node *root , int &&dummy){ 46 | while(root!=nullptr){ 47 | if(root->left_Node==nullptr){ 48 | cout<value<<' '; 49 | root = root->right_Node; 50 | }else{ 51 | Node* predecessor = root->left_Node; 52 | while(predecessor->right_Node!=nullptr and predecessor->right_Node!=root)/*second condition is to stop revisiting the node*/{ 53 | predecessor = predecessor->right_Node; 54 | } 55 | if(predecessor->right_Node==nullptr){ 56 | predecessor->right_Node = root; 57 | root = root->left_Node; 58 | }else{ 59 | predecessor->right_Node=nullptr;// removing the link although not required 60 | cout<value<<' '; 61 | root = root->right_Node; 62 | } 63 | } 64 | } 65 | } 66 | int main(int argc , char *argv[]){ 67 | Node *root{nullptr}; 68 | root = insert(root , 10); 69 | root = insert(root , 5); 70 | root = insert(root , 30); 71 | root = insert(root , -2); 72 | root = insert(root , 6); 73 | root = insert(root , 40); 74 | root = insert(root , 2); 75 | root = insert(root , 8); 76 | root = insert(root , -1); 77 | cout<<"Default O(H) PreOrder: "; 78 | print_PreOrder(root); 79 | cout< 12 | using std::cin; 13 | using std::endl; 14 | using std::cout; 15 | using std::vector; 16 | auto get_Solution(vector&arr)->int{ 17 | int ans = 1; // minimum answer possible 18 | // idea is to check whether we can form a answer of prefix_sum[i] + 1 ,, or not 19 | for(int i=0;i(arr.size());++i){ 20 | if(ans>=arr[i]){ 21 | ans+=arr[i]; // because we can make a sum of 1 to (ans-1) by using the array form 0 to i 22 | }else{ 23 | break; 24 | } 25 | } 26 | return ans; 27 | } 28 | int main(int argc , char *argv[]){ 29 | int n; 30 | cin>>n;//array size 31 | vectorarr(n,0); 32 | for(auto &itr:arr) 33 | cin>>itr; 34 | cout<; 2 | bool compare(pci&a , pci&b){ 3 | return a.second < b.second; 4 | } 5 | class Solution { 6 | public: 7 | string reorganizeString(string s) { 8 | mapm; 9 | for(auto&itr:s) { 10 | m[itr]++; 11 | } 12 | priority_queue , function> pq(compare); 13 | for(auto&itr:m) { 14 | pq.push(itr); 15 | } 16 | string res; 17 | while (pq.size() > 1) { 18 | pci charOne = pq.top(); pq.pop(); 19 | pci charTwo = pq.top(); pq.pop(); 20 | res+=charOne.first; charOne.second--; 21 | res+=charTwo.first; charTwo.second--; 22 | if (charOne.second) pq.push(charOne); 23 | if (charTwo.second) pq.push(charTwo); 24 | } 25 | if (pq.size()) { 26 | pci ch = pq.top(); pq.pop(); 27 | if(ch.second >=2) { 28 | return ""; 29 | } 30 | res+=ch.first; 31 | } 32 | return res; 33 | } 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /Solution/Day-232.cpp: -------------------------------------------------------------------------------- 1 | class MapSum { 2 | class Node{ 3 | public: 4 | Node* node[30]; 5 | bool isEnd; 6 | int num; 7 | Node() { 8 | for (int i=0; i<30; ++i) { 9 | node[i] = nullptr; 10 | } 11 | isEnd = false; 12 | num = 0; 13 | } 14 | }; 15 | Node *root; 16 | public: 17 | /** Initialize your data structure here. */ 18 | MapSum() { 19 | root = new Node(); 20 | } 21 | 22 | void insert(string key, int val) { 23 | Node* temp = root; 24 | for (auto&itr:key) { 25 | if (temp -> node[itr-'a'] == nullptr) { 26 | temp->node[itr-'a'] = new Node(); 27 | } 28 | temp = temp->node[itr-'a']; 29 | } 30 | temp -> num = val; 31 | temp -> isEnd = true; 32 | } 33 | int dfs(Node*temp) { 34 | int res = 0; 35 | if (temp == nullptr)return res; 36 | if (temp-> isEnd) { 37 | res += temp -> num; 38 | } 39 | for (auto itr: temp->node) { 40 | res += dfs(itr); 41 | } 42 | return res; 43 | } 44 | int sum(string prefix) { 45 | int res{}; 46 | Node*temp = root; 47 | for (auto&itr:prefix) { 48 | if (temp -> node[itr-'a'] != nullptr) { 49 | temp = temp->node[itr-'a']; 50 | } else { 51 | return res; 52 | } 53 | } 54 | return res + dfs(temp); 55 | } 56 | }; 57 | 58 | /** 59 | * Your MapSum object will be instantiated and called as such: 60 | * MapSum* obj = new MapSum(); 61 | * obj->insert(key,val); 62 | * int param_2 = obj->sum(prefix); 63 | */ 64 | -------------------------------------------------------------------------------- /Solution/Day-241.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | int low = 0 , high = citations.size()-1; 5 | const int &n = citations.size(); 6 | while (low <= high) { 7 | int mid = (low + high) / 2; 8 | if (citations[mid] == n-mid) { 9 | return n - mid; 10 | } else if (citations[mid] > n - mid) { 11 | high = mid - 1; 12 | } else { 13 | low = mid + 1; 14 | } 15 | } 16 | return n - low; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Solution/Day-242.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | arrayhour; 9 | 10 | Solution () { 11 | fill (hour.begin(), hour.end(), 0); 12 | } 13 | 14 | void update (int Hour, int subscriberIncreased) { 15 | hour.at(Hour) += subscriberIncreased; 16 | } 17 | 18 | int query (int startHour, int endHour) { 19 | return accumulate(hour.begin()+startHour , hour.begin()+endHour , 0ll); 20 | } 21 | }; 22 | int main(void){ 23 | Solution s; 24 | s.update(1 , 25); 25 | s.update(2 , 25); 26 | s.update(2 , 25); 27 | s.update(3 , 25); 28 | assert(s.query(1 , 3) != 100); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Solution/Day-244.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | unordered_setprinted; 5 | void generate_primes(void) { 6 | for(int i=2; ;++i) { 7 | if(all_of(printed.begin() , printed.end() , [i](int x){ return (i % x ) !=0; })){ 8 | cout << i << '\n'; 9 | printed.insert(i); 10 | sleep(1); 11 | } 12 | } 13 | } 14 | int main(void){ 15 | generate_primes(); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Solution/Day-255.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution{ 6 | public: 7 | vector>closer; 8 | void dfs(vector>&graph , int parent , int root) { 9 | if (graph.size() == 1) { 10 | return; 11 | } 12 | for (auto&itr: graph.at(parent)) { 13 | if (closer.at(root).at(itr) == 0) { 14 | closer.at(root).at(itr) = 1; 15 | dfs(graph , itr , root); 16 | } 17 | } 18 | } 19 | void setCloser(vector>&graph) { 20 | closer.resize(graph.size() , vector(graph.size())); 21 | for (int i=0; i <(int)graph.size(); ++i) { 22 | closer.at(i).at(i) = 1; 23 | dfs(graph,i, i); 24 | } 25 | } 26 | }; 27 | int main(void){ 28 | vector> graph(4); 29 | graph.at(0).push_back(0); graph.at(0).push_back(1); graph.at(0).push_back(3); 30 | graph.at(1).push_back(1); graph.at(1).push_back(2); 31 | graph.at(2).push_back(2); 32 | graph.at(3).push_back(3); 33 | 34 | vector> closer = { 35 | {1, 1, 1, 1} , 36 | {0, 1, 1, 0} , 37 | {0, 0, 1, 0} , 38 | {0, 0, 0, 1} 39 | }; 40 | Solution s; 41 | s.setCloser(graph); 42 | for (int i=0; i<(int)closer.size(); ++i) { 43 | for (int j=0; j<(int)closer.at(0).size(); ++j) { 44 | assert(closer.at(i).at(j) == s.closer.at(i).at(j)); 45 | } 46 | } 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Solution/Day-256.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int value; 8 | node*next; 9 | }; 10 | node* getlist(int value) { 11 | node* head = nullptr, *tail = nullptr; 12 | for (int i=1; i<=value; ++i) { 13 | if (head == nullptr) { 14 | head= new node(); 15 | head->value = i; 16 | tail = head; 17 | }else { 18 | tail->next = new node(); 19 | tail = tail->next; 20 | tail->value = i; 21 | } 22 | } 23 | return head; 24 | } 25 | class solution { 26 | vectorvalues; 27 | void extractvalues(node*head) { 28 | node *temp = head; 29 | while(head != nullptr) { 30 | values.push_back(head->value); 31 | head = head->next; 32 | } 33 | sort(values.begin(), values.end()); 34 | head = temp; 35 | } 36 | void setlist(node*head) { 37 | node*temp = head; 38 | int i=0; 39 | while(temp != nullptr) { 40 | temp->value = values.at(i++); 41 | temp = temp->next; 42 | } 43 | } 44 | public: 45 | node* rearrange(node* head) { 46 | if (head == nullptr || head->next == nullptr) { 47 | return head; 48 | } 49 | extractvalues(head); 50 | for (int i=1; i+1 < (int)values.size(); i+=2) { 51 | swap(values.at(i) , values.at(i+1)); 52 | } 53 | setlist(head); 54 | return head; 55 | } 56 | }; 57 | int main(void){ 58 | node*n1 = getlist(5); 59 | solution s1; 60 | s1.rearrange(n1); 61 | while (n1!=nullptr) { 62 | cout << n1->value << ' ' ; 63 | n1 = n1->next; 64 | } 65 | cout << '\n'; 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Solution/Day-257.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution{ 7 | public: 8 | pair getInterval(vector&v) { 9 | int low =0 ,high = v.size()-1; 10 | int max_seen = v.at(0); 11 | while (low < high) { 12 | if (v.at(low) >= max_seen) { 13 | max_seen = v.at(low); 14 | ++low; 15 | } else { 16 | break; 17 | } 18 | } 19 | max_seen = v.at(high); 20 | while (low < high) { 21 | if (v.at(high) <= max_seen) { 22 | max_seen = v.at(high); 23 | --high; 24 | } else { 25 | break; 26 | } 27 | } 28 | if ((low-1) == (high+1)) { 29 | return make_pair(-1,-1); 30 | } else { 31 | return make_pair(low-1, high+1); 32 | } 33 | } 34 | }; 35 | int main(void){ 36 | vectorv{3, 7, 5, 6, 9}; 37 | Solution s; 38 | auto p = s.getInterval(v); 39 | cout << p.first << ' ' << p.second << '\n'; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Solution/Day-258.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | struct Node; 6 | struct Node { 7 | int left; 8 | int right; 9 | Node () { 10 | left = -1; 11 | right = -1; 12 | } 13 | }; 14 | struct Solution { 15 | vectorspiralOrder; 16 | vector getSpiralOrder(const vector&tree, int root) { 17 | stackleftToRight , rightToLeft; 18 | leftToRight.push(root); 19 | while ((!leftToRight.empty()) || (!rightToLeft.empty())) { 20 | while (!leftToRight.empty()) { 21 | int node = leftToRight.top(); leftToRight.pop(); 22 | if (tree.at(node).left != -1) { 23 | rightToLeft.push(tree.at(node).left); 24 | } 25 | if (tree.at(node).right != -1) { 26 | rightToLeft.push(tree.at(node).right); 27 | } 28 | spiralOrder.push_back(node); 29 | } 30 | while (!rightToLeft.empty()) { 31 | int node = rightToLeft.top(); rightToLeft.pop(); 32 | if (tree.at(node).right != -1) { 33 | leftToRight.push(tree.at(node).right); 34 | } 35 | if (tree.at(node).left != -1) { 36 | leftToRight.push(tree.at(node).left); 37 | } 38 | spiralOrder.push_back(node); 39 | } 40 | } 41 | return spiralOrder; 42 | } 43 | }; 44 | int main(void){ 45 | vector tree(8); 46 | tree.at(1).left = 2; 47 | tree.at(1).right = 3; 48 | tree.at(2).left = 4; 49 | tree.at(2).right = 5; 50 | tree.at(3).left = 6; 51 | tree.at(3).right = 7; 52 | 53 | Solution s; 54 | const vector&spiralOrder = s.getSpiralOrder(tree, 1); 55 | for (const auto& itr: spiralOrder) { 56 | cout << itr <<' '; 57 | } 58 | cout << '\n'; 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Solution/Day-259.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | class Solution { 8 | public: 9 | vector getMove (vector&s) { 10 | map> f; 11 | for (auto&itr: s) { 12 | f[itr[0]].insert((int)itr.size()); 13 | } 14 | vectorgood; 15 | for (auto&itr:f) { 16 | if (none_of(itr.second.begin(), itr.second.end() , [](int x) { return x%2!=0; })) { 17 | good.push_back(itr.first); 18 | } 19 | } 20 | return good; 21 | } 22 | }; 23 | int main(void){ 24 | vectordict {"cat" , "calf" , "dog" , "bear"}; 25 | Solution s; 26 | vectorv = s.getMove(dict); 27 | for (auto&itr : v) { 28 | cout << itr << ' '; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Solution/Day-260.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution { 6 | public: 7 | vector getArray(vector&v) { 8 | int negCounter = count_if(v.begin(), v.end(), [](char ch) { return ch=='-';}); 9 | int start = negCounter; 10 | vector ans(v.size(), -1); 11 | ans[0] = start++; 12 | --negCounter; 13 | for (int i=1; i<(int)v.size(); ++i) { 14 | if (v.at(i) == '+') { 15 | ans.at(i) = start++; 16 | } else { 17 | ans.at(i) = negCounter--; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | int main(void){ 24 | // vector v{'*', '+' , '+' , '-', '+'}; 25 | vector v{'*', '-', '-', '-', '+', '+'}; 26 | Solution s; 27 | vector sol = s.getArray(v); 28 | for (auto&itr:sol) { 29 | cout << itr <<' '; 30 | } 31 | cout << '\n'; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Solution/Day-261.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | struct Node{ 8 | char ch; 9 | bool leaf; 10 | int freq; 11 | Node* leftTree; 12 | Node* rightTree; 13 | Node() { 14 | ch = '-'; 15 | leaf = false; 16 | freq = 0; 17 | leftTree = nullptr; 18 | rightTree = nullptr; 19 | } 20 | Node(char node_ch , int num) { 21 | ch = node_ch; 22 | freq = num; 23 | leaf = true; 24 | leftTree = nullptr; 25 | rightTree = nullptr; 26 | } 27 | Node(const Node&n1){ 28 | ch = n1.ch; 29 | freq = n1.freq; 30 | leaf = n1.leaf; 31 | leftTree= n1.leftTree; 32 | rightTree= n1.rightTree; 33 | } 34 | Node(int fr) { 35 | ch = '-'; 36 | freq = fr; 37 | leaf = false; 38 | leftTree = nullptr; 39 | rightTree = nullptr; 40 | } 41 | }; 42 | Node* getTree(queue&q) { 43 | if (q.size() == 1) { 44 | Node *n = &q.front(); 45 | q.pop(); 46 | return n; 47 | } 48 | Node *n1 = new Node(q.front()); q.pop(); 49 | Node *n2 = new Node(q.front()); q.pop(); 50 | Node n3(n1->freq + n2->freq); 51 | n3.leftTree = n1; 52 | n3.rightTree = n2; 53 | q.push(n3); 54 | Node*n = getTree(q); 55 | return n; 56 | } 57 | void getCode(map&code , Node*n1 , const string &path) { 58 | if(n1->ch != '-') { 59 | if(n1->ch != 0) { 60 | code[n1->ch] = path; 61 | } 62 | return; 63 | } 64 | if(n1->leftTree) 65 | getCode(code , n1->leftTree, path+"0"); 66 | if(n1->rightTree) 67 | getCode(code , n1->rightTree, path+"1"); 68 | } 69 | Node* buildTree(vector&words) { 70 | map freq; 71 | for (auto&word:words) { 72 | for (auto&ch:word) { 73 | freq[ch]++; 74 | } 75 | } 76 | vectornodes; 77 | for (auto&itr:freq) { 78 | cout << "[" << itr.first <<"," << itr.second << "], "; 79 | nodes.push_back(Node(itr.first, itr.second)); 80 | } 81 | cout << '\n'; 82 | sort(nodes.begin(), nodes.end(), [](const Node&n1 ,const Node&n2) {return n1.freq < n2.freq;}); 83 | queueq; 84 | for (int i=0; i<(int)nodes.size(); ++i) { 85 | q.push(nodes.at(i)); 86 | } 87 | Node* n = getTree(q); 88 | return n; 89 | } 90 | 91 | int main(void){ 92 | vector words {"cats"}; 93 | Node *tree= buildTree(words); 94 | mapcode; 95 | getCode(code , tree, ""); 96 | for (auto&itr: code) { 97 | cout << itr.first <<' ' << itr.second << '\n'; 98 | } 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /Solution/Day-262.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution { 6 | vectorinTime, minFoundTime; 7 | vector>bridge; 8 | int timer; 9 | void getBridges(vector>&graph , int node=0, int parent=-1) { 10 | inTime[node] = minFoundTime[node] = timer++; 11 | int countChild{}; 12 | bool isBridge = false; 13 | for (auto&itr: graph[node]) { 14 | if (itr != parent) { 15 | ++countChild; 16 | if (inTime[itr] == -1) { 17 | getBridges(graph, itr, node); 18 | } 19 | if (inTime[node] < minFoundTime[itr]) { 20 | bridge.push_back(make_pair(node , itr)); 21 | } 22 | minFoundTime[node] = min(minFoundTime[node], minFoundTime[itr]); 23 | } 24 | } 25 | } 26 | public: 27 | vector> findBridges(vector>&graph) { 28 | bridge.clear(); 29 | timer = 0; 30 | inTime.assign(graph.size(), -1); 31 | minFoundTime.resize(graph.size()); 32 | getBridges(graph); 33 | inTime.clear(); 34 | minFoundTime.clear(); 35 | return bridge; 36 | } 37 | }; 38 | int main(void){ 39 | vector>graph1; 40 | graph1.resize(5); // edges are 0 based 41 | graph1.at(0).push_back(1); 42 | graph1.at(1).push_back(0); 43 | graph1.at(2).push_back(1); 44 | graph1.at(1).push_back(2); 45 | graph1.at(2).push_back(3); 46 | graph1.at(3).push_back(2); 47 | Solution s; 48 | vector> bridge = s.findBridges(graph1); 49 | for (auto&itr : bridge) { 50 | cout << itr.first << ' ' << itr.second << '\n'; 51 | } 52 | cout << '\n'; 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Solution/Day-265.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vectorgetSalary(vector&v) { 7 | int n = v.size(); 8 | vector sol(n); 9 | sol[n-1] = 1; 10 | for (int i=n-2; i>=0; --i) { 11 | if (v[i] > v[i+1]) { 12 | sol[i] = sol[i+1]+1; 13 | } else { 14 | sol[i] = 1; 15 | } 16 | } 17 | int counter = 2; 18 | for (int i=1; i v[i-1]) { 20 | sol[i] = max(sol[i] , counter); 21 | ++counter; 22 | } else { 23 | counter = 1; 24 | } 25 | } 26 | return sol; 27 | } 28 | }; 29 | int main(void){ 30 | // vectoremp{10 , 40, 200, 1000, 60, 30}; 31 | // vectoremp{1}; 32 | vectoremp{10, 40, 200, 1000, 900, 800, 30}; 33 | Solution s; 34 | for (auto&itr:s.getSalary(emp)) { 35 | cout << itr << ' '; 36 | } 37 | cout << '\n'; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Solution/Day-269.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string pushDominoes(string dominoes) { 4 | const int &n = dominoes.size(); 5 | vectorv(dominoes.size() , INT_MAX); 6 | int counter{-1}; 7 | string temp = dominoes; 8 | for (int i=0; i=0; --i) { 20 | if (dominoes[i] == 'L') { 21 | counter = 0; 22 | } else if (dominoes[i] == 'R') { 23 | counter = -1; 24 | } else if (dominoes[i] == '.' && counter != -1) { 25 | if (v[i] > counter) { 26 | temp[i] = 'L'; 27 | counter++; 28 | } else if(v[i]==counter){ 29 | temp[i] = '.'; 30 | } 31 | } 32 | } 33 | return temp; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Solution/Day-272.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRollsToTarget(int d, int f, int target) { 4 | if (d*f > dp(d+10 , vector(target+10)); 6 | int mod = 1e9+7; 7 | for(int i=1; i<=min(target , f); ++i) { 8 | dp[1][i] = 1; 9 | } 10 | // dp[i][j] => number of ways to generate sum equal to j , with i dice 11 | for (int i=2; i<=d; ++i) { 12 | for (int j=1; j<=target; ++j) { 13 | for (int k=1; k<=f && j-k>=0; ++k) { 14 | dp[i][j] = (dp[i][j]+dp[i-1][j-k])%mod; 15 | } 16 | } 17 | } 18 | return dp[d][target]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Solution/Day-273.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int getFixedPoint(vector&v) { 5 | for (int i=0; i<(int)v.size(); ++i) { 6 | if ( i == v.at(i)) { 7 | return i; 8 | } 9 | } 10 | throw false; 11 | } 12 | int main(void){ 13 | vectorv1{-6,0,2,40}; 14 | vectorv2{1,5,7,8}; 15 | try{ 16 | cout << getFixedPoint(v1) << '\n'; 17 | cout << getFixedPoint(v2) << '\n'; 18 | } catch (const bool error) { 19 | cout << boolalpha << error << '\n'; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Solution/Day-282.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | // Function to check if the 4 | // Pythagorean triplet exists or not 5 | bool checkTriplet(int arr[], int n) { 6 | unordered_sets; 7 | for (int i=0; i 2 | using namespace std; 3 | using dcc= tuple; 4 | bool compare(dcc&a, dcc&b) { 5 | return get<0>(a) > get<0>(b); 6 | } 7 | double getSimilarity(set&a , set&b) { 8 | vectorinter(a.size()+b.size()); 9 | vector::iterator l; 10 | l = set_intersection(a.begin(), a.end(), b.begin(), b.end(), inter.begin()); 11 | double interE= (l - inter.begin()); 12 | l = set_union(a.begin(), a.end(), b.begin(), b.end(), inter.begin()); 13 | double uniE= (l - inter.begin()); 14 | return double(interE / uniE); 15 | } 16 | list> similarWebsites(multimapwebsite , int k) { 17 | list>ans; 18 | map>user; 19 | for (auto &itr: website) { 20 | user[itr.first].insert(itr.second); 21 | } 22 | vectorweb; 23 | for (auto& itr: user) { 24 | web.push_back(itr.first); 25 | } 26 | priority_queue, function>pq(compare); 27 | for (int i=0; i(pq.top()) < similarity) { 33 | pq.pop(); 34 | pq.push(make_tuple(similarity , web[i] , web[j])); 35 | } 36 | } 37 | } 38 | while(!pq.empty()) { 39 | ans.push_back(make_pair(get<1>(pq.top()), get<2>(pq.top()))); 40 | pq.pop(); 41 | } 42 | return ans; 43 | } 44 | int main(void){ 45 | multimapwebsite; 46 | website.insert({'a',1}); 47 | website.insert({'a',3}); 48 | website.insert({'a',5}); 49 | website.insert({'b',2}); 50 | website.insert({'b',6}); 51 | website.insert({'c',1}); 52 | website.insert({'c',2}); 53 | website.insert({'c',3}); 54 | website.insert({'c',4}); 55 | website.insert({'c',5}); 56 | website.insert({'d',4}); 57 | website.insert({'d',5}); 58 | website.insert({'d',6}); 59 | website.insert({'d',7}); 60 | website.insert({'e',1}); 61 | website.insert({'e',3}); 62 | website.insert({'e',5}); 63 | website.insert({'e',6}); 64 | list>l = similarWebsites(website , 3); 65 | for(auto&itr:l) { 66 | cout << itr.first << ' ' << itr.second << '\n'; 67 | } 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Solution/Day-288.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | if you try to simulate then at most 7 steps are possible to reach to kaprekar's constant. 3 | so a brute force solution should be accepted. I didn't find any pattern so preprocessing will 4 | be a stupid thing to do here. 5 | 6 | Numbers, which have all digits same can never reach, so make sure to apply a condition here that all digit 7 | shouldn't be same, maybe we can return -1, for numbers like 0000 , 1111, 2222, 3333, 4444 ... 9999. 8 | 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | class Solution{ 14 | static const int kaprekar_constant = 6174; 15 | public: 16 | int stepsForKaprekarConstant(int num) { 17 | int step{}; 18 | while (num != kaprekar_constant) { 19 | string temp = to_string(num); 20 | sort(temp.begin(), temp.end()); 21 | int num_small = atoi(temp.c_str()); 22 | reverse(temp.begin(), temp.end()); 23 | int num_big = atoi(temp.c_str()); 24 | num = num_big - num_small; 25 | step++; 26 | } 27 | return step; 28 | } 29 | }; 30 | signed main(void){ 31 | Solution sol; 32 | int num; cin >> num; 33 | cout << sol.stepsForKaprekarConstant(num) << '\n'; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Solution/Day-340.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define int int64_t 4 | double dist(pair&a , pair&b) { 5 | double x= a.first-b.first; 6 | double y= a.second-b.second; 7 | x*=x; 8 | y*=y; 9 | return sqrt(x+y); 10 | } 11 | vector> closestPoints(vector>&v) { 12 | vector>res; 13 | double min_dist = INT_MAX; 14 | const int &n = v.size(); 15 | for (int i=0; i> v = { 35 | {1, 1}, {-1, -1}, {3, 4}, {6, 1}, {-1, -6}, {-4, -3} 36 | }; 37 | vector> res = closestPoints(v); 38 | for (auto&itr: res) { 39 | cout << itr.first << ' ' << itr.second << '\n'; 40 | } 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Solution/Day-351.cpp: -------------------------------------------------------------------------------- 1 | This seems a Neural Language Processing problem. 2 | 3 | The general idea to solve this problem is, to create vector for each of the word , let's just say 4 | our attributes are : name , height , nature , color , age 5 | then these attributes have different value for a person , country , material. So by supervised or un-supervised 6 | learning we can prepare the model and predict the output. 7 | 8 | solving this problem is somewhat creating a whole new project, so let's just skip this one. 9 | -------------------------------------------------------------------------------- /Solution/Day-362.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vector strobogrammatic( int n ) { 7 | vectorret; 8 | if ( n & 1) { 9 | ret.push_back("1"); 10 | ret.push_back("0"); 11 | ret.push_back("8"); 12 | } else { 13 | ret.push_back(""); 14 | } 15 | for ( ; n>1; n-=2) { 16 | vectortemp; 17 | for (int i=0; i 3 ) { 20 | temp.push_back("0" + s + "0"); 21 | } 22 | temp.push_back("1" + s + "1"); 23 | temp.push_back("8" + s + "8"); 24 | temp.push_back("9" + s + "6"); 25 | temp.push_back("6" + s + "9"); 26 | } 27 | ret = temp; 28 | } 29 | return ret; 30 | } 31 | }; 32 | int main(void){ 33 | Solution s; 34 | int n; cin >> n; 35 | for (const auto &itr: s.strobogrammatic(n)) { 36 | cout << itr << ' '; 37 | } 38 | cout << '\n'; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Solution/Day-547.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaximumXOR(vector& nums) { 4 | unordered_set pref; 5 | int maxx=0 , mask=0; 6 | for (int i=31; i>=0; --i) { 7 | mask |= (1< 2 | using namespace std; 3 | 4 | int main(void){ 5 | srand(time(NULL)); 6 | long double pi , circle_point{} , square_point{}; 7 | for (int i=1; i<200'000; ++i) { 8 | double x = double(rand() % (i+1))/(double)i; 9 | double y = double(rand() % (i+1))/(double)i; 10 | double dist = x*x + y*y; 11 | if (dist <= 1) { 12 | ++circle_point; 13 | } 14 | ++square_point; 15 | cout << double (4) * circle_point / square_point << '\n'; 16 | } 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Solution/Day-559.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* mergeKLists(vector& lists) { 14 | ListNode *res_head , *res_end; 15 | res_head = res_end = nullptr; 16 | set> h; 17 | for (int i=0; ival , lists[i])); 20 | } 21 | } 22 | while (!h.empty()) { 23 | ListNode *temp = h.begin()->second; 24 | if ( res_head == nullptr) { 25 | res_head = temp; 26 | res_end = temp; 27 | } else { 28 | res_end->next = temp; 29 | res_end = res_end->next; 30 | } 31 | if (temp->next != nullptr) { 32 | h.insert(make_pair(temp->next->val , temp->next)); 33 | } 34 | h.erase(h.begin()); 35 | } 36 | return res_head; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Solution/Day-560.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | maph; 5 | vectorres; 6 | for(int i=0; i&nums , int left , int right) { 14 | if (left > right) { 15 | return nullptr; 16 | } 17 | int mid = left + (right - left) / 2; 18 | TreeNode* root = new TreeNode(nums.at(mid)); 19 | root -> left = BSTree(nums , left , mid - 1); 20 | root -> right= BSTree(nums , mid+1 , right); 21 | return root; 22 | } 23 | public: 24 | TreeNode* sortedArrayToBST(vector& nums) { 25 | return BSTree(nums , 0 , nums.size()-1); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Solution/Day-562.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | const size_t n= nums.size(); 5 | vectorans(n,1); 6 | int answer =1; 7 | for(size_t i=0;i=0;--i){ 16 | if(i!=0){ 17 | temp = nums[i]; 18 | nums[i] = ans[i-1]*answer; 19 | answer*=temp; 20 | }else{ 21 | nums[i] = answer; 22 | } 23 | } 24 | return nums; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Solution/Day-567.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | paircons(int a, int b){ 5 | return make_pair(a,b); 6 | } 7 | int car(pairp){ 8 | return p.first; 9 | } 10 | int cdr(pairp){ 11 | return p.second; 12 | } 13 | int main(void){ 14 | cout< sortedSquares(vector& nums) { 4 | vectorans(nums.size()); 5 | int left =0 , right = nums.size() -1 , current = nums.size()-1; 6 | while (current>=0) { 7 | int a = nums[left]* nums[left]; 8 | int b = nums[right]*nums[right]; 9 | if (a > b) { 10 | ans[current] = a; 11 | left++; 12 | } else { 13 | ans[current] = b; 14 | right--; 15 | } 16 | current--; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Solution/Day-574.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class bitArray{ 5 | private: 6 | vectorbaseArray; 7 | public: 8 | void init(const int &x) { 9 | baseArray.resize(x); 10 | } 11 | bool get(const int &i) const { 12 | return baseArray.at(i); 13 | } 14 | void set(const int &index , const int &value) { 15 | baseArray[index] = value; 16 | } 17 | friend ostream& operator<< (ostream&out ,const bitArray&a) { 18 | for(auto itr:a.baseArray) { 19 | out << itr; 20 | } 21 | return out; 22 | } 23 | }; 24 | 25 | int main(void){ 26 | bitArray b; 27 | b.init(100); 28 | b.set(10 , 1); 29 | cout << b << '\n'; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Solution/Day-577.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | map>fr; 5 | map>graph; 6 | unordered_setvisited; 7 | void dfs(string&node) { 8 | if(visited.find(node) != visited.end()) { 9 | return ; 10 | } 11 | visited.insert(node); 12 | for(auto&itr:graph[node]) { 13 | dfs(itr); 14 | } 15 | } 16 | public: 17 | bool chainPresent(vector&v) { 18 | fr.clear(); 19 | visited.clear(); 20 | bck.clear(); 21 | graph.clear(); 22 | for(auto&itr:v) { 23 | fr[itr[0]].push_back(itr); 24 | } 25 | for(auto&itr:fr) { 26 | for(auto&it:itr.second) { 27 | char lastchar = it[it.length()-1]; 28 | for(auto&i:fr[lastchar]) { 29 | graph[it].push_back(i); 30 | } 31 | } 32 | } 33 | dfs(v[0]); 34 | return visited.size() == v.size(); 35 | } 36 | }; 37 | signed main(void){ 38 | vectorv = {"chair", "height", "racket","touch", "tunic"}; 39 | //vectorv = {"aa" , "ba" , "ab" }; 40 | Solution s; 41 | if (s.chainPresent(v)) { 42 | cout << "Can be Chained" << '\n'; 43 | } else { 44 | cout << "Can't chained" << '\n'; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Solution/Day-578.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | mapc; 5 | mapd; 6 | for(int i=0; i<(int)s.length(); ++i) { 7 | if (c.find(s[i]) == c.end()) { 8 | c[s[i]] = t[i]; 9 | } else if (c[s[i]] != t[i]) { 10 | return false; 11 | } 12 | if (d.find(t[i]) == d.end()) { 13 | d[t[i]] = s[i]; 14 | } else if (d[t[i]] != s[i]) { 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Solution/Day-579.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reachNumber(int target) { 4 | // either by adding the values we are going to get the sum 5 | // or we need to make the (target-currentPos) even number , because 6 | // with even number we can make the displacement 0, let's say your difference 7 | // is 10 then you can move 5 step back and 5 step ahead and distance covered by you will be 10 8 | // but will it make any impact on your journey, NO; as you are at the same position where you started. 9 | // but in our case you overcome the extra 10 unit distance which is exceeding the target value; 10 | // you can't break a odd number in two equal weights , just try a few testcase you will get it. 11 | 12 | int current = 0 , moves = 0 , inc = 1; 13 | target = abs(target); 14 | while (true) { 15 | if(target == current) { 16 | break; 17 | } 18 | if (target < current && (target-current)%2==0) { 19 | break; 20 | } 21 | current+=inc++; 22 | ++moves; 23 | } 24 | 25 | return moves; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Solution/Day-580.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 | int minSum; 14 | void dfs(TreeNode* root , int currentSum) { 15 | if (currentSum > minSum) { 16 | return; 17 | } 18 | if (root == nullptr) { 19 | minSum = min(minSum , currentSum) ; 20 | return; 21 | } 22 | currentSum+=root->val; 23 | if (root -> left == nullptr && root -> right == nullptr) { 24 | minSum = min(minSum , currentSum) ; 25 | return ; 26 | } 27 | if (root->left) 28 | dfs(root -> left , currentSum); 29 | if (root->right) 30 | dfs(root -> right , currentSum); 31 | } 32 | public: 33 | int minimumSum(TreeNode* root) { 34 | minSum = numeric_limits::max(); 35 | dfs(root , 0); 36 | return minSum; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Solution/Day-582.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | vector stabbingPoints(vector>inter) { 6 | sort(inter.begin() , inter.end() , [](paira , pairb) { 7 | if (a.second == b.second) { 8 | return a.first < b.second; 9 | } else { 10 | return a.second < b.second; 11 | } 12 | }); 13 | vectorans; 14 | int last = numeric_limits::min(); 15 | for(int i=0; i> interval = {{1,4},{4,5},{7,9},{9,12}}; 26 | Solution s; 27 | vectorans = s.stabbingPoints(interval); 28 | for(const auto&itr:ans) { 29 | cout << itr << ' '; 30 | } 31 | cout << '\n'; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /cmake-build-debug/.cmake/api/v1/query/cache-v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/offamitkumar/Daily-Coding-Problem/e831e360bb1170162473a5e4ddf9b07d134826c1/cmake-build-debug/.cmake/api/v1/query/cache-v2 -------------------------------------------------------------------------------- /cmake-build-debug/.cmake/api/v1/query/cmakeFiles-v1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/offamitkumar/Daily-Coding-Problem/e831e360bb1170162473a5e4ddf9b07d134826c1/cmake-build-debug/.cmake/api/v1/query/cmakeFiles-v1 -------------------------------------------------------------------------------- /cmake-build-debug/.cmake/api/v1/query/codemodel-v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/offamitkumar/Daily-Coding-Problem/e831e360bb1170162473a5e4ddf9b07d134826c1/cmake-build-debug/.cmake/api/v1/query/codemodel-v2 -------------------------------------------------------------------------------- /cmake-build-debug/.cmake/api/v1/query/toolchains-v1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/offamitkumar/Daily-Coding-Problem/e831e360bb1170162473a5e4ddf9b07d134826c1/cmake-build-debug/.cmake/api/v1/query/toolchains-v1 -------------------------------------------------------------------------------- /cmake-build-debug/CMakeFiles/3.24.2/CMakeSystem.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_HOST_SYSTEM "Darwin-22.3.0") 2 | set(CMAKE_HOST_SYSTEM_NAME "Darwin") 3 | set(CMAKE_HOST_SYSTEM_VERSION "22.3.0") 4 | set(CMAKE_HOST_SYSTEM_PROCESSOR "arm64") 5 | 6 | 7 | 8 | set(CMAKE_SYSTEM "Darwin-22.3.0") 9 | set(CMAKE_SYSTEM_NAME "Darwin") 10 | set(CMAKE_SYSTEM_VERSION "22.3.0") 11 | set(CMAKE_SYSTEM_PROCESSOR "arm64") 12 | 13 | set(CMAKE_CROSSCOMPILING "FALSE") 14 | 15 | set(CMAKE_SYSTEM_LOADED 1) 16 | -------------------------------------------------------------------------------- /cmake-build-debug/CMakeFiles/clion-environment.txt: -------------------------------------------------------------------------------- 1 | ToolSet: 1.0 (local)Options: 2 | 3 | Options:-DCMAKE_MAKE_PROGRAM=/Applications/CLion.app/Contents/bin/ninja/mac/ninja --------------------------------------------------------------------------------