├── .gitignore ├── 09 Binary Tree ├── tree_input.cpp ├── level_order_tree_input.txt ├── .DS_Store ├── level_order_traversal.cpp ├── max_subset.cpp ├── root_2_leaft_paths.cpp ├── vertical_print.cpp ├── height_balanced.cpp ├── level_order_build.cpp ├── diameter.cpp └── node_at_kth_distance.cpp ├── 11 Heaps ├── cars_input.cpp ├── .DS_Store ├── sorting_using_heap.cpp ├── custom_compare.cpp ├── heaps_02_ropes.cpp ├── 04_running_median.cpp ├── 03_merge_k_sorted.cpp └── heaps_01_cabs.cpp ├── 12 Hashing ├── Counting Triangles │ ├── input_triangles.txt │ ├── .DS_Store │ └── triangles.cpp ├── Counting Rectangles │ ├── input_rect.txt │ ├── .DS_Store │ └── rectangle.cpp ├── .DS_Store ├── triplets_in_gp.cpp ├── anagrams_substrings.cpp └── quick-brown-fox.cpp ├── .DS_Store ├── 10 BST ├── .DS_Store ├── bst.cpp ├── closest_in_bst.cpp ├── inorder_succcessor.cpp └── bst_2_linked_list.cpp ├── 15 DP1 ├── .DS_Store ├── frog_jumps.cpp ├── lcs.cpp ├── rod_cutting.cpp └── lcs_bottom_up.cpp ├── 17 LRU ├── .DS_Store └── LRU.cpp ├── 13 Tries ├── .DS_Store ├── max_xor_trie ├── trie_introduction.cpp ├── suffix_trie.cpp ├── max_xor_trie.cpp └── little_cute_cat_trie.cpp ├── 02 Strings ├── .DS_Store ├── 05 strtok_use.cpp ├── strings.cpp ├── 07 check_subset.cpp ├── 00 stringfind.cpp ├── 03 tokenisation_sstream.cpp ├── 01 string_find_all.cpp ├── 02 space20.cpp ├── 08 sort subsequence.cpp ├── 04 mystrtok.cpp └── 06 sort_strings.cpp ├── 14 Graphs ├── .DS_Store ├── weighted_graph.cpp ├── 01_adj_list.cpp ├── 04_dfs.cpp ├── 03_bfs_.cpp ├── 02_adj_list.cpp ├── 02_adj_list_node.cpp ├── cycle_detection_undirected.cpp ├── cycle_detection_directed.cpp ├── largest_island.cpp ├── largest_island copy.cpp ├── dijkstra.cpp ├── 03_bfs_shortest_path.cpp ├── shortest_grid_path.cpp └── board-game.cpp ├── 05 Binary Search ├── .DS_Store ├── 02 rotated_search.cpp ├── 03 square_root.cpp ├── 05 min_pairs.cpp ├── 04 angry_birds.cpp ├── 01 Frequency Count.cpp ├── max_subarray_sliding_window_deque.cpp └── kpartition.cpp ├── 07 Linked Lists ├── .DS_Store └── linked_list.cpp ├── 01 Arrays & Vectors ├── .DS_Store ├── 02 2dvector.cpp ├── 01 vector.cpp ├── pairs 03.cpp ├── 07 rainwater-trap.cpp ├── fizzbuzz.cpp ├── 05 mountain.cpp ├── 06 longest_band.cpp ├── 04 triplets.cpp ├── 08 subarray_sort.cpp └── 09 min_swaps.cpp ├── 03 Sliding Window ├── .DS_Store ├── 01 housing.cpp ├── 02 unique_substring.cpp └── 03 string_window.cpp ├── 08 Stacks & Queue ├── .DS_Store ├── first_non_repeating_queue.cpp ├── redundant_paranthesis.cpp ├── max_in_window_k.cpp ├── balanced_paranthesis.cpp └── simplify_path.cpp ├── 06 Recursion Problems ├── .DS_Store ├── TODO permutations.cpp ├── ladder.cpp ├── generate_brackets.cpp ├── Subset Sum to X.cpp ├── keypad_input.cpp └── Sudoku.cpp └── 04 Sorting & Searching ├── .DS_Store ├── 05 smallest_string.cpp ├── 03 quicksort.cpp ├── 04 quickselect.cpp ├── 01 mergesort_vector.cpp ├── 06 sparse_search.cpp └── 02 inversion_count.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_STORE -------------------------------------------------------------------------------- /09 Binary Tree/tree_input.cpp: -------------------------------------------------------------------------------- 1 | 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 -------------------------------------------------------------------------------- /09 Binary Tree/level_order_tree_input.txt: -------------------------------------------------------------------------------- 1 | 1 2 3 4 5 -1 6 -1-1 7 -1 -1 -1 -1 -1 2 | 3 | -------------------------------------------------------------------------------- /11 Heaps/cars_input.cpp: -------------------------------------------------------------------------------- 1 | 5 3 2 | C1 1 1 3 | C2 2 1 4 | C3 3 2 5 | C4 0 1 6 | C5 2 3 7 | 8 | -------------------------------------------------------------------------------- /12 Hashing/Counting Triangles/input_triangles.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 1 2 3 | 2 1 4 | 2 2 5 | 2 3 6 | 3 2 7 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/.DS_Store -------------------------------------------------------------------------------- /10 BST/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/10 BST/.DS_Store -------------------------------------------------------------------------------- /12 Hashing/Counting Rectangles/input_rect.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 4 1 3 | 4 0 4 | 0 0 5 | 0 1 6 | 1 1 7 | 1 0 8 | 2 0 9 | 2 1 10 | -------------------------------------------------------------------------------- /15 DP1/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/15 DP1/.DS_Store -------------------------------------------------------------------------------- /17 LRU/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/17 LRU/.DS_Store -------------------------------------------------------------------------------- /11 Heaps/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/11 Heaps/.DS_Store -------------------------------------------------------------------------------- /13 Tries/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/13 Tries/.DS_Store -------------------------------------------------------------------------------- /02 Strings/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/02 Strings/.DS_Store -------------------------------------------------------------------------------- /12 Hashing/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/12 Hashing/.DS_Store -------------------------------------------------------------------------------- /13 Tries/max_xor_trie: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/13 Tries/max_xor_trie -------------------------------------------------------------------------------- /14 Graphs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/14 Graphs/.DS_Store -------------------------------------------------------------------------------- /09 Binary Tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/09 Binary Tree/.DS_Store -------------------------------------------------------------------------------- /05 Binary Search/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/05 Binary Search/.DS_Store -------------------------------------------------------------------------------- /07 Linked Lists/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/07 Linked Lists/.DS_Store -------------------------------------------------------------------------------- /01 Arrays & Vectors/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/01 Arrays & Vectors/.DS_Store -------------------------------------------------------------------------------- /03 Sliding Window/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/03 Sliding Window/.DS_Store -------------------------------------------------------------------------------- /08 Stacks & Queue/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/08 Stacks & Queue/.DS_Store -------------------------------------------------------------------------------- /06 Recursion Problems/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/06 Recursion Problems/.DS_Store -------------------------------------------------------------------------------- /04 Sorting & Searching/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/04 Sorting & Searching/.DS_Store -------------------------------------------------------------------------------- /12 Hashing/Counting Triangles/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/12 Hashing/Counting Triangles/.DS_Store -------------------------------------------------------------------------------- /12 Hashing/Counting Rectangles/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/data-structures-algorithms-level-up-bootcamp/HEAD/12 Hashing/Counting Rectangles/.DS_Store -------------------------------------------------------------------------------- /06 Recursion Problems/TODO permutations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void permute(string a,int i){ 6 | 7 | 8 | } 9 | 10 | 11 | int main(){ 12 | 13 | string s; 14 | cin>>s; 15 | permute(s); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /15 DP1/frog_jumps.cpp: -------------------------------------------------------------------------------- 1 | CODING INTERVIEW ~ 20 mins 2 | 3 | FROG JUMPS 4 | ============ 5 | Given an array containing integers, and there is a frog 6 | sitting at the starting of the array. Each integer represents the 7 | maximum number of steps frog can take in the array. 8 | Write a function which can calculates the minimum jumps 9 | required by frog to reach the end of the array. 10 | 11 | 12 | -------------------------------------------------------------------------------- /06 Recursion Problems/ladder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // 5 | int countWays(int n){ 6 | //Base 7 | if(n<0){ 8 | return 0; 9 | } 10 | if(n==0){ 11 | return 1; 12 | } 13 | 14 | //Recursive 15 | return countWays(n-1) + countWays(n-2) + countWays(n-3); 16 | 17 | } 18 | 19 | 20 | int main(){ 21 | int n; 22 | cin>>n; 23 | cout < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | int main(){ 8 | 9 | char input[1000]; 10 | cin.getline(input,1000); 11 | 12 | //strtok() 13 | char *token = strtok(input," "); 14 | 15 | 16 | while(token!=NULL){ 17 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | bool compare(string x,string y){ 7 | return x + y < y + x; 8 | } 9 | 10 | 11 | int main() { 12 | string arr[] = {"a","ab","aba"}; 13 | int n = 3; 14 | 15 | sort(arr,arr+n,compare); 16 | 17 | for(auto s : arr){ 18 | cout < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | int main(){ 8 | 9 | //char s[1000] = {'1','a','b','c','\0'}; 10 | 11 | string s; //"hello world"; //Dynamic Array 12 | 13 | int n=5; 14 | vector sarr; 15 | string temp; 16 | 17 | while(n--){ 18 | getline(cin,temp); 19 | sarr.push_back(temp); 20 | } 21 | 22 | for(string x: sarr){ 23 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main(){ 7 | 8 | int arr[] = {10,15,20,13,6,90}; 9 | int n = sizeof(arr)/sizeof(int); 10 | 11 | priority_queue , greater > heap; 12 | 13 | for(int x : arr){ 14 | heap.push(x); 15 | } 16 | 17 | while(!heap.empty()){ 18 | cout << heap.top() < 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main(){ 7 | //2D Vector 8 | vector< vector > arr = { 9 | {1,2,3}, 10 | {4,5,6}, 11 | {7,8,9,10}, 12 | {11,12}}; 13 | 14 | 15 | arr[0][0] += 10; //update 16 | 17 | for(int i=0;i< arr.size(); i++){ 18 | 19 | for(int number : arr[i]){ 20 | cout << number <<","; 21 | } 22 | cout < 2 | #include 3 | using namespace std; 4 | 5 | bool isSubset(string s1,string s2){ 6 | 7 | int i = s1.length() - 1; 8 | int j = s2.length()-1; 9 | 10 | while(i>=0 and j>=0){ 11 | if(s2[j]==s1[i]){ 12 | i--; 13 | j--; 14 | } 15 | else{ 16 | i--; 17 | } 18 | } 19 | if(j==-1){ 20 | return true; 21 | } 22 | return false; 23 | 24 | } 25 | 26 | 27 | int main() { 28 | string s1,s2; 29 | cin>>s1>>s2; 30 | cout< 2 | #include 3 | using namespace std; 4 | 5 | class Compare{ 6 | public: 7 | bool operator()(int a,int b){ 8 | return a < b; 9 | } 10 | }; 11 | 12 | 13 | int main(){ 14 | 15 | int arr[] = {10,15,20,13,6,90}; 16 | int n = sizeof(arr)/sizeof(int); 17 | 18 | priority_queue , Compare > heap; 19 | 20 | for(int x : arr){ 21 | heap.push(x); 22 | } 23 | 24 | while(!heap.empty()){ 25 | cout << heap.top() < 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main(){ 7 | 8 | string paragraph = "We are learning about STL strings. STL string class is quite powerful"; 9 | 10 | string word; 11 | getline(cin,word); 12 | 13 | //find function 14 | int index = paragraph.find(word); 15 | 16 | if(index!=-1){ 17 | cout <<"first occ" < 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | //Demo Vector 7 | //vector arr = //{1,2,10,12,15}; 8 | 9 | //Fill Constructor 10 | vector arr(10,7); 11 | 12 | //Fill Constructor 13 | vector visited(100,0); 14 | 15 | //Pop_back 16 | arr.pop_back(); 17 | // Push_Back O(1) 18 | arr.push_back(16); 19 | 20 | //Print all the elements 21 | for(int x : arr){ 22 | cout << x <<","; 23 | } 24 | 25 | /*for(int i=0;i< arr.size(); i++){ 26 | cout << arr[i] < 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | int main(){ 9 | 10 | string input; 11 | getline(cin,input); 12 | //"this is a sunny day" 13 | 14 | //create a string stream object 15 | stringstream ss(input); 16 | 17 | // >> and << operators 18 | string token; 19 | vector tokens; 20 | while(getline(ss,token,' ')){ 21 | tokens.push_back(token); 22 | } 23 | 24 | //print all all tokens 25 | for(auto token:tokens){ 26 | cout< 2 | using namespace std; 3 | 4 | 5 | void generateBrackets(string output,int n,int open,int close,int i){ 6 | //base case 7 | if(i==2*n){ 8 | cout<>n; 29 | generateBrackets(output,n,0,0,0); 30 | 31 | return 0; 32 | 33 | } -------------------------------------------------------------------------------- /06 Recursion Problems/Subset Sum to X.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | int countSubsets(vector arr,int n,int i,int X){ 9 | 10 | //base case 11 | if(i==n){ 12 | if(X==0){ 13 | return 1; 14 | } 15 | return 0; 16 | } 17 | 18 | //recusive case 19 | int inc = countSubsets(arr,n,i+1,X - arr[i]); 20 | int exc = countSubsets(arr,n,i+1,X); 21 | return inc + exc; 22 | } 23 | 24 | int main(){ 25 | vector arr{1,2,3,4,5}; 26 | int X = 10; 27 | 28 | cout << countSubsets(arr,arr.size(),0,X)< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | 8 | int V; 9 | list > *l; 10 | 11 | public: 12 | Graph(int v){ 13 | V = v; 14 | l = new list >[V]; 15 | } 16 | 17 | void addEdge(int u,int v,int wt,bool undir = true){ 18 | 19 | l[u].push_back({wt,v}); 20 | if(undir){ 21 | l[v].push_back({wt,u}); 22 | } 23 | } 24 | 25 | }; 26 | 27 | int main(){ 28 | 29 | Graph g(5); 30 | g.addEdge(0,1,1); 31 | g.addEdge(1,2,2); 32 | g.addEdge(0,2,4); 33 | g.addEdge(0,3,7); 34 | g.addEdge(3,2,2); 35 | g.addEdge(3,4,3); 36 | 37 | 38 | 39 | 40 | } -------------------------------------------------------------------------------- /02 Strings/01 string_find_all.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector stringSearch(string big,string small){ 7 | 8 | vector result; 9 | int index = big.find(small); 10 | while(index!=-1){ 11 | result.push_back(index); 12 | index = big.find(small,index+1); 13 | } 14 | 15 | return result; 16 | } 17 | 18 | int main(){ 19 | 20 | string paragraph = "We are learning about STL strings. STL string class is quite powerful"; 21 | 22 | string word = "STL"; 23 | 24 | vector result = stringSearch(paragraph,word); 25 | for(int x:result){ 26 | cout < 2 | #include 3 | using namespace std; 4 | 5 | int join_ropes(int ropes[], int n) { 6 | 7 | //min heap 8 | priority_queue , greater > pq(ropes,ropes+n); 9 | 10 | 11 | //logic 12 | int cost = 0; 13 | 14 | while(pq.size() > 1){ 15 | 16 | int A = pq.top(); 17 | pq.pop(); 18 | 19 | int B = pq.top(); 20 | pq.pop(); 21 | 22 | 23 | int new_rope = (A+B); 24 | cost += new_rope; 25 | pq.push(new_rope); 26 | 27 | } 28 | 29 | return cost; 30 | 31 | } 32 | 33 | int main() { 34 | int ropes[] = {4, 3, 2, 6}; 35 | int n = 4; 36 | 37 | cout << join_ropes(ropes, n) << endl; 38 | 39 | 40 | 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /01 Arrays & Vectors/pairs 03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector pairSum(vector arr,int Sum){ 7 | //Logic 8 | unordered_set s; 9 | vector result; 10 | 11 | for(int i=0;i arr{10, 5, 2 , 3, -6, 9 , 11}; 28 | int S = 4; 29 | 30 | auto p = pairSum(arr,S); 31 | if(p.size()==0){ 32 | cout<<"No such pair"; 33 | } 34 | else{ 35 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | int trappedWater(vector heights) { 7 | 8 | //Complete 9 | int n = heights.size(); 10 | if(n<=2){ 11 | return 0; 12 | } 13 | 14 | //Left Max, Right Max 15 | vector left(n,0), right(n,0); 16 | left[0] = heights[0]; 17 | right[n-1] = heights[n-1]; 18 | 19 | for(int i=1;i water = {0,1,0,2,1,0,1,3,2,1,2,1}; 35 | cout< 2 | #include 3 | using namespace std; 4 | 5 | string keypad[] = {"","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"}; 6 | 7 | 8 | void printKeypadOutput(string input,string output,int i=0){ 9 | 10 | if(input[i]=='\0'){ 11 | cout<>input; 36 | 37 | string output; 38 | printKeypadOutput(input,output); 39 | 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /01 Arrays & Vectors/fizzbuzz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //Complete this method, don't write main 7 | vector fizzbuzz(int n){ 8 | 9 | vector result; 10 | for(int i=1;i<=n;i++){ 11 | if((i%15)==0){ 12 | result.push_back("FizzBuzz"); 13 | } 14 | else if(i%5 == 0){ 15 | result.push_back("Buzz"); 16 | } 17 | else if(i%3 == 0){ 18 | result.push_back("Fizz"); 19 | } 20 | else{ 21 | result.push_back(to_string(i)); 22 | } 23 | 24 | } 25 | 26 | return result; 27 | 28 | } 29 | 30 | 31 | int main(){ 32 | 33 | vector output = fizzbuzz(10); 34 | for(string x : output){ 35 | cout << x <<","; 36 | } 37 | 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /04 Sorting & Searching/03 quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int partition(vector &a,int s,int e){ 7 | 8 | int pivot = a[e]; 9 | int i = s - 1; 10 | 11 | for(int j=s;j &a, int s,int e){ 24 | //Base Case 25 | if(s>=e){ 26 | return; 27 | } 28 | //Rec Case 29 | int p = partition(a,s,e); 30 | quicksort(a,s,p-1); 31 | quicksort(a,p+1,e); 32 | } 33 | 34 | 35 | int main(){ 36 | vector arr{10,5,2,0,7,6,4}; 37 | cout<< arr.size() < 2 | #include 3 | using namespace std; 4 | 5 | 6 | int highest_mountain(vector a){ 7 | int n = a.size(); 8 | 9 | int largest = 0; 10 | 11 | for(int i=1;i<=n-2;){ 12 | 13 | //check a[i] is peak or not 14 | if(a[i]>a[i-1] and a[i]>a[i+1]){ 15 | //do some work 16 | int cnt = 1; 17 | int j = i; 18 | //cnt backwards (left) 19 | while(j>=1 and a[j]>a[j-1]){ 20 | j--; 21 | cnt++; 22 | } 23 | //cnt forwards (right) 24 | while(i<=n-2 and a[i]>a[i+1]){ 25 | i++; 26 | cnt++; 27 | } 28 | largest = max(largest,cnt); 29 | 30 | } 31 | else{ 32 | i++; 33 | } 34 | } 35 | return largest; 36 | 37 | } 38 | 39 | int main(){ 40 | 41 | vector arr{5,6,1,2,3,4,5,4,3,2,0,1,2,3,-2,4}; 42 | 43 | cout<< highest_mountain(arr)< 2 | #include 3 | using namespace std; 4 | 5 | void replace_space(char *str){ 6 | 7 | //1. calc spaces 8 | int spaces = 0; 9 | for(int i=0;str[i]!='\0';i++){ 10 | if(str[i]==' '){ 11 | spaces += 1; 12 | } 13 | } 14 | 15 | int idx = strlen(str) + 2*spaces; 16 | str[idx] = '\0'; 17 | 18 | for(int i= strlen(str)-1;i>=0;i--){ 19 | if(str[i]==' '){ 20 | str[idx-1] = '0'; 21 | str[idx-2] = '2'; 22 | str[idx-3] = '%'; 23 | idx = idx - 3; 24 | } 25 | else{ 26 | str[idx-1] = str[i]; 27 | idx--; 28 | } 29 | } 30 | 31 | } 32 | 33 | 34 | int main() { 35 | char input[10000]; 36 | cin.getline(input,1000); 37 | replace_space(input); 38 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int rotated_search(vector a,int key) { 6 | int n = a.size(); 7 | 8 | //Logic 9 | int s = 0; 10 | int e = n - 1; 11 | 12 | while(s<=e){ 13 | int mid = (s+e)/2; 14 | 15 | if(a[mid]==key){ 16 | return mid; 17 | } 18 | 19 | //2 cases 20 | if(a[s]<=a[mid]){ 21 | //left 22 | if(key>=a[s] and key<=a[mid]){ 23 | e = mid - 1; 24 | } 25 | else{ 26 | s = mid + 1; 27 | } 28 | 29 | } 30 | else{ 31 | //right 32 | 33 | if(key>=a[mid] and key<=a[e]){ 34 | s = mid + 1; 35 | } 36 | else{ 37 | e = mid - 1; 38 | } 39 | 40 | } 41 | 42 | } 43 | return -1; 44 | 45 | } 46 | 47 | 48 | 49 | int main() { 50 | 51 | 52 | vector a{4,5,6,7,0,1,2,3}; 53 | int key; 54 | cin>>key; 55 | cout<< rotated_search(a,key) < 2 | #include 3 | using namespace std; 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | void play_song(int song_id){ 10 | 11 | if(song_id==0){ 12 | return; 13 | } 14 | 15 | 16 | } 17 | 18 | 19 | int main() { 20 | 21 | //First Non-Repeating character in the running stream 22 | queue q; 23 | int freq[27] = {0}; //a-z 24 | 25 | char ch; 26 | cin >> ch; 27 | 28 | while(ch!='.'){ 29 | 30 | //letter 31 | q.push(ch); 32 | freq[ch - 'a']++; 33 | 34 | //query -> remove all chars from front of queue till you get a char with freq 1 35 | while(!q.empty()){ 36 | int idx = q.front() - 'a'; 37 | if(freq[idx]>1){ 38 | q.pop(); 39 | } 40 | else{ 41 | cout<< q.front() <>ch; 50 | } 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /14 Graphs/01_adj_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | class Graph{ 7 | 8 | int V; 9 | list *l; 10 | 11 | public: 12 | Graph(int v){ 13 | V = v; 14 | l = new list[V]; 15 | } 16 | 17 | void addEdge(int i,int j,bool undir=true){ 18 | l[i].push_back(j); 19 | if(undir){ 20 | l[j].push_back(i); 21 | } 22 | } 23 | 24 | void printAdjList(){ 25 | //Iterate over all the rows 26 | for(int i=0;i"; 28 | //every element of ith linked list 29 | for(auto node:l[i]){ 30 | cout << node <<","; 31 | } 32 | cout < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int largestBand(vector arr){ 7 | int n = arr.size(); 8 | unordered_set s; 9 | 10 | //Data inside a set 11 | for(int x : arr){ 12 | s.insert(x); 13 | } 14 | 15 | //Iterate over the arr 16 | int largestLen = 1; 17 | 18 | for(auto element : s){ 19 | int parent = element - 1; 20 | 21 | if(s.find(parent)==s.end()){ 22 | //find entire band / chain starting from element 23 | int next_no = element + 1; 24 | int cnt = 1; 25 | 26 | while(s.find(next_no)!=s.end()){ 27 | next_no++; 28 | cnt++; 29 | } 30 | 31 | if(cnt>largestLen){ 32 | largestLen = cnt; 33 | } 34 | } 35 | } 36 | 37 | 38 | return largestLen; 39 | } 40 | 41 | 42 | 43 | int main(){ 44 | 45 | vector arr{1, 9, 3, 0, 18, 5, 2, 10, 7, 12, 6}; 46 | cout << largestBand(arr)< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | //sorted subsequences 7 | void subsequence(string s,string o, vector &v){ 8 | //base case 9 | if(s.size()==0){ 10 | v.push_back(o); 11 | return; 12 | } 13 | 14 | //rec case 15 | char ch = s[0]; 16 | string reduced_input = s.substr(1); 17 | 18 | //includes 19 | subsequence(reduced_input, o + ch, v); 20 | 21 | //excludes 22 | subsequence(reduced_input, o , v); 23 | } 24 | bool compare(string s1,string s2){ 25 | if(s1.length()==s2.length()){ 26 | return s1 < s2; 27 | } 28 | return s1.length() < s2.length(); 29 | 30 | } 31 | 32 | int main(){ 33 | 34 | string s; 35 | cin>>s; 36 | vector v; 37 | string output = ""; 38 | subsequence(s,output,v); 39 | 40 | sort(v.begin(),v.end(),compare); 41 | 42 | for(auto s : v){ 43 | cout<< s << ","; 44 | } 45 | 46 | 47 | return 0; 48 | 49 | } -------------------------------------------------------------------------------- /04 Sorting & Searching/04 quickselect.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int partition(vector &a,int s,int e){ 7 | 8 | int pivot = a[e]; 9 | int i = s - 1; 10 | 11 | for(int j=s;j a, int s,int e,int k){ 24 | 25 | //assuming that k will be inside the array 26 | 27 | int p = partition(a,s,e); 28 | if(p==k){ 29 | return a[p]; 30 | } 31 | else if(k arr{10,5,2,0,7,6,4}; 43 | //cout<< arr.size() <>k; 47 | 48 | cout < 2 | #include 3 | using namespace std; 4 | 5 | 6 | int lcs(string s1,string s2,int i,int j,vector > &dp){ 7 | //base case 8 | if(i==s1.length() or j==s2.length()){ 9 | return 0; 10 | } 11 | //check if a state is already computed 12 | if(dp[i][j]!=-1){ 13 | return dp[i][j]; 14 | } 15 | 16 | //rec case 17 | if(s1[i]==s2[i]){ 18 | return dp[i][j] = 1 + lcs(s1,s2,i+1,j+1,dp); 19 | } 20 | 21 | int op1 = lcs(s1,s2,i+1,j,dp); 22 | int op2 = lcs(s1,s2,i,j+1,dp); 23 | return dp[i][j] = max(op1,op2); 24 | } 25 | 26 | int main(){ 27 | 28 | string s1 = "ABCD"; 29 | string s2 = "ABEDG"; 30 | 31 | int n1 = s1.length(); 32 | int n2 = s2.length(); 33 | 34 | vector > dp(n1+1, vector(n2+1,-1)); //n1 X n2 35 | 36 | cout<< lcs(s1,s2,0,0,dp) < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | bool checkRedundant(string str){ 7 | //Complete 8 | stack s; 9 | 10 | for(char ch : str){ 11 | if(ch!=')'){ 12 | s.push(ch); // a,b, + , - , ( .... 13 | } 14 | else{ 15 | // ')' 16 | bool operator_found = false; 17 | 18 | while(!s.empty() and s.top()!='('){ 19 | char top = s.top(); 20 | if(top=='+' or top=='-' or top=='*' or top=='/'){ 21 | operator_found = true; 22 | } 23 | s.pop(); 24 | } 25 | s.pop(); //pop the opening bracked after the loop if over 26 | 27 | if(operator_found == false){ 28 | return true; 29 | } 30 | } 31 | } 32 | return false; 33 | } 34 | 35 | 36 | int main() { 37 | string str = "((a+b)+c) + ((d*e))"; 38 | if(checkRedundant(str)){ 39 | cout<<"Contains Redundant Parenthesis"; 40 | } 41 | else{ 42 | cout<<"r"; 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /05 Binary Search/03 square_root.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | float square_root(int N,int P){ 5 | int s = 0; 6 | int e = N ; 7 | float ans = 0; 8 | 9 | //Binary Search (Search Space 0....N) 10 | while(s<=e){ 11 | int mid = (s+e)/2; 12 | if(mid*mid==N){ 13 | return mid; 14 | } 15 | else if(mid*mid < N){ 16 | ans = mid; 17 | s = mid + 1; 18 | } 19 | 20 | else{ 21 | e = mid - 1; 22 | } 23 | 24 | } 25 | 26 | //Linear Search for each place (for floating part) 27 | float inc = 0.1; 28 | 29 | for(int place=1;place<=P;place++){ 30 | 31 | //do linear search 32 | while(ans*ans <=N){ 33 | ans += inc; 34 | } 35 | 36 | //take one step back 37 | ans = ans - inc; 38 | inc = inc/10.0; 39 | } 40 | 41 | 42 | return ans; 43 | } 44 | 45 | 46 | 47 | int main(){ 48 | 49 | int n,p; 50 | cin>>n>>p; 51 | 52 | cout< 2 | using namespace std; 3 | 4 | 5 | void housing(int *arr,int n,int k){ 6 | 7 | int i=0; 8 | int j= 0; 9 | int cs = 0; 10 | 11 | while(j sum and i k and i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void min_pair(vector a1,vector a2){ 8 | 9 | 10 | //Sort the array 11 | sort(a2.begin(),a2.end()); 12 | 13 | int p1,p2; 14 | int diff = INT_MAX; 15 | 16 | //iteratte over 1 array and look for closes elements in the second array 17 | for(int x : a1){ 18 | auto lb = lower_bound(a2.begin(),a2.end(),x) - a2.begin(); 19 | 20 | //left 21 | if(lb>=1 and x - a2[lb-1] < diff){ 22 | diff = x - a2[lb-1]; 23 | p2 = x; 24 | p1 = a2[lb-1]; 25 | } 26 | //greater / right 27 | if(lb!=a2.size() and a2[lb]-x < diff){ 28 | diff = a2[lb] - x; 29 | p1 = x; 30 | p2 = a2[lb]; 31 | } 32 | 33 | } 34 | cout<<"Min Pair "< a1 = {-1, 5, 10, 20, 3}; 43 | vector a2 = {26, 134, 135, 15, 17}; 44 | min_pair(a1,a2); 45 | 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /14 Graphs/04_dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void dfsHelper(int node,bool *visited){ 25 | visited[node] = true; 26 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | bool canPlaceBirds(int B,int N,vector nests,int sep){ 8 | 9 | int birds = 1; 10 | int location = nests[0]; 11 | 12 | for(int i=1; i<=N-1; i++){ 13 | int current_location = nests[i]; 14 | if(current_location - location >= sep){ 15 | birds++; 16 | location = current_location; 17 | 18 | if(birds==B){ 19 | return true; 20 | } 21 | } 22 | } 23 | return false; 24 | 25 | } 26 | 27 | 28 | int main(){ 29 | int B = 3; 30 | vector nests{1,2,4,8,9}; 31 | //sorting 32 | sort(nests.begin(),nests.end()); 33 | int N = nests.size(); 34 | 35 | //Binary Search 36 | int s = 0; 37 | int e = nests[N-1] - nests[0]; 38 | int ans = -1; 39 | 40 | while(s<=e){ 41 | int mid = (s+e)/2; 42 | 43 | bool canPlace = canPlaceBirds(B,N,nests,mid); 44 | if(canPlace){ 45 | ans = mid; 46 | s = mid + 1; 47 | } 48 | else{ 49 | e = mid - 1; 50 | } 51 | } 52 | 53 | cout << ans < 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int key; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int key){ 12 | this->key = key; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | Node* insert(Node * root, int key){ 18 | if(root==NULL){ 19 | return new Node(key); 20 | } 21 | 22 | //rec case 23 | if(key < root->key){ 24 | root->left = insert(root->left,key); 25 | } 26 | else{ 27 | root->right = insert(root->right,key); 28 | } 29 | return root; 30 | 31 | } 32 | 33 | bool search(Node * root, int key){ 34 | //Homework 35 | 36 | 37 | 38 | } 39 | 40 | void printInOrder(Node *root){ 41 | if(root==NULL){ 42 | return; 43 | } 44 | //left, root, right 45 | printInOrder(root->left); 46 | cout << root-> key <<" ,"; 47 | printInOrder(root->right); 48 | } 49 | 50 | 51 | int main(){ 52 | 53 | Node * root = NULL; 54 | int arr[] = {8,3,10,1,6,14,4,7,13}; 55 | 56 | for(int x : arr){ 57 | root = insert(root,x); 58 | } 59 | printInOrder(root); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /12 Hashing/triplets_in_gp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int count_triplets(vector arr,int r){ 7 | 8 | int n = arr.size(); 9 | unordered_map right,left; 10 | 11 | //Init the Right Map with freq, Left map = 0 12 | for(auto x : arr){ 13 | right[x]++; 14 | left[x] = 0; 15 | } 16 | 17 | //compute by iterating left to right 18 | int ans = 0; 19 | for(int i = 0; i < n; i++){ 20 | 21 | right[arr[i]]--; 22 | 23 | if(arr[i]%r==0){ 24 | long b = arr[i]; 25 | long a = arr[i]/r; 26 | long c = arr[i]*r; 27 | 28 | ans += left[a] * right[c]; 29 | } 30 | 31 | left[arr[i]]++; 32 | 33 | } 34 | return ans; 35 | 36 | } 37 | 38 | int main() { 39 | 40 | int n,r; 41 | cin>>n>>r; 42 | vector arr(n,0); 43 | 44 | for(int i=0;i>arr[i]; 46 | } 47 | 48 | cout< 2 | using namespace std; 3 | 4 | 5 | //Recursive Solution 6 | int max_profit(int prices[],int n){ 7 | //base case 8 | if(n<=0){ 9 | return 0; 10 | } 11 | 12 | //rec case 13 | int ans = INT_MIN; 14 | 15 | for(int i=0;i < n;i++){ 16 | int cut = i + 1; 17 | 18 | int current_ans = prices[i] + max_profit(prices,n - cut); 19 | ans = max(ans,current_ans); 20 | 21 | } 22 | return ans; 23 | } 24 | 25 | 26 | 27 | //bottom up solution 28 | int max_profit_dp(int *prices,int n){ 29 | 30 | int dp[n+1]; 31 | dp[0] = 0; 32 | 33 | 34 | for(int len=1;len<=n;len++){ 35 | 36 | int ans = INT_MIN; 37 | for(int i=0;i 2 | using namespace std; 3 | 4 | char *mystrtok(char *str,char delim){ 5 | 6 | static char *input = NULL; 7 | 8 | if(str!=NULL){ 9 | input = str; 10 | } 11 | if(input==NULL){ 12 | return NULL; 13 | } 14 | //static 15 | char *token = new char[strlen(input)+1]; 16 | int i=0; 17 | 18 | for( ; input[i]!='\0';i++){ 19 | if(input[i]!=delim){ 20 | token[i] = input[i]; 21 | } 22 | else 23 | { 24 | token[i] = '\0'; 25 | input = input + i + 1; 26 | return token; 27 | } 28 | } 29 | 30 | //out of the loop 31 | token[i] = '\0'; 32 | //reset the input as nULL 33 | input = NULL; 34 | return token; 35 | } 36 | 37 | 38 | int main(){ 39 | 40 | char s[1000]; 41 | cin.getline(s,1000); 42 | 43 | //strtok() 44 | char *token = mystrtok(s,' '); 45 | 46 | 47 | while(token!=NULL){ 48 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int count_triangles(vector > &points){ 7 | 8 | unordered_map freq_x; 9 | unordered_map freq_y; 10 | 11 | //Count the freq by iterating over all the points 12 | for(auto p:points){ 13 | int x = p.first; 14 | int y = p.second; 15 | freq_x[x]++; 16 | freq_y[y]++; 17 | } 18 | 19 | 20 | //count 21 | int count = 0; 22 | for(auto p:points){ 23 | int x = p.first; 24 | int y = p.second; 25 | 26 | int fx = freq_x[x]; 27 | int fy = freq_y[y]; 28 | 29 | count += (fx-1)*(fy-1); 30 | } 31 | return count; 32 | 33 | } 34 | 35 | 36 | int main() { 37 | 38 | int N; 39 | cin>>N; 40 | 41 | vector > points; 42 | 43 | for(int i=0;i>x>>y; 46 | points.push_back({x,y}); 47 | } 48 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string unique_substring(string str){ 7 | 8 | int i = 0; 9 | int j = 0; 10 | 11 | int window_len = 0; 12 | int max_window_len = 0; 13 | int start_window = -1; 14 | 15 | 16 | unordered_map m; 17 | 18 | 19 | while(j < str.length()){ 20 | 21 | char ch = str[j]; 22 | 23 | //if it is inside hashmap & its idx >= start of the current window 24 | if(m.count(ch) and m[ch]>=i){ 25 | //later on.. 26 | i = m[ch] + 1; 27 | window_len = j - i; //updated remaining window len excluding current char 28 | } 29 | 30 | //update the last occ 31 | m[ch] = j; 32 | window_len++; 33 | j++; 34 | 35 | //update max_window_len at every step 36 | if(window_len > max_window_len){ 37 | max_window_len = window_len; 38 | start_window = i; 39 | } 40 | } 41 | return str.substr(start_window,max_window_len); 42 | } 43 | 44 | 45 | int main(){ 46 | 47 | string input; 48 | cin>>input; 49 | 50 | cout << unique_substring(input); 51 | 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /01 Arrays & Vectors/04 triplets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector > triplets(vector arr,int targetSum){ 7 | //Logic 8 | int n = arr.size(); 9 | sort(arr.begin(),arr.end()); 10 | vector > result; 11 | 12 | // Pick every a[i], pair sum for remaining part 13 | for(int i=0; i<=n-3;i++){ 14 | 15 | int j = i + 1; 16 | int k = n - 1; 17 | 18 | //two pointer approach 19 | while(j < k){ 20 | int current_sum = arr[i]; 21 | current_sum += arr[j]; 22 | current_sum += arr[k]; 23 | 24 | if(current_sum==targetSum){ 25 | result.push_back({arr[i],arr[j],arr[k]}); 26 | j++; 27 | k--; 28 | } 29 | else if(current_sum > targetSum){ 30 | k--; 31 | } 32 | else{ 33 | j++; 34 | } 35 | } 36 | 37 | } 38 | return result; 39 | 40 | } 41 | 42 | int main(){ 43 | 44 | vector arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 15}; 45 | int S = 18; 46 | 47 | auto result = triplets(arr,S); 48 | 49 | for(auto v : result){ 50 | for(auto no : v){ 51 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | //Build a Prefix Tree - Trie 7 | class Node{ 8 | public: 9 | char data; 10 | unordered_map m; 11 | bool isTerminal; 12 | 13 | Node(char d){ 14 | data = d; 15 | isTerminal = false; 16 | } 17 | }; 18 | 19 | 20 | class Trie{ 21 | 22 | Node*root; 23 | public: 24 | Trie(){ 25 | root = new Node('\0'); 26 | } 27 | 28 | //later 29 | void insert(string word){ 30 | 31 | Node* temp = root; 32 | 33 | for(char ch : word){ 34 | 35 | if(temp->m.count(ch)==0){ 36 | Node *n = new Node(ch); 37 | temp->m[ch] = n; 38 | } 39 | temp = temp->m[ch]; 40 | } 41 | 42 | temp->isTerminal = true; 43 | 44 | } 45 | 46 | bool search(string word){ 47 | 48 | Node*temp = root; 49 | 50 | for(char ch : word){ 51 | 52 | if(temp->m.count(ch)==0){ 53 | return false; 54 | } 55 | temp = temp->m[ch]; 56 | 57 | 58 | } 59 | return temp->isTerminal; 60 | } 61 | }; 62 | 63 | 64 | int main(){ 65 | 66 | string input = "this is a suffix trie"; 67 | 68 | string queries[] = "fix," 69 | 70 | 71 | return 0; 72 | } 73 | 74 | -------------------------------------------------------------------------------- /14 Graphs/03_bfs_.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void bfs(int source){ 25 | 26 | queue q; 27 | bool *visited = new bool[V]{0}; 28 | 29 | q.push(source); 30 | visited[source] = true; 31 | 32 | while(!q.empty()){ 33 | //Do some work for every node 34 | int f = q.front(); 35 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int lower_bound(vector arr,int key){ 7 | 8 | int s = 0; 9 | int e = arr.size() - 1; 10 | 11 | int ans = -1; 12 | 13 | while(s<=e){ 14 | int mid = (s+e)/2; 15 | 16 | if(arr[mid]==key){ 17 | ans = mid; 18 | e = mid - 1; 19 | } 20 | else if(arr[mid] > key){ 21 | e = mid - 1; 22 | } 23 | else{ 24 | s = mid + 1; 25 | } 26 | } 27 | return ans; 28 | 29 | } 30 | int upper_bound(vector arr,int key){ 31 | 32 | int s = 0; 33 | int e = arr.size() - 1; 34 | 35 | int ans = -1; 36 | 37 | while(s<=e){ 38 | int mid = (s+e)/2; 39 | 40 | if(arr[mid]==key){ 41 | ans = mid; 42 | s = mid + 1; 43 | } 44 | else if(arr[mid] > key){ 45 | e = mid - 1; 46 | } 47 | else{ 48 | s = mid + 1; 49 | } 50 | } 51 | return ans; 52 | 53 | } 54 | 55 | 56 | int main(){ 57 | 58 | vector arr = {0,1,1,2,3,3,3,3,3,4,5,5,5,10}; 59 | int n = arr.size(); 60 | 61 | cout<< upper_bound(arr,3) - lower_bound(arr,3) + 1 < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | bool outOfOrder(vector arr,int i){ 7 | int x = arr[i]; 8 | if(i==0){ 9 | return x > arr[1]; 10 | } 11 | if(i==arr.size()-1){ 12 | return x < arr[i-1]; 13 | } 14 | return x > arr[i+1] or x < arr[i-1]; 15 | 16 | } 17 | 18 | pair subarraySort(vector arr) { 19 | 20 | int smallest = INT_MAX; 21 | int largest = INT_MIN; 22 | 23 | for(int i=0;i= arr[left]){ 39 | left++; 40 | } 41 | int right = arr.size() - 1; 42 | while(largest <= arr[right]){ 43 | right--; 44 | } 45 | 46 | return {left,right}; 47 | 48 | } 49 | 50 | int main() { 51 | vector arr = {1, 2, 3, 4, 5, 8, 6, 7, 9, 10, 11}; 52 | auto p = subarraySort(arr); 53 | cout<< p.first <<" and "< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void maxSubArrayK(vector a,int k){ 7 | 8 | //Algorithm 9 | int n = a.size(); 10 | 11 | deque Q(k); 12 | //1. Process only the first K elements 13 | int i; 14 | 15 | for(i=0;i a[Q.back()]){ 19 | Q.pop_back(); 20 | } 21 | 22 | Q.push_back(i); 23 | 24 | } 25 | 26 | //2. Remaining the elements of the array 27 | for( ;i= a[Q.back()]){ 34 | Q.pop_back(); 35 | } 36 | 37 | //always 38 | Q.push_back(i); 39 | } 40 | 41 | 42 | cout<< a[Q.front()]; 43 | 44 | } 45 | 46 | int main() { 47 | 48 | vector arr{1,2,3,1,4,5,2,3,5}; 49 | int k = 3; 50 | 51 | maxSubArrayK(arr,k); 52 | 53 | 54 | 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /08 Stacks & Queue/balanced_paranthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | bool isBalanced(string input){ 8 | //Todo: Complete this method 9 | 10 | stack s; 11 | for(auto ch : input){ 12 | 13 | switch(ch){ 14 | case '(': 15 | case '[': 16 | case '{': s.push(ch); 17 | break; 18 | 19 | case ')': if(!s.empty() and s.top()=='('){ 20 | s.pop(); 21 | } 22 | else{ 23 | return false; 24 | } 25 | break; 26 | 27 | case ']': if(!s.empty() and s.top()=='['){ 28 | s.pop(); 29 | } 30 | else{ 31 | return false; 32 | } 33 | break; 34 | 35 | case '}': if(!s.empty() and s.top()=='{'){ 36 | s.pop(); 37 | } 38 | else{ 39 | return false; 40 | } 41 | break; 42 | default : continue; 43 | } 44 | } 45 | 46 | if(s.empty()==true){ 47 | return true; 48 | } 49 | return false; 50 | } 51 | 52 | 53 | 54 | int main(){ 55 | string s = "{ a + (b+c) + ([d+e]*f)) } + k`";//{ a + (b+c) + ([d+e]*f)) } + k"; 56 | 57 | if(isBalanced(s)){ 58 | cout<<"Balanced!"< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Node{ 9 | public: 10 | string name; 11 | list nbrs; 12 | 13 | Node(string name){ 14 | this->name = name; 15 | } 16 | }; 17 | 18 | class Graph{ 19 | unordered_map m; 20 | 21 | public: 22 | Graph(vector cities){ 23 | for(auto city : cities){ 24 | m[city] = new Node(city); 25 | } 26 | } 27 | 28 | void addEdge(string x,string y,bool undir=false){ 29 | m[x]->nbrs.push_back(y); 30 | 31 | if(undir){ 32 | m[y]->nbrs.push_back(x); 33 | } 34 | } 35 | 36 | void printAdjList(){ 37 | for(auto cityPair : m){ 38 | auto city = cityPair.first; 39 | Node *node = cityPair.second; 40 | cout<"; 41 | for(auto nbr : node->nbrs){ 42 | cout << nbr<<","; 43 | } 44 | cout< cities = {"Delhi","London","Paris","New York"}; 51 | Graph g(cities); 52 | 53 | g.addEdge("Delhi","London"); 54 | g.addEdge("New York","London"); 55 | g.addEdge("Delhi","Paris"); 56 | g.addEdge("Paris","New York"); 57 | 58 | g.printAdjList(); 59 | 60 | 61 | return 0; 62 | } 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /05 Binary Search/max_subarray_sliding_window_deque.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void maxSubArrayK(vector a,int k){ 7 | 8 | //Algorithm 9 | int n = a.size(); 10 | 11 | deque Q(k); 12 | //1. Process only the first K elements 13 | int i; 14 | 15 | for(i=0;i a[Q.back()]){ 19 | Q.pop_back(); 20 | } 21 | 22 | Q.push_back(i); 23 | 24 | } 25 | 26 | //2. Remaining the elements of the array 27 | for( ;i= a[Q.back()]){ 34 | Q.pop_back(); 35 | } 36 | 37 | //always 38 | Q.push_back(i); 39 | } 40 | 41 | 42 | cout<< a[Q.front()]; 43 | 44 | } 45 | 46 | int main() { 47 | 48 | vector arr{1,2,3,1,4,5,2,3,5}; 49 | int k = 3; 50 | 51 | maxSubArrayK(arr,k); 52 | 53 | 54 | 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /12 Hashing/anagrams_substrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /* 7 | 1. Generate all substrings 8 | 2. Generate their hash 9 | 3. Hash the 'hash' values to club all anagrams in single bucket, to get their frequency count 10 | 4. From freq count, we can easily count the paris 11 | */ 12 | vector getHashValue(string s,int i,int j){ 13 | 14 | vector freq(26,0); 15 | 16 | //iterate over the original string from i to j to fill this vector 17 | for(int k=i;k<=j;k++){ 18 | char ch = s[k]; 19 | freq[ch-'a']++; 20 | } 21 | 22 | return freq; 23 | 24 | } 25 | 26 | 27 | 28 | int anagrams_substrings(string s){ 29 | 30 | map , int > m; 31 | 32 | for(int i=0;i h = getHashValue(s,i,j); 37 | //put it inside a map 38 | m[h]++; 39 | } 40 | } 41 | 42 | //pairs 43 | int ans = 0; 44 | for(auto p : m){ 45 | 46 | int freq = p.second; 47 | if(freq>=2){ 48 | ans += (freq)*(freq-1)/2; 49 | } 50 | 51 | } 52 | return ans; 53 | 54 | } 55 | 56 | 57 | 58 | int main(){ 59 | 60 | string s; 61 | cin>>s ; 62 | 63 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | class Node{ 10 | public: 11 | string name; 12 | list nbrs; 13 | 14 | Node(string name){ 15 | this->name = name; 16 | } 17 | }; 18 | 19 | class Graph{ 20 | //Node Name -- Pointer to Node Object 21 | unordered_map m; 22 | public: 23 | Graph(vector cities){ 24 | for(auto city : cities){ 25 | m[city] = new Node(city); 26 | } 27 | } 28 | 29 | void addEdge(string x,string y,bool undir=false){ 30 | m[x]->nbrs.push_back(y); 31 | if(undir){ 32 | m[y]->nbrs.push_back(x); 33 | } 34 | } 35 | 36 | void printAdjList(){ 37 | for(auto cityPair : m){ 38 | auto city = cityPair.first; 39 | cout<"; 40 | Node *node = cityPair.second; 41 | for(auto nbr : node->nbrs){ 42 | cout< cities = {"Delhi","London","Paris","New York"}; 52 | Graph g(cities); 53 | g.addEdge("Delhi","London"); 54 | g.addEdge("New York","London"); 55 | g.addEdge("Delhi","Paris"); 56 | g.addEdge("Paris","New York"); 57 | 58 | g.printAdjList(); 59 | 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /11 Heaps/04_running_median.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | //Running Median Heaps 7 | int main(){ 8 | 9 | 10 | 11 | priority_queue leftheap; //maxheap 12 | priority_queue,greater > rightheap; //min heap 13 | 14 | int d; 15 | cin>>d; 16 | leftheap.push(d); 17 | 18 | float med = d; 19 | cout<< med <<" "; 20 | 21 | cin>>d; 22 | while(d!=-1){ 23 | //left or right or equal 24 | if(leftheap.size() > rightheap.size()){ 25 | if(d < med){ 26 | rightheap.push(leftheap.top()); 27 | leftheap.pop(); 28 | leftheap.push(d); 29 | } 30 | else{ 31 | rightheap.push(d); 32 | } 33 | med = (leftheap.top() + rightheap.top())/2.0; 34 | } 35 | else if(leftheap.size()==rightheap.size()){ 36 | if(d < med){ 37 | leftheap.push(d); 38 | med = leftheap.top(); 39 | } 40 | else{ 41 | rightheap.push(d); 42 | med = rightheap.top(); 43 | } 44 | 45 | } 46 | else{ 47 | if(d < med){ 48 | leftheap.push(d); 49 | } 50 | else{ 51 | leftheap.push(rightheap.top()); 52 | rightheap.pop(); 53 | rightheap.push(d); 54 | } 55 | med = (leftheap.top() + rightheap.top())/2; 56 | 57 | } 58 | 59 | cout<< med<<" "; 60 | cin>>d; 61 | } 62 | 63 | 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /05 Binary Search/kpartition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool divideAmongK(int arr[],int n,int k,int limit){ 5 | //return true if every partition gets atleast limit no of coins 6 | 7 | int cnt = 0; 8 | int current_sum = 0; 9 | 10 | for(int i=0;i=limit){ 12 | cnt +=1; 13 | current_sum = 0; 14 | } 15 | else{ 16 | current_sum += arr[i]; 17 | } 18 | } 19 | 20 | return cnt>=k; 21 | } 22 | 23 | int k_partition(int arr[],int n,int k){ 24 | 25 | int e = 0; 26 | int s = 0; 27 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int countMinSwaps(vector arr){ 7 | 8 | // Know the actual positions of elements (sorting) 9 | //store the current indices 10 | int n = arr.size(); 11 | pair ap[n]; 12 | for(int i=0;i visited(n,false); 22 | 23 | int ans = 0; 24 | for(int i=0;i arr{5,4,3,2,1}; 53 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | int lcs(string s1,string s2){ 8 | //bottom up approach to lcs 9 | int n1 = s1.length(); 10 | int n2 = s2.length(); 11 | 12 | //2d dp array 13 | vector > dp(n1 + 1, vector(n2+1,0)); 14 | 15 | //1,1 ... n1,n2 16 | for(int i=1;i<=n1;i++){ 17 | for(int j=1;j<=n2;j++){ 18 | 19 | if(s1[i-1]==s2[j-1]){ 20 | dp[i][j] = 1 + dp[i-1][j-1]; 21 | } 22 | else{ 23 | int op1 = dp[i-1][j]; 24 | int op2 = dp[i][j-1]; 25 | dp[i][j] = max(op1,op2); 26 | } 27 | } 28 | } 29 | 30 | //print 31 | /* 32 | for(int i=0;i<=n1;i++){ 33 | for(int j=0;j<=n2;j++){ 34 | cout< result; 41 | int i=n1,j=n2; 42 | while(i!=0 and j!=0){ 43 | if(dp[i][j]==dp[i][j-1]){ 44 | j--; 45 | } 46 | else if(dp[i][j]==dp[i-1][j]){ 47 | i--; 48 | } 49 | else{ 50 | result.push_back(s1[i-1]); 51 | i--; 52 | j--; 53 | } 54 | } 55 | reverse(result.begin(),result.end()); 56 | for(char x:result){ 57 | cout< 2 | #include 3 | using namespace std; 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node*left; 10 | node*right; 11 | 12 | node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 20 | node* buildTree(){ 21 | 22 | int d; 23 | cin>>d; 24 | 25 | if(d==-1){ 26 | return NULL; 27 | } 28 | 29 | node* n = new node(d); 30 | n->left = buildTree(); 31 | n->right = buildTree(); 32 | 33 | return n; 34 | } 35 | /* Todo: Implement Level Order Traversal 36 | Expected Output 37 | 38 | 1 39 | 2 3 40 | 4 5 6 41 | 7 42 | */ 43 | 44 | void levelOrderPrint(node*root){ 45 | 46 | queue q; 47 | q.push(root); 48 | q.push(NULL); 49 | 50 | while(!q.empty()){ 51 | node* temp = q.front(); 52 | if(temp==NULL){ 53 | cout<data<<" "; 63 | 64 | if(temp->left){ 65 | q.push(temp->left); 66 | } 67 | if(temp->right){ 68 | q.push(temp->right); 69 | } 70 | } 71 | 72 | } 73 | return; 74 | } 75 | 76 | 77 | 78 | 79 | int main(){ 80 | 81 | node* root = buildTree(); 82 | levelOrderPrint(root); 83 | 84 | 85 | return 0; 86 | } -------------------------------------------------------------------------------- /04 Sorting & Searching/01 mergesort_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //helper method 6 | void merge(vector &array,int s,int e){ 7 | int i = s; 8 | int m = (s+e)/2; 9 | int j = m + 1; 10 | 11 | vector temp; 12 | 13 | 14 | while(i<=m and j<=e){ 15 | if(array[i] < array[j]){ 16 | temp.push_back(array[i]); 17 | i++; 18 | } 19 | else{ 20 | temp.push_back(array[j]); 21 | j++; 22 | } 23 | } 24 | 25 | //copy rem elements from first array 26 | while(i<=m){ 27 | temp.push_back(array[i++]); 28 | } 29 | 30 | // or copy rem elements from second array 31 | while(j<=e){ 32 | temp.push_back(array[j++]); 33 | } 34 | 35 | //copy back the eleemtns from temp to original array 36 | int k = 0 ; 37 | for(int idx = s; idx <=e ;idx++){ 38 | array[idx] = temp[k++]; 39 | } 40 | return; 41 | } 42 | 43 | //sorting method 44 | void mergesort(vector &arr,int s,int e){ 45 | //base case 46 | if(s>=e){ 47 | return; 48 | } 49 | //rec case 50 | int mid = (s+e)/2; 51 | mergesort(arr,s,mid); 52 | mergesort(arr,mid+1,e); 53 | return merge(arr,s,e); 54 | } 55 | 56 | int main(){ 57 | 58 | vector arr{10,5,2,0,7,6,4}; 59 | 60 | int s = 0; 61 | int e = arr.size()-1; 62 | mergesort(arr,s,e); 63 | for(int x : arr){ 64 | cout<< x <<","; 65 | } 66 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int sparse_search(string a[],int n,string key){ 6 | 7 | // sparse search 8 | int s=0; 9 | int e = n-1; 10 | while(s<=e){ 11 | int mid = (s+e)/2; 12 | int mid_left = mid - 1; 13 | int mid_right = mid + 1; 14 | if(a[mid]==""){ 15 | while(1){ 16 | if(mid_lefte){ 17 | return -1; 18 | } 19 | else if(mid_right<=e and a[mid_right]!=""){ 20 | mid = mid_right; 21 | break; 22 | } 23 | else if(mid_left>=s and a[mid_left]!=""){ 24 | mid = mid_left; 25 | break; 26 | } 27 | mid_left--; 28 | mid_right++; 29 | } 30 | } 31 | if(a[mid]==key){ 32 | return mid; 33 | } 34 | else if(a[mid] > key){ 35 | e = mid - 1; 36 | } 37 | else{ 38 | s = mid + 1; 39 | } 40 | } 41 | return -1; 42 | } 43 | 44 | int main() { 45 | string arr[] = {"ai", "", "","bat", "","","car","cat","","","dog",""}; 46 | int n = 12; 47 | 48 | string f; 49 | cin>>f; 50 | cout< 2 | #include 3 | using namespace std; 4 | 5 | //helper method 6 | int merge(vector &array,int s,int e){ 7 | int i = s; 8 | int m = (s+e)/2; 9 | int j = m + 1; 10 | 11 | vector temp; 12 | 13 | int cnt = 0; 14 | 15 | while(i<=m and j<=e){ 16 | if(array[i] < array[j]){ 17 | temp.push_back(array[i]); 18 | i++; 19 | } 20 | else{ 21 | cnt += (m - i + 1); 22 | temp.push_back(array[j]); 23 | j++; 24 | } 25 | } 26 | 27 | //copy rem elements from first array 28 | while(i<=m){ 29 | temp.push_back(array[i++]); 30 | } 31 | 32 | // or copy rem elements from second array 33 | while(j<=e){ 34 | temp.push_back(array[j++]); 35 | } 36 | 37 | //copy back the eleemtns from temp to original array 38 | int k = 0 ; 39 | for(int idx = s; idx <=e ;idx++){ 40 | array[idx] = temp[k++]; 41 | } 42 | return cnt; 43 | } 44 | 45 | //sorting method 46 | int inversion_count(vector &arr,int s,int e){ 47 | //base case 48 | if(s>=e){ 49 | return 0; 50 | } 51 | //rec case 52 | int mid = (s+e)/2; 53 | int C1 = inversion_count(arr,s,mid); 54 | int C2 = inversion_count(arr,mid+1,e); 55 | int CI = merge(arr,s,e); 56 | return C1 + C2 + CI; 57 | } 58 | 59 | int main(){ 60 | 61 | vector arr{0,5,2,3,1}; 62 | 63 | int s = 0; 64 | int e = arr.size()-1; 65 | cout<< inversion_count(arr,s,e) < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | //undirected graph 17 | void addEdge(int x,int y){ 18 | l[x].push_back(y); 19 | l[y].push_back(x); 20 | } 21 | bool dfs(int node, vector &visited, int parent){ 22 | //mark that node visited 23 | visited[node] = true; 24 | 25 | for(auto nbr : l[node]){ 26 | 27 | if(!visited[nbr]){ 28 | 29 | bool nbrFoundACycle = dfs(nbr,visited,node); 30 | if(nbrFoundACycle){ 31 | return true; 32 | } 33 | } 34 | //nbr is visited and its not the parent of current node in the current dfs call 35 | else if(nbr!=parent){ 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | bool contains_cycle(){ 43 | //Graph is single component 44 | vector visited(V,false); 45 | return dfs(0, visited, -1); 46 | } 47 | 48 | }; 49 | 50 | bool contains_cycle(int V,vector > edges){ 51 | //Complete this method 52 | 53 | Graph g(V); 54 | for(auto edge:edges){ 55 | g.addEdge(edge.first,edge.second); 56 | } 57 | return g.contains_cycle(); 58 | 59 | } 60 | 61 | int main(){ 62 | 63 | Graph g(3); 64 | g.addEdge(0,1); 65 | g.addEdge(1,2); 66 | //g.addEdge(2,0); 67 | 68 | cout << g.contains_cycle() < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector mergeKArrays(vector > arrays){ 7 | //logic 8 | 9 | int k = arrays.size(); 10 | //triplet -> element, array idx, element idx 11 | priority_queue< vector , vector > , greater > > q; 12 | 13 | 14 | vector output; 15 | 16 | //init the heap 17 | for(int i=0;i > arr = {{10,15,20,30}, 52 | {2,5,8,14,24}, 53 | {0,11,60,90}}; 54 | 55 | //various approaches 56 | vector result = mergeKArrays(arr); 57 | 58 | 59 | //output 60 | for(auto x:result){ 61 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | string s ="thequickbrownfoxjumpsoverthehighbridge"; 8 | 9 | string words[] = {"the","fox","thequickbrownfox", "jumps","lazy","lazyfox", 10 | 11 | "highbridge","the","over", "bridge","high","tall", 12 | 13 | "quick","brown"}; 14 | 15 | /* 16 | string s ="thequickbrownfox"; 17 | 18 | string words[] = {"the", "quickbrown", "fox","quick","brown"}; 19 | */ 20 | //Main Logic 21 | int min_bars_helper(string s,string words[],int idx, unordered_set &m){ 22 | 23 | //base case 24 | if(s[idx]=='\0'){ 25 | return 0; 26 | } 27 | 28 | //rec case 29 | int ans = INT_MAX; 30 | string current_string = ""; 31 | 32 | for(int j=idx; s[j]!='\0';j++){ 33 | current_string += s[j]; 34 | 35 | //at every step you can whether this prefix is present in set 36 | if(m.find(current_string)!=m.end()){ 37 | int remaning_ans = min_bars_helper(s,words,j+1,m); 38 | if(remaning_ans!=-1){ 39 | ans = min(ans, 1 + remaning_ans); 40 | 41 | } 42 | } 43 | } 44 | 45 | if(ans==INT_MAX){ 46 | return -1; 47 | } 48 | return ans; 49 | } 50 | 51 | 52 | 53 | int min_bars(){ 54 | 55 | unordered_set m; 56 | 57 | for(string w:words){ 58 | m.insert(w); 59 | } 60 | 61 | //recursive helper function 62 | int output = min_bars_helper(s,words,0,m); 63 | return output - 1; 64 | 65 | } 66 | 67 | int main(){ 68 | 69 | cout<< min_bars() < 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | string simplifyPath(string path){ 8 | //1. Step - Tokenisation & Filtering 9 | 10 | istringstream iss(path); 11 | vector tokens; 12 | 13 | string token; 14 | while(getline(iss,token,'/')){ 15 | if(token=="." or token==""){ 16 | continue; 17 | } 18 | tokens.push_back(token); 19 | } 20 | 21 | 22 | // 2. Handle .. 23 | vector stack; 24 | 25 | if(path[0]=='/'){ 26 | //denotes that our path is an abs path (wrt root dir) 27 | stack.push_back(""); 28 | } 29 | 30 | for(string token : tokens){ 31 | if(token==".."){ 32 | //2 cases -> Abs path or relative path 33 | if(stack.size()==0 or stack[stack.size()-1]==".."){ 34 | stack.push_back(".."); 35 | } 36 | 37 | else if(stack[stack.size()-1]!=""){ 38 | stack.pop_back(); 39 | } 40 | } 41 | else{ 42 | //x,y,z... 43 | stack.push_back(token); 44 | } 45 | 46 | } 47 | //single element 48 | if(stack.size()==1 and stack[0]==""){ 49 | return "/"; 50 | } 51 | 52 | //combine all elements in stack to get the answer 53 | ostringstream oss; 54 | int i = 0; 55 | 56 | for(auto token :stack){ 57 | if(i!=0){ 58 | oss<<"/"; 59 | } 60 | i++; 61 | oss << token; 62 | } 63 | 64 | return oss.str(); 65 | 66 | } 67 | 68 | 69 | int main(){ 70 | string path = "/../x/y/../z/././w/a///../../c/./"; 71 | // Output : /x/z/c 72 | cout << simplifyPath(path) < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | //Build a Prefix Tree - Trie 8 | class Node{ 9 | public: 10 | char data; 11 | unordered_map m; 12 | bool isTerminal; 13 | 14 | Node(char d){ 15 | data = d; 16 | isTerminal = false; 17 | } 18 | }; 19 | 20 | 21 | class SuffixTrie{ 22 | 23 | Node*root; 24 | public: 25 | SuffixTrie(){ 26 | root = new Node('\0'); 27 | } 28 | 29 | //later 30 | void insert_helper(string word){ 31 | 32 | Node* temp = root; 33 | 34 | for(char ch : word){ 35 | 36 | if(temp->m.count(ch)==0){ 37 | Node *n = new Node(ch); 38 | temp->m[ch] = n; 39 | } 40 | temp = temp->m[ch]; 41 | } 42 | 43 | temp->isTerminal = true; 44 | 45 | } 46 | 47 | bool search(string word){ 48 | 49 | Node*temp = root; 50 | 51 | for(char ch : word){ 52 | 53 | if(temp->m.count(ch)==0){ 54 | return false; 55 | } 56 | temp = temp->m[ch]; 57 | 58 | 59 | } 60 | return temp->isTerminal; 61 | } 62 | 63 | void insert(string word){ 64 | //pick all substrings from (i, eos) and insert_helper 65 | for(int i=0;word[i]!='\0';i++){ 66 | insert_helper(word.substr(i)); 67 | } 68 | } 69 | }; 70 | 71 | 72 | int main(){ 73 | 74 | //Simplified Suffix Trie 75 | string input = "hello"; 76 | string suffixes[] = {"lo","ell","hello"}; 77 | 78 | SuffixTrie t; 79 | t.insert(input); 80 | 81 | for(auto sf : suffixes){ 82 | if(t.search(sf)){ 83 | cout<<"yes "; 84 | } 85 | else{ 86 | cout<<"no "; 87 | } 88 | } 89 | 90 | return 0; 91 | } 92 | 93 | -------------------------------------------------------------------------------- /10 BST/closest_in_bst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int key; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int key){ 12 | this->key = key; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | Node* insert(Node * root, int key){ 18 | if(root==NULL){ 19 | return new Node(key); 20 | } 21 | 22 | //rec case 23 | if(key < root->key){ 24 | root->left = insert(root->left,key); 25 | } 26 | else{ 27 | root->right = insert(root->right,key); 28 | } 29 | return root; 30 | 31 | } 32 | 33 | int findClosestInBST(Node * root, int target){ 34 | //todo 35 | 36 | int closest; 37 | int diff = INT_MAX; 38 | 39 | Node *temp = root; 40 | 41 | while(temp!=NULL){ 42 | 43 | int current_diff = abs(temp->key - target); 44 | 45 | if(current_diff==0){ 46 | return temp->key; 47 | } 48 | 49 | 50 | if(current_diff < diff){ 51 | diff = current_diff; 52 | closest = temp->key; 53 | } 54 | 55 | 56 | //right or left 57 | if(temp-> key < target){ 58 | temp = temp -> right; 59 | } 60 | else{ 61 | temp = temp->left; 62 | } 63 | } 64 | return closest; 65 | 66 | } 67 | 68 | void printInOrder(Node *root){ 69 | if(root==NULL){ 70 | return; 71 | } 72 | //left, root, right 73 | printInOrder(root->left); 74 | cout << root-> key <<" ,"; 75 | printInOrder(root->right); 76 | } 77 | 78 | 79 | int main(){ 80 | 81 | Node * root = NULL; 82 | int arr[] = {8,3,10,1,6,14,4,7,13}; 83 | 84 | for(int x : arr){ 85 | root = insert(root,x); 86 | } 87 | //printInOrder(root); 88 | 89 | cout << findClosestInBST(root,12) < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | void addEdge(int x,int y){ 17 | l[x].push_back(y); 18 | } 19 | 20 | bool dfs(int node,vector &visited, vector &stack){ 21 | //arrive at node 22 | visited[node] = true; 23 | stack[node] = true; 24 | 25 | //do some work at node,return true if backedge is found here itself 26 | for(int nbr : l[node]){ 27 | 28 | if(stack[nbr]==true){ 29 | return true; 30 | } 31 | else if(visited[nbr]==false){ 32 | bool nbrFoundACycle = dfs(nbr,visited,stack); 33 | if(nbrFoundACycle){ 34 | return true; 35 | } 36 | } 37 | } 38 | 39 | //going back 40 | stack[node] = false; 41 | return false; 42 | } 43 | 44 | bool contains_cycle(){ 45 | vector visited(V,false); 46 | vector stack(V,false); 47 | 48 | for(int i=0;i > edges){ 63 | //Complete this method 64 | 65 | Graph g(V); 66 | for(auto edge : edges){ 67 | g.addEdge(edge.first,edge.second); 68 | } 69 | return g.contains_cycle(); 70 | 71 | } 72 | 73 | int main(){ 74 | 75 | Graph g(3); 76 | g.addEdge(0,1); 77 | g.addEdge(1,2); 78 | g.addEdge(2,0); 79 | 80 | cout << g.contains_cycle() < 2 | #include 3 | using namespace std; 4 | 5 | int dfs(vector > &matrix, vector > &visited, int i,int j,int m,int n){ 6 | 7 | visited[i][j] = true; 8 | 9 | int cs = 1; 10 | 11 | int dx[] = {1,-1,0,0}; 12 | int dy[] = {0,0,1,-1}; 13 | 14 | for(int k=0;k<4;k++){ 15 | int nx = i + dx[k]; 16 | int ny = j + dy[k]; 17 | 18 | if(nx>=0 and nx=0 and ny > matrix){ 28 | //return the size of largest island in grid 29 | int m = matrix.size(); 30 | int n = matrix[0].size(); 31 | 32 | //visited matrix 33 | vector > visited(m, vector(n,false)); 34 | 35 | int largest = 0; 36 | 37 | for(int i=0;ilargest){ 43 | largest = size; 44 | } 45 | 46 | } 47 | 48 | } 49 | } 50 | return largest; 51 | } 52 | 53 | 54 | int main(){ 55 | vector > grid = { 56 | {1, 0, 0, 1, 0}, 57 | {1, 0, 1, 0, 0}, 58 | {0, 0, 1, 0, 1}, 59 | {1, 0, 1, 1, 1}, 60 | {1, 0, 1, 1, 0} 61 | }; 62 | 63 | cout<< largest_island(grid) < 2 | #include 3 | using namespace std; 4 | 5 | int dfs(vector > &matrix, vector > &visited, int i,int j,int m,int n){ 6 | 7 | visited[i][j] = true; 8 | 9 | int cs = 1; 10 | 11 | int dx[] = {1,-1,0,0}; 12 | int dy[] = {0,0,1,-1}; 13 | 14 | for(int k=0;k<4;k++){ 15 | int nx = i + dx[k]; 16 | int ny = j + dy[k]; 17 | 18 | if(nx>=0 and nx=0 and ny > matrix){ 28 | //return the size of largest island in grid 29 | int m = matrix.size(); 30 | int n = matrix[0].size(); 31 | 32 | //visited matrix 33 | vector > visited(m, vector(n,false)); 34 | 35 | int largest = 0; 36 | 37 | for(int i=0;ilargest){ 43 | largest = size; 44 | } 45 | 46 | } 47 | 48 | } 49 | } 50 | return largest; 51 | } 52 | 53 | 54 | int main(){ 55 | vector > grid = { 56 | {1, 0, 0, 1, 0}, 57 | {1, 0, 1, 0, 0}, 58 | {0, 0, 1, 0, 1}, 59 | {1, 0, 1, 1, 1}, 60 | {1, 0, 1, 1, 0} 61 | }; 62 | 63 | cout<< largest_island(grid) < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string find_window(string s,string p){ 7 | 8 | 9 | //Array as a Freq Map or you can hashmap 10 | int FP[256] = {0}; 11 | int FS[256] = {0}; 12 | 13 | for(int i=0;i FP[s[start]]){ 42 | FS[s[start]]--; 43 | start++; 44 | } 45 | 46 | //note. the window size 47 | window_size = i - start + 1; 48 | if(window_size < min_so_far){ 49 | min_so_far = window_size; 50 | start_idx = start; 51 | } 52 | 53 | } 54 | 55 | } 56 | if(start_idx==-1){ 57 | return "No window found"; 58 | } 59 | return s.substr(start_idx,min_so_far); 60 | } 61 | 62 | 63 | 64 | int main(){ 65 | 66 | string s,p; 67 | cin>>s>>p; 68 | 69 | 70 | cout< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Car{ 8 | 9 | public: 10 | string id; 11 | int x,y; 12 | Car(string id,int x,int y){ 13 | this->id = id; 14 | this->x = x; 15 | this->y = y; 16 | } 17 | int dist() const{ 18 | return x*x + y*y; //square of the dist 19 | } 20 | }; 21 | 22 | class CarCompare{ 23 | public: 24 | bool operator()(const Car A,const Car B){ 25 | return A.dist() < B.dist();// max heap 26 | } 27 | }; 28 | 29 | 30 | 31 | void printNearestCars(vector cars,int k){ 32 | 33 | 34 | //create a max heap of size K 35 | priority_queue , CarCompare> max_heap(cars.begin(), cars.begin() + k); 36 | 37 | //remaining cars 38 | for(int i=k; i < cars.size();i++){ 39 | auto car = cars[i]; 40 | 41 | if(car.dist() < max_heap.top().dist()){ 42 | max_heap.pop(); //remove the root node largest 43 | max_heap.push(car); 44 | } 45 | } 46 | 47 | //print all the cars inside the heap they will be smallest 48 | vector output; 49 | while(!max_heap.empty()){ 50 | //cout<< max_heap.top().id <>N>>K; 72 | 73 | string id; 74 | int x,y; 75 | 76 | vector cars; 77 | 78 | for(int i=0;i> id>>x>>y; 80 | Car car(id,x,y); 81 | cars.push_back(car); 82 | } 83 | 84 | printNearestCars(cars,K); 85 | 86 | return 0; 87 | } -------------------------------------------------------------------------------- /12 Hashing/Counting Rectangles/rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //Point Class 7 | class Point { 8 | public: 9 | int x; 10 | int y; 11 | 12 | Point() { 13 | 14 | } 15 | 16 | Point(int x, int y) { 17 | this->x = x; 18 | this->y = y; 19 | } 20 | 21 | }; 22 | 23 | //Comparator Class 24 | class Compare{ 25 | 26 | public: 27 | bool operator()(const Point p1,const Point p2){ 28 | if(p1.x==p2.x){ 29 | return p1.y < p2.y; 30 | } 31 | return p1.x < p2.x; 32 | } 33 | }; 34 | 35 | 36 | //Count Rectangles Function 37 | int count_rectangles(vector points) { 38 | 39 | //1. Insert all Points in the set 40 | set s; 41 | 42 | for(Point p:points){ 43 | s.insert(p); 44 | } 45 | 46 | int ans = 0; 47 | //2. Logic Brute Force Two Points + LookUp for other Two 48 | for(auto it = s.begin();it!= prev(s.end());it++){ 49 | for(auto jt= next(it); jt!=s.end();jt++){ 50 | 51 | Point p1 = *it; 52 | Point p2 = *jt; 53 | 54 | //small check that we want to make 55 | if(p2.x==p1.x or p2.y==p1.y){ 56 | continue; 57 | } 58 | 59 | 60 | //P3, P4 61 | Point p3(p1.x,p2.y); 62 | Point p4(p2.x,p1.y); 63 | 64 | //Lookup 65 | if(s.find(p3)!=s.end() and s.find(p4)!=s.end()) 66 | { 67 | ans += 1; 68 | } 69 | 70 | } 71 | 72 | } 73 | 74 | return ans/2; 75 | 76 | } 77 | 78 | 79 | 80 | int main() { 81 | 82 | int N; 83 | cin >> N; 84 | 85 | int x, y; 86 | 87 | vector points; 88 | 89 | for (int i = 0; i < N; i++) { 90 | cin >> x >> y; 91 | Point p(x, y); 92 | points.push_back(p); 93 | } 94 | 95 | cout << count_rectangles(points) << endl; 96 | 97 | return 0; 98 | } 99 | 100 | 101 | -------------------------------------------------------------------------------- /14 Graphs/dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Graph{ 9 | 10 | int V; 11 | list > *l; 12 | 13 | public: 14 | Graph(int v){ 15 | V = v; 16 | l = new list >[V]; 17 | } 18 | 19 | void addEdge(int u,int v,int wt,bool undir = true){ 20 | 21 | l[u].push_back({wt,v}); 22 | if(undir){ 23 | l[v].push_back({wt,u}); 24 | } 25 | } 26 | 27 | int dijkstra(int src,int dest){ 28 | 29 | //Data Structures 30 | vector dist(V,INT_MAX); 31 | set > s; 32 | 33 | //1. Init 34 | dist[src] = 0; 35 | s.insert({0,src}); 36 | 37 | while(!s.empty()){ 38 | 39 | auto it = s.begin(); 40 | int node = it->second; 41 | int distTillNow = it->first; 42 | s.erase(it); //Pop 43 | 44 | //Iterate over the nbrs of node 45 | for(auto nbrPair : l[node]){ 46 | //...... 47 | 48 | int nbr = nbrPair.second; 49 | int currentEdge = nbrPair.first; 50 | 51 | if(distTillNow + currentEdge < dist[nbr]){ 52 | //remove if nbr already exist in the set 53 | 54 | auto f = s.find({dist[nbr],nbr}); 55 | if(f!=s.end()){ 56 | s.erase(f); 57 | } 58 | //insert the updated value with the new dist 59 | dist[nbr] = distTillNow + currentEdge; 60 | s.insert({dist[nbr],nbr}); 61 | 62 | } 63 | 64 | } 65 | 66 | } 67 | //Single Source Shortest Dist to all other nodes 68 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void bfs(int source,int dest=-1){ 25 | 26 | queue q; 27 | bool *visited = new bool[V]{0}; 28 | int *dist = new int[V]{0}; 29 | int *parent = new int[V]; 30 | 31 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node*left; 10 | node*right; 11 | 12 | node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 20 | node* buildTree(){ 21 | 22 | int d; 23 | cin>>d; 24 | 25 | if(d==-1){ 26 | return NULL; 27 | } 28 | 29 | node* n = new node(d); 30 | n->left = buildTree(); 31 | n->right = buildTree(); 32 | 33 | return n; 34 | } 35 | 36 | void levelOrderPrint(node*root){ 37 | 38 | queue q; 39 | q.push(root); 40 | q.push(NULL); 41 | 42 | while(!q.empty()){ 43 | node* temp = q.front(); 44 | if(temp==NULL){ 45 | cout<data<<" "; 55 | 56 | if(temp->left){ 57 | q.push(temp->left); 58 | } 59 | if(temp->right){ 60 | q.push(temp->right); 61 | } 62 | } 63 | 64 | } 65 | return; 66 | } 67 | //ToDo : Complete the MaxSubset Function 68 | 69 | class Pair{ 70 | public: 71 | int inc; 72 | int exc; 73 | 74 | }; 75 | //O(N) 76 | Pair maxSubsetSum(node* root){ 77 | Pair p; 78 | if(root==NULL){ 79 | p.inc = p.exc = 0; 80 | return p; 81 | } 82 | 83 | Pair Left = maxSubsetSum(root->left); 84 | Pair Right = maxSubsetSum(root->right); 85 | 86 | p.inc = root->data + Left.exc + Right.exc; 87 | p.exc = max(Left.inc,Left.exc) + max(Right.inc,Right.exc); 88 | 89 | return p; 90 | } 91 | 92 | 93 | int main(){ 94 | 95 | node* root = buildTree(); 96 | levelOrderPrint(root); 97 | 98 | Pair p = maxSubsetSum(root); 99 | cout <<"Max Sum : "<< max(p.inc, p.exc) < 2 | #include 3 | using namespace std; 4 | 5 | bool isSafe(int mat[][9],int i,int j,int no){ 6 | 7 | 8 | //Check for row and col 9 | for(int k=0;k<9;k++){ 10 | if(mat[k][j]==no||mat[i][k]==no){ 11 | return false; 12 | } 13 | } 14 | //check for subgrid 15 | 16 | int sx = (i/3)*3; 17 | int sy = (j/3)*3; 18 | 19 | for(int x=sx; x 2 | using namespace std; 3 | 4 | 5 | class node{ 6 | public: 7 | node *left; //0 8 | node *right; // 1 9 | }; 10 | 11 | class trie{ 12 | node*root; 13 | 14 | public: 15 | trie(){ 16 | root = new node(); 17 | } 18 | 19 | void insert(int n){ 20 | //bits of that number in the trie 21 | node* temp = root; 22 | for(int i=31;i>=0;i--){ 23 | int bit = (n>>i)&1; 24 | if(bit==0){ 25 | if(temp->left==NULL){ 26 | temp->left = new node(); 27 | } 28 | //go to that node 29 | temp = temp->left; 30 | } 31 | else{ 32 | if(temp->right==NULL){ 33 | temp->right = new node(); 34 | } 35 | temp = temp->right; 36 | } 37 | } 38 | //Insertion is Done 39 | } 40 | 41 | int max_xor_helper(int value){ 42 | 43 | int current_ans = 0; 44 | node* temp = root; 45 | 46 | for(int j=31;j>=0;j--){ 47 | int bit =(value>>j)&1; 48 | 49 | if(bit==0){ 50 | //find the opp value 51 | if(temp->right!=NULL){ 52 | temp = temp->right; 53 | current_ans += (1<left; 57 | } 58 | } 59 | else{ 60 | //look for a zero 61 | if(temp->left!=NULL){ 62 | temp = temp->left; 63 | current_ans += (1<right; 67 | } 68 | } 69 | 70 | } 71 | return current_ans; 72 | 73 | } 74 | int max_xor(int *input,int n){ 75 | 76 | int max_xor = 0; 77 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Node{ 7 | public: 8 | int x; 9 | int y; 10 | int dist; 11 | 12 | Node(int x,int y,int dist){ 13 | this-> x = x; 14 | this->y = y; 15 | this->dist = dist; 16 | } 17 | }; 18 | 19 | //comparator should return boolean value, 20 | // indicating whether the element passed as 21 | // first argument is considered to go before the second in the specific strict weak ordering 22 | class Compare{ 23 | public: 24 | bool operator()(const Node &a,const Node &b){ 25 | return a.dist <= b.dist; 26 | } 27 | }; 28 | 29 | 30 | int shortest_path(vector > grid){ 31 | //return the shortest path len 32 | 33 | int m = grid.size(); 34 | int n = grid[0].size(); 35 | 36 | int i = 0; 37 | int j = 0; 38 | 39 | //2D vector to denote of each cell 40 | vector > dist(m+1, vector(n+1,INT_MAX)); 41 | 42 | dist[i][j] = grid[0][0]; 43 | set s; 44 | 45 | s.insert(Node(0,0,dist[0][0])); 46 | 47 | int dx[] = {0,0,1,-1}; 48 | int dy[] = {1,-1,0,0}; 49 | 50 | 51 | while(!s.empty()){ 52 | 53 | auto it = s.begin(); 54 | int cx = it->x; 55 | int cy = it->y; 56 | int cd = it->dist; 57 | s.erase(it); 58 | 59 | //update nbrs 60 | for(int k=0;k<4;k++){ 61 | int nx = cx + dx[k]; 62 | int ny = cy + dy[k]; 63 | 64 | if(nx>=0 and nx=0 and ny 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int key; 9 | Node *left; 10 | Node *right; 11 | 12 | Node(int key){ 13 | this->key = key; 14 | left = right = NULL; 15 | } 16 | }; 17 | 18 | Node* insert(Node * root, int key){ 19 | if(root==NULL){ 20 | return new Node(key); 21 | } 22 | 23 | //rec case 24 | if(key < root->key){ 25 | root->left = insert(root->left,key); 26 | } 27 | else{ 28 | root->right = insert(root->right,key); 29 | } 30 | return root; 31 | 32 | } 33 | 34 | 35 | 36 | void printInOrder(Node *root){ 37 | if(root==NULL){ 38 | return; 39 | } 40 | //left, root, right 41 | printInOrder(root->left); 42 | cout << root-> key <<" ,"; 43 | printInOrder(root->right); 44 | } 45 | 46 | 47 | //---------Next Inorder Successor 48 | 49 | Node * inorderSucc(Node * root, Node * target){ 50 | 51 | // If Right Subtree 52 | if(target->right!=NULL){ 53 | Node* temp = target->right; 54 | while(temp->left!=NULL){ 55 | temp = temp->left; 56 | } 57 | return temp; 58 | } 59 | 60 | 61 | // Otherwise 62 | Node * temp = root; 63 | Node * succ = NULL; 64 | 65 | while (temp!=NULL){ 66 | 67 | if(temp->key > target->key){ 68 | succ = temp; 69 | temp = temp->left; 70 | } 71 | else if(temp->key < target->key ){ 72 | temp = temp->right; 73 | } 74 | else{ 75 | break; 76 | } 77 | } 78 | return succ; 79 | } 80 | 81 | 82 | int main(){ 83 | 84 | Node * root = NULL; 85 | root = insert(root,8); 86 | root = insert(root,3); 87 | root = insert(root,10); 88 | root = insert(root,1); 89 | root = insert(root,6); 90 | root = insert(root,14); 91 | root = insert(root,4); 92 | root = insert(root,7); 93 | root = insert(root,13); 94 | 95 | //Test our Code 96 | Node* t1 = root->left->right->right; 97 | Node* t2 = root->right; 98 | 99 | cout<<"Inorder succ of 7 is" << inorderSucc(root,t1)->key <key < 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //Build a Prefix Tree - Trie 8 | class Node{ 9 | public: 10 | char data; 11 | unordered_map children; 12 | bool isTerminal; 13 | 14 | Node(char d){ 15 | data = d; 16 | isTerminal = false; 17 | } 18 | }; 19 | 20 | class Trie{ 21 | public: 22 | Node*root; 23 | 24 | Trie(){ 25 | root = new Node('\0'); 26 | } 27 | 28 | void insert(string word){ 29 | 30 | Node* temp = root; 31 | 32 | for(char ch : word){ 33 | 34 | if(temp->children.count(ch)==0){ 35 | Node *n = new Node(ch); 36 | temp->children[ch] = n; 37 | } 38 | temp = temp->children[ch]; 39 | } 40 | 41 | temp->isTerminal = true; 42 | } 43 | }; 44 | 45 | void searchHelper(Trie t, string document, int i, unordered_map &m ){ 46 | 47 | Node*temp = t.root; 48 | for(int j = i; j < document.length();j++){ 49 | char ch = document[j]; 50 | if(temp->children.count(ch)==0){ 51 | return; 52 | } 53 | temp = temp->children[ch]; 54 | if(temp->isTerminal){ 55 | //history part 56 | string out = document.substr(i,j-i+1); 57 | m[out] = true; 58 | } 59 | 60 | } 61 | return; 62 | 63 | } 64 | 65 | void documentSearch(string document, vector words){ 66 | 67 | //1. Create a trie of words 68 | Trie t; 69 | for(string w : words){ 70 | t.insert(w); 71 | } 72 | 73 | //2. Searching (Helper Fn) 74 | unordered_map m; 75 | for(int i=0;i words{"cute cat", "ttle", "cat","quick","big"}; 97 | 98 | documentSearch(document,words); 99 | 100 | 101 | return 0; 102 | } 103 | 104 | -------------------------------------------------------------------------------- /02 Strings/06 sort_strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sample Input 3 | ------------ 4 | 3 5 | 92 022 6 | 82 12 7 | 77 13 8 | 2 false numeric 9 | 10 | Sample Output 11 | ------------- 12 | 82 12 13 | 77 13 14 | 92 022 15 | 16 | */ 17 | #include 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | string extractStringAtKey(string str,int key){ 24 | 25 | //string tokeniser 26 | // hello how are you 27 | 28 | char *s = strtok( (char *)str.c_str(), " "); 29 | while(key>1){ 30 | s = strtok(NULL," "); 31 | key--; 32 | } 33 | return (string)s; 34 | } 35 | 36 | int convertToInt(string s){ 37 | 38 | int ans = 0; 39 | int p = 1; 40 | 41 | for(int i=s.length()-1; i>=0;i--){ 42 | ans += ((s[i]-'0')*p); 43 | p = p*10; 44 | } 45 | return ans; 46 | } 47 | 48 | bool lexicoCompare(pair s1, pair s2){ 49 | string key1, key2; 50 | key1 = s1.second; 51 | key2 = s2.second; 52 | return key1 < key2; 53 | } 54 | 55 | bool numericCompare(pair s1, pair s2){ 56 | string key1, key2; 57 | key1 = s1.second; 58 | key2 = s2.second; 59 | 60 | return convertToInt(key1) < convertToInt(key2); 61 | } 62 | 63 | 64 | 65 | int main(){ 66 | string s ="20 30 40 50"; 67 | 68 | 69 | int n; 70 | cin>>n; 71 | 72 | cin.get(); //consume the extra \n 73 | 74 | string temp; 75 | vector v; 76 | for(int i=0;i>key >> reversal >> ordering; 84 | 85 | 86 | //1. To extract keys for comparison & store them 87 | vector > vp; 88 | 89 | for(int i=0;i 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int key; 9 | Node *left; 10 | Node *right; 11 | 12 | Node(int key){ 13 | this->key = key; 14 | left = right = NULL; 15 | } 16 | }; 17 | 18 | Node* insert(Node * root, int key){ 19 | if(root==NULL){ 20 | return new Node(key); 21 | } 22 | 23 | //rec case 24 | if(key < root->key){ 25 | root->left = insert(root->left,key); 26 | } 27 | else{ 28 | root->right = insert(root->right,key); 29 | } 30 | return root; 31 | 32 | } 33 | 34 | 35 | 36 | void printInOrder(Node *root){ 37 | if(root==NULL){ 38 | return; 39 | } 40 | //left, root, right 41 | printInOrder(root->left); 42 | cout << root-> key <<" ,"; 43 | printInOrder(root->right); 44 | } 45 | 46 | 47 | //---------BST to Sorted Linked List 48 | class LinkedList{ 49 | public: 50 | Node * head; 51 | Node * tail; 52 | }; 53 | 54 | LinkedList tree2LL(Node * root){ 55 | 56 | LinkedList l; 57 | //base case 58 | if(root==NULL){ 59 | l.head = l.tail = NULL; 60 | return l; 61 | } 62 | 63 | //4 cases 64 | if(root->left==NULL and root->right==NULL){ 65 | l.head = l.tail = root; 66 | } 67 | else if(root->left!=NULL and root->right==NULL){ 68 | LinkedList leftLL = tree2LL(root->left); 69 | leftLL.tail->right = root; 70 | 71 | l.head = leftLL.head; 72 | l.tail = root; 73 | } 74 | else if(root->left==NULL and root->right!=NULL){ 75 | LinkedList rightLL = tree2LL(root->right); 76 | root->right = rightLL.head; 77 | 78 | l.head = root; 79 | l.tail = rightLL.tail; 80 | 81 | } 82 | else{ 83 | LinkedList leftLL = tree2LL(root->left); 84 | LinkedList rightLL = tree2LL(root->right); 85 | leftLL.tail->right = root; 86 | root->right = rightLL.head; 87 | 88 | l.head = leftLL.head; 89 | l.tail = rightLL.tail; 90 | } 91 | 92 | return l; 93 | } 94 | 95 | 96 | 97 | int main(){ 98 | 99 | Node * root = NULL; 100 | int arr[] = {8,3,10,1,6,14,4,7,13}; 101 | 102 | for(int x : arr){ 103 | root = insert(root,x); 104 | } 105 | //printInOrder(root); 106 | LinkedList l = tree2LL(root); 107 | 108 | Node * temp = l.head; 109 | while(temp!=NULL){ 110 | cout << temp->key <<"--> "; 111 | temp = temp->right; 112 | } 113 | 114 | 115 | return 0; 116 | } -------------------------------------------------------------------------------- /09 Binary Tree/root_2_leaft_paths.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class node{ 7 | 8 | public: 9 | int data; 10 | node*left; 11 | node*right; 12 | 13 | node(int d){ 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 21 | node* buildTree(){ 22 | 23 | int d; 24 | cin>>d; 25 | 26 | if(d==-1){ 27 | return NULL; 28 | } 29 | 30 | node* n = new node(d); 31 | n->left = buildTree(); 32 | n->right = buildTree(); 33 | 34 | return n; 35 | } 36 | 37 | void levelOrderPrint(node*root){ 38 | 39 | queue q; 40 | q.push(root); 41 | q.push(NULL); 42 | 43 | while(!q.empty()){ 44 | node* temp = q.front(); 45 | if(temp==NULL){ 46 | cout<data<<" "; 56 | 57 | if(temp->left){ 58 | q.push(temp->left); 59 | } 60 | if(temp->right){ 61 | q.push(temp->right); 62 | } 63 | } 64 | 65 | } 66 | return; 67 | } 68 | //=============================== 69 | //ToDo: Complete this Function | 70 | //=============================== 71 | void printRoot2LeafPaths(node* root, vector &path){ 72 | 73 | if(root==NULL){ 74 | return; 75 | } 76 | //end at leaft node, print the path 77 | if(root->left==NULL and root->right==NULL){ 78 | for(int data:path){ 79 | cout<"; 80 | } 81 | cout << root->data <<" "; 82 | cout<data); 86 | printRoot2LeafPaths(root->left,path); 87 | printRoot2LeafPaths(root->right,path); 88 | path.pop_back(); 89 | return; 90 | } 91 | 92 | int main(){ 93 | 94 | node* root = new node(1); 95 | root->left = new node(2); 96 | root->right = new node(3); 97 | root->left->left = new node(4); 98 | root->left->right = new node(5); 99 | root->right->right = new node(6); 100 | root->left->right->left = new node(7); 101 | root->left->right->right = new node(8); 102 | root->left->right->right->left = new node(9); 103 | root->left->right->right->right = new node(10); 104 | 105 | 106 | vector temp; 107 | printRoot2LeafPaths(root,temp); 108 | 109 | 110 | 111 | return 0; 112 | } -------------------------------------------------------------------------------- /17 LRU/LRU.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //Node to store the data (Linked List) 7 | class Node{ 8 | public: 9 | string key; 10 | int value; 11 | Node(string key,int value){ 12 | this->key = key; 13 | this->value = value; 14 | } 15 | }; 16 | 17 | 18 | //LRU Cache Data Structure 19 | class LRUCache{ 20 | public: 21 | int maxSize; 22 | list l; 23 | unordered_map::iterator > m; 24 | 25 | LRUCache(int maxSize){ 26 | this->maxSize = maxSize > 1 ? maxSize : 1; 27 | } 28 | 29 | void insertKeyValue(string key,int value){ 30 | //2 cases 31 | if(m.count(key)!=0){ 32 | //replace the old value and update 33 | auto it = m[key]; 34 | it-> value = value; 35 | } 36 | else{ 37 | //check if cache if full or not 38 | //remove the least recently used item from cache 39 | if(l.size()==maxSize){ 40 | Node last = l.back(); 41 | m.erase(last.key); //remove from hashmap 42 | l.pop_back(); //remove from linked list 43 | } 44 | 45 | Node n(key,value); 46 | l.push_front(n); 47 | m[key] = l.begin(); 48 | } 49 | } 50 | 51 | int* getValue(string key){ 52 | 53 | if(m.count(key)!=0){ 54 | auto it = m[key]; 55 | 56 | int value = it->value; 57 | l.push_front(*it); 58 | l.erase(it); 59 | m[key] = l.begin(); 60 | return &l.begin()->value; 61 | } 62 | return NULL; 63 | 64 | } 65 | 66 | string mostRecentKey(){ 67 | return l.front().key; 68 | } 69 | 70 | }; 71 | 72 | 73 | int main(){ 74 | LRUCache lru(3); 75 | lru.insertKeyValue("mango",10); 76 | lru.insertKeyValue("apple",20); 77 | lru.insertKeyValue("guava",30); 78 | cout << lru.mostRecentKey() < 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class node{ 8 | 9 | public: 10 | int data; 11 | node*left; 12 | node*right; 13 | 14 | node(int d){ 15 | data = d; 16 | left = NULL; 17 | right = NULL; 18 | } 19 | }; 20 | 21 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 22 | node* buildTree(){ 23 | 24 | int d; 25 | cin>>d; 26 | 27 | if(d==-1){ 28 | return NULL; 29 | } 30 | 31 | node* n = new node(d); 32 | n->left = buildTree(); 33 | n->right = buildTree(); 34 | 35 | return n; 36 | } 37 | 38 | void levelOrderPrint(node*root){ 39 | 40 | queue q; 41 | q.push(root); 42 | q.push(NULL); 43 | 44 | while(!q.empty()){ 45 | node* temp = q.front(); 46 | if(temp==NULL){ 47 | cout<data<<" "; 57 | 58 | if(temp->left){ 59 | q.push(temp->left); 60 | } 61 | if(temp->right){ 62 | q.push(temp->right); 63 | } 64 | } 65 | 66 | } 67 | return; 68 | } 69 | //=============================== 70 | //ToDo: Complete this Function | 71 | //=============================== 72 | 73 | //helper 74 | void traverseTree(node*root, int d, map > &m){ 75 | if(root==NULL){ 76 | return; 77 | } 78 | 79 | m[d].push_back(root->data); 80 | traverseTree(root->left, d-1,m); 81 | traverseTree(root->right,d+1,m); 82 | } 83 | 84 | void verticalOrderPrint(node* root){ 85 | 86 | map > m; 87 | int d = 0; 88 | 89 | traverseTree(root, d, m); 90 | 91 | //Keys are sorted (-2, -1,0,1,2,3.....) 92 | for(auto p:m){ 93 | int key = p.first; 94 | vector line = p.second; 95 | 96 | for(auto data : line){ 97 | cout << data <<" "; 98 | } 99 | cout <left = new node(2); 109 | root->right = new node(3); 110 | root->left->left = new node(4); 111 | root->left->right = new node(5); 112 | root->right->left = new node(6); 113 | root->right->right = new node(7); 114 | root->right->left->right = new node(8); 115 | root->right->right->right = new node(9); 116 | 117 | verticalOrderPrint(root); 118 | 119 | 120 | return 0; 121 | } -------------------------------------------------------------------------------- /09 Binary Tree/height_balanced.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class node{ 7 | 8 | public: 9 | int data; 10 | node*left; 11 | node*right; 12 | 13 | node(int d){ 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 21 | node* buildTree(){ 22 | 23 | int d; 24 | cin>>d; 25 | 26 | if(d==-1){ 27 | return NULL; 28 | } 29 | 30 | node* n = new node(d); 31 | n->left = buildTree(); 32 | n->right = buildTree(); 33 | 34 | return n; 35 | } 36 | 37 | void levelOrderPrint(node*root){ 38 | 39 | queue q; 40 | q.push(root); 41 | q.push(NULL); 42 | 43 | while(!q.empty()){ 44 | node* temp = q.front(); 45 | if(temp==NULL){ 46 | cout<data<<" "; 56 | 57 | if(temp->left){ 58 | q.push(temp->left); 59 | } 60 | if(temp->right){ 61 | q.push(temp->right); 62 | } 63 | } 64 | 65 | } 66 | return; 67 | } 68 | //=============================== 69 | //ToDo: Complete this Function | 70 | //=============================== 71 | 72 | // O(N) time 73 | pair isHeightBalanced(node *root){ 74 | 75 | pair p, Left, Right; 76 | 77 | if(root==NULL){ 78 | p.first = 0; //height 79 | p.second = true; // balanced 80 | return p; 81 | } 82 | 83 | //rec case (Postorder Traversal) 84 | Left = isHeightBalanced(root->left); 85 | Right = isHeightBalanced(root->right); 86 | 87 | int height = max(Left.first, Right.first) + 1; 88 | 89 | if(abs(Left.first - Right.first)<=1 and Left.second and Right.second){ 90 | return make_pair(height,true); 91 | } 92 | return make_pair(height,false); 93 | } 94 | 95 | 96 | 97 | int main(){ 98 | 99 | node* root = new node(1); 100 | root->left = new node(2); 101 | root->right = new node(3); 102 | root->left->left = new node(4); 103 | root->left->right = new node(5); 104 | root->right->right = new node(6); 105 | root->left->right->left = new node(7); 106 | root->left->right->right = new node(8); 107 | //root->left->right->right->left = new node(9); 108 | //root->left->right->right->right = new node(10); 109 | 110 | pair p = isHeightBalanced(root); 111 | if(p.second){ 112 | cout << "Yes, its height balanced"; 113 | } 114 | else{ 115 | cout << "Not a height balanced tree"; 116 | } 117 | 118 | 119 | return 0; 120 | } -------------------------------------------------------------------------------- /09 Binary Tree/level_order_build.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node*left; 10 | node*right; 11 | 12 | node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 20 | node* buildTree(){ 21 | 22 | int d; 23 | cin>>d; 24 | 25 | if(d==-1){ 26 | return NULL; 27 | } 28 | 29 | node* n = new node(d); 30 | n->left = buildTree(); 31 | n->right = buildTree(); 32 | 33 | return n; 34 | } 35 | /*Level Order Traversal 36 | Expected Output 37 | 38 | 1 39 | 2 3 40 | 4 5 6 41 | 7 42 | */ 43 | 44 | void levelOrderPrint(node*root){ 45 | 46 | queue q; 47 | q.push(root); 48 | q.push(NULL); 49 | 50 | while(!q.empty()){ 51 | node* temp = q.front(); 52 | if(temp==NULL){ 53 | cout<data<<" "; 63 | 64 | if(temp->left){ 65 | q.push(temp->left); 66 | } 67 | if(temp->right){ 68 | q.push(temp->right); 69 | } 70 | } 71 | 72 | } 73 | return; 74 | } 75 | 76 | /* Implement Level Order Build 77 | for the tree 78 | */ 79 | 80 | node* levelOrderBuild(){ 81 | 82 | int d; 83 | cin>>d; 84 | 85 | node* root = new node(d); 86 | 87 | queue q; 88 | q.push(root); 89 | 90 | 91 | while(!q.empty()){ 92 | node* current = q.front(); 93 | q.pop(); 94 | 95 | int c1, c2; 96 | cin>> c1 >> c2; 97 | 98 | if(c1!=-1){ 99 | current->left = new node(c1); 100 | q.push(current->left); 101 | } 102 | if(c2!=-1){ 103 | current->right = new node(c2); 104 | q.push(current->right); 105 | } 106 | } 107 | return root; 108 | } 109 | 110 | //Todo: Replace with Descendant Sum leaving leaf nodes intact 111 | int replaceWithSum(node *root){ 112 | //base case 113 | if(root==NULL){ 114 | return 0; 115 | } 116 | if(root->left==NULL and root->right==NULL){ 117 | return root->data; 118 | } 119 | //recursive case 120 | int LS = replaceWithSum(root->left); 121 | int RS = replaceWithSum(root->right); 122 | 123 | int temp = root->data; 124 | root->data = LS + RS; 125 | return root->data + temp; 126 | } 127 | 128 | int main(){ 129 | 130 | //node* root = buildTree(); 131 | node* root = levelOrderBuild(); 132 | levelOrderPrint(root); 133 | cout< 2 | #include 3 | using namespace std; 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node*left; 10 | node*right; 11 | 12 | node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 20 | node* buildTree(){ 21 | 22 | int d; 23 | cin>>d; 24 | 25 | if(d==-1){ 26 | return NULL; 27 | } 28 | 29 | node* n = new node(d); 30 | n->left = buildTree(); 31 | n->right = buildTree(); 32 | 33 | return n; 34 | } 35 | /* Todo: Implement Level Order Traversal 36 | Expected Output 37 | 38 | 1 39 | 2 3 40 | 4 5 6 41 | 7 42 | */ 43 | 44 | void levelOrderPrint(node*root){ 45 | 46 | queue q; 47 | q.push(root); 48 | q.push(NULL); 49 | 50 | while(!q.empty()){ 51 | node* temp = q.front(); 52 | if(temp==NULL){ 53 | cout<data<<" "; 63 | 64 | if(temp->left){ 65 | q.push(temp->left); 66 | } 67 | if(temp->right){ 68 | q.push(temp->right); 69 | } 70 | } 71 | 72 | } 73 | return; 74 | } 75 | //Helper Function : Height of the Tree 76 | int height(node*root){ 77 | if(root==NULL){ 78 | return 0; 79 | } 80 | int h1 = height(root->left); 81 | int h2 = height(root->right); 82 | return 1 + max(h1,h2); 83 | } 84 | 85 | // Diameter 86 | // Time Complexity? 87 | int diameter(node*root){ 88 | //base case 89 | if(root==NULL){ 90 | return 0; 91 | } 92 | 93 | //rec case 94 | int D1 = height(root->left) + height(root->right); 95 | int D2 = diameter(root->left); 96 | int D3 = diameter(root->right); 97 | 98 | return max(D1,max(D2,D3)); 99 | } 100 | 101 | //---------Diameter Optimised 102 | class HDPair{ 103 | public: 104 | int height; 105 | int diameter; 106 | }; 107 | 108 | HDPair optDiameter(node*root){ 109 | HDPair p; 110 | 111 | if(root==NULL){ 112 | p.height = p.diameter = 0; 113 | return p; 114 | } 115 | 116 | //otherwise 117 | HDPair Left = optDiameter(root->left); 118 | HDPair Right = optDiameter(root->right); 119 | 120 | p.height = max(Left.height,Right.height) + 1; 121 | 122 | int D1 = Left.height + Right.height; 123 | int D2 = Left.diameter; 124 | int D3 = Right.diameter; 125 | 126 | p.diameter = max(D1,max(D2,D3)); 127 | return p; 128 | } 129 | 130 | 131 | 132 | int main(){ 133 | 134 | node* root = buildTree(); 135 | levelOrderPrint(root); 136 | cout << "Diameter is "< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #define M 3 7 | #define N 4 8 | 9 | 10 | class Node{ 11 | public: 12 | char s; 13 | unordered_map children; 14 | string word; 15 | bool isTerminal; 16 | 17 | Node(char s){ 18 | this->s = s; 19 | isTerminal = false; 20 | word = ""; 21 | } 22 | }; 23 | 24 | class Trie{ 25 | public: 26 | Node*root; 27 | 28 | Trie(){ 29 | root = new Node('\0'); 30 | } 31 | 32 | void addWord(string word){ 33 | 34 | Node * temp = root; 35 | for(auto ch : word){ 36 | if(temp->children.count(ch)==0){ 37 | temp->children[ch] = new Node(ch); 38 | } 39 | temp = temp->children[ch]; 40 | } 41 | //last node 42 | temp->isTerminal = true; 43 | temp->word = word; 44 | } 45 | }; 46 | 47 | 48 | //main algorithm (8-way dfs + trie guided search) 49 | 50 | void dfs(char board[M][N],Node *node,int i,int j,bool visited[][N], unordered_set &output){ 51 | 52 | //base case 53 | char ch = board[i][j]; 54 | if(node->children.count(ch)==0){ 55 | return; 56 | } 57 | 58 | //otherwise trie contains this node 59 | visited[i][j] = true; 60 | node = node->children[ch]; 61 | 62 | 63 | // if it is a terminal node in the trie 64 | if(node->isTerminal){ 65 | output.insert(node->word); 66 | } 67 | 68 | //explore the neigbours 69 | int dx[] = {0, 1 , 1 ,1, 0, -1, -1,-1}; 70 | int dy[] = {-1,-1, 0, 1, 1, 1, 0, -1}; 71 | 72 | for(int k=0;k<8;k++){ 73 | 74 | int ni = i + dx[k]; 75 | int nj = j + dy[k]; 76 | 77 | //if it is in bounds and is not visited 78 | if(ni>=0 and nj>=0 and ni < M and nj < N and !visited[ni][nj]){ 79 | dfs(board,node,ni,nj,visited,output); 80 | } 81 | } 82 | //last step (backtracking) 83 | visited[i][j] = false; 84 | return; 85 | } 86 | 87 | 88 | int main() { 89 | 90 | 91 | 92 | string words[] = {"SNAKE", "FOR", "QUEZ", "SNACK", "SNACKS", "GO","TUNES","CAT"}; 93 | 94 | char board[M][N] = { { 'S', 'E', 'R' ,'T'}, 95 | { 'U', 'N', 'K' ,'S'}, 96 | { 'T', 'C', 'A' ,'T'} }; 97 | 98 | //1. Trie 99 | 100 | Trie t; 101 | for(auto w : words){ 102 | t.addWord(w); 103 | } 104 | 105 | //2. Take a container to store words that are found in dfs search 106 | unordered_set output; 107 | 108 | 109 | //3. Step (8-DFS Search from every cell) 110 | bool visited[M][N] = {0}; 111 | 112 | 113 | for(int i=0; i 2 | #include 3 | using namespace std; 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node*left; 10 | node*right; 11 | 12 | node(int d){ 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | //Input : 1 2 4 -1 -1 5 7 -1 -1 -1 3 -1 6 -1 -1 20 | node* buildTree(){ 21 | 22 | int d; 23 | cin>>d; 24 | 25 | if(d==-1){ 26 | return NULL; 27 | } 28 | 29 | node* n = new node(d); 30 | n->left = buildTree(); 31 | n->right = buildTree(); 32 | 33 | return n; 34 | } 35 | 36 | void levelOrderPrint(node*root){ 37 | 38 | queue q; 39 | q.push(root); 40 | q.push(NULL); 41 | 42 | while(!q.empty()){ 43 | node* temp = q.front(); 44 | if(temp==NULL){ 45 | cout<data<<" "; 55 | 56 | if(temp->left){ 57 | q.push(temp->left); 58 | } 59 | if(temp->right){ 60 | q.push(temp->right); 61 | } 62 | } 63 | 64 | } 65 | return; 66 | } 67 | //=============================== 68 | //ToDo: Complete this Function | 69 | //=============================== 70 | void printAtLevelK(node*root, int k){ 71 | if(root==NULL){ 72 | return; 73 | } 74 | if(k==0){ 75 | cout<data<<" "; 76 | return; 77 | } 78 | printAtLevelK(root->left,k-1); 79 | printAtLevelK(root->right,k-1); 80 | return; 81 | } 82 | 83 | 84 | int printNodesAtDistanceK(node* root, node* target,int k){ 85 | 86 | //base case 87 | if(root==NULL){ 88 | return -1; 89 | } 90 | 91 | //reach the target node 92 | if(root==target){ 93 | printAtLevelK(target,k); 94 | return 0; 95 | } 96 | 97 | 98 | //other case 99 | int DL = printNodesAtDistanceK(root->left,target,k); 100 | if(DL!=-1){ 101 | 102 | //2 cases 103 | // Print the current node 104 | if(DL + 1 ==k){ 105 | cout << root->data; 106 | } 107 | // or print somenodes in the rightsubtree 108 | else{ 109 | printAtLevelK(root->right,k-2-DL); 110 | } 111 | return 1 + DL; 112 | } 113 | int DR = printNodesAtDistanceK(root->right,target,k); 114 | if(DR!=-1){ 115 | //2 cases 116 | //print current node 117 | if(DR + 1 ==k){ 118 | cout<< root->data <<" "; 119 | } 120 | else{ 121 | printAtLevelK(root->left,k-2-DR); 122 | } 123 | return 1 + DR; 124 | } 125 | return -1; 126 | } 127 | 128 | int main(){ 129 | 130 | node* root = new node(1); 131 | root->left = new node(2); 132 | root->right = new node(3); 133 | root->left->left = new node(4); 134 | root->left->right = new node(5); 135 | root->right->right = new node(6); 136 | root->left->right->left = new node(7); 137 | root->left->right->right = new node(8); 138 | root->left->right->right->left = new node(9); 139 | root->left->right->right->right = new node(10); 140 | 141 | //Target Node 5 142 | node* target = root->left->right; 143 | 144 | 145 | int k = 2; 146 | printNodesAtDistanceK(root,target,k); 147 | cout< 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | int data; 7 | node* next; 8 | 9 | node(int data){ 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }; 14 | //----------Linked List-----------// 15 | void insertAtHead(node * &head,int data){ 16 | if(head==NULL){ 17 | head = new node(data); 18 | return; 19 | } 20 | //otherwise 21 | node * n = new node(data); 22 | n->next = head; 23 | head = n; 24 | } 25 | 26 | void insertInMiddle(node* &head, int data, int pos){ 27 | if(pos==0){ 28 | insertAtHead(head,data); 29 | } 30 | 31 | else{ 32 | node * temp = head; 33 | for(int jump=1;jump<=pos-1;jump++){ 34 | temp = temp->next; 35 | } 36 | 37 | node * n = new node(data); 38 | n->next = temp->next; 39 | temp->next = n; 40 | 41 | } 42 | } 43 | 44 | node* recReverse(node *head){ 45 | //base case 46 | if(head==NULL or head->next==NULL){ 47 | return head; 48 | } 49 | //otherwise 50 | node* sHead = recReverse(head->next); 51 | head->next->next = head; 52 | head->next = NULL; 53 | return sHead; 54 | } 55 | 56 | void reverse(node *&head){ 57 | node* prev = NULL; 58 | node* current = head; 59 | node * temp; 60 | 61 | while(current!=NULL){ 62 | //store next 63 | temp = current->next; 64 | //update the current 65 | current->next = prev; 66 | 67 | //prev and current 68 | prev = current; 69 | current = temp; 70 | } 71 | 72 | head = prev; 73 | return; 74 | } 75 | 76 | 77 | node* kReverse(node *head,int k){ 78 | //base case 79 | if(head==NULL){ 80 | return NULL; 81 | } 82 | 83 | //reverse the first k nodes 84 | node* prev = NULL; 85 | node* current = head; 86 | node * temp; 87 | int cnt = 1; 88 | 89 | while(current!=NULL and cnt<=k){ 90 | //store next 91 | temp = current->next; 92 | //update the current 93 | current->next = prev; 94 | 95 | //prev and current 96 | prev = current; 97 | current = temp; 98 | cnt++; 99 | } 100 | 101 | if(temp!=NULL){ 102 | head->next = kReverse(temp,k); 103 | } 104 | return prev; 105 | } 106 | 107 | node* merge(node *a, node* b){ 108 | //Complete this method 109 | //base case 110 | if(a==NULL){ 111 | return b; 112 | } 113 | if(b==NULL){ 114 | return a; 115 | } 116 | 117 | //rec case 118 | node * c; 119 | 120 | if(a->data < b->data){ 121 | c = a; 122 | c->next = merge(a->next,b); 123 | } 124 | else{ 125 | c = b; 126 | c->next = merge(a,b->next); 127 | } 128 | return c; 129 | } 130 | 131 | node* midPoint(node *head){ 132 | 133 | node * slow = head; 134 | node * fast = head->next; 135 | 136 | while(fast!=NULL and fast->next!=NULL){ 137 | slow = slow->next; 138 | fast = fast->next->next; 139 | } 140 | return slow; 141 | } 142 | 143 | 144 | //ToDo : MergeSort 145 | node* mergeSort(node * head){ 146 | //base case 147 | if(head==NULL or head->next==NULL){ 148 | return head; 149 | } 150 | 151 | //rec case 152 | node * mid = midPoint(head); 153 | 154 | //Break at the mid 155 | node * a = head; 156 | node * b = mid->next; 157 | mid->next = NULL; 158 | 159 | //Recursive Sort 160 | a = mergeSort(a); 161 | b = mergeSort(b); 162 | 163 | //Merge 164 | return merge(a,b); 165 | 166 | } 167 | 168 | 169 | void printLL(node * head){ 170 | 171 | while(head!=NULL){ 172 | cout <data <<"-->"; 173 | head = head->next; 174 | } 175 | cout < 5 -> 7 -> 10 -> NULL 198 | // 2 , 3, 6 199 | /* 200 | node* a = NULL; 201 | insertAtHead(a,10); 202 | insertAtHead(a,7); 203 | insertAtHead(a,5); 204 | insertAtHead(a,1); 205 | 206 | node* b = NULL; 207 | insertAtHead(b,6); 208 | insertAtHead(b,3); 209 | insertAtHead(b,2); 210 | 211 | node* head = merge(a,b); 212 | printLL(head); 213 | */ 214 | 215 | /* 216 | node* head = NULL; 217 | insertAtHead(head,4); 218 | insertAtHead(head,3); 219 | insertAtHead(head,2); 220 | insertAtHead(head,1); 221 | insertAtHead(head,0); 222 | printLL(head); 223 | head = kReverse(head,3); 224 | printLL(head);*/ 225 | 226 | return 0; 227 | } --------------------------------------------------------------------------------