├── .gitignore ├── Chapter 3 - Stacks and Queues ├── Sort Stack │ ├── sort_stack.py │ └── sort_stack.cpp ├── Queue Via Stacks │ ├── queue_via_one_stack.py │ ├── queue_via_stacks.py │ ├── queue_via_stacks.cpp │ └── queue_via_one_stack.cpp ├── Stack Min │ ├── stack_min.py │ └── stack_min.cpp ├── Animal Shelter │ ├── animal_shelter.py │ └── animal_shelter.cpp ├── Three in One │ ├── three_in_one.py │ └── three_in_one.cpp └── Stack Of Plates │ ├── stack_of_plates.py │ └── stack_of_plates.cpp ├── Chapter 1 - Arrays and Strings ├── String Rotation │ ├── string_rotation.py │ └── string_rotation.cpp ├── URLify │ ├── urlify.py │ └── urlify.cpp ├── Check Permutation │ ├── check_permutation.py │ └── check_permutation.cpp ├── Rotate Matrix │ ├── rotate_matrix.py │ └── rotate_matrix.cpp ├── Is Unique │ ├── is_unique.py │ └── is_unique.cpp ├── String Compression │ ├── string_compression.py │ └── string_compression.cpp ├── One Away │ ├── one_away.py │ └── one_away.cpp ├── Zero Matrix │ ├── zero_matrix.py │ ├── zero_matrix_v1.cpp │ └── zero_matrix.cpp ├── Palindrome Permutation │ ├── palindrome_permutation.py │ └── palindrome_permutation.cpp └── Readme.md ├── Miscellaneous ├── Readme.md ├── root_to_leaf_paths_equal_to_sum.cpp ├── diameter_of_binary_tree.cpp ├── reverse_levelOrderTraversal.cpp ├── identical_trees.cpp ├── height_of_binary_tree.cpp ├── root_to_leaf_paths.cpp ├── max_in_binary_tree.cpp ├── count_nodes.cpp ├── search_in_binary_tree.cpp ├── max_sum_per_level_binary_tree.cpp ├── convert_tree_to_mirror.cpp ├── number_of_leaves.cpp ├── tree_traversals.cpp ├── path_with_given_sum.cpp ├── insert_in_binary_tree.cpp ├── delete_node.cpp └── tree_traversals_non_recursive.cpp ├── Chapter 2 - Linked Lists ├── Delete Middle node │ ├── delete_middle_node.py │ └── delete_middle_node.cpp ├── Return Kth To Last │ ├── return_kth_to_last.py │ └── return_kth_to_last.cpp ├── Sum Lists │ ├── sum_lists_backward.py │ ├── sum_lists_forward1.cpp │ ├── sum_lists_backward.cpp │ └── sum_lists_forward.cpp ├── Partition │ ├── partition.py │ └── partition.cpp ├── Loop Detection │ ├── loop_detection.py │ ├── loop_detection_removal.py │ ├── loop_detection.cpp │ └── loop_detection_removal.cpp ├── Palindrome │ ├── palindrome.py │ └── palindrome.cpp ├── Remove Dups │ ├── remove_dups.py │ └── remove_dups.cpp └── Intersection │ ├── intersection.py │ └── intersection.cpp └── Readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Sort Stack/sort_stack.py: -------------------------------------------------------------------------------- 1 | def sort_stack(s1): 2 | s2 = [] 3 | while not s1 == []: 4 | current = s1.pop() 5 | while not s2 == [] and s2[-1] > current: 6 | s1.append(s2.pop()) 7 | s2.append(current) 8 | return s2 9 | print(sort_stack([10, 4, 3, 8, 2])) -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/String Rotation/string_rotation.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/5TAL2ZXgXN 2 | if __name__ == "__main__": 3 | a = str(input()) 4 | b = str(input()) 5 | if len(a) < 0 or len(b) < 0 or len(a) != len(b): 6 | print("b !substring of a") 7 | a += a 8 | if b in a: print("b is substring of a") 9 | else: print("b !substring of a") -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/URLify/urlify.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #https://ide.geeksforgeeks.org/0sYLKxGN46 4 | def urlify(mystr, length): 5 | if mystr is None or mystr is "" or len is None: 6 | return None 7 | 8 | url = [] 9 | for i in range(length): 10 | if mystr[i] == " ": 11 | url.append("%20") 12 | else: 13 | url.append(mystr[i]) 14 | return ''.join(url) 15 | 16 | if __name__ == "__main__": 17 | catch = urlify("Mr John Smith ", 13) 18 | if catch is not None: 19 | print(catch) 20 | else: 21 | print("Invalid string literal") -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Queue Via Stacks/queue_via_one_stack.py: -------------------------------------------------------------------------------- 1 | #incorrect solution.. 2 | class Queue: 3 | def __init__(self): 4 | self.s1 = [] 5 | 6 | def enqueue(self, data): 7 | self.s1.append(data) 8 | 9 | def dequeue(self): 10 | if self.s1 == []: 11 | print("Empty stack..!") 12 | return None 13 | res = self.s1.pop() 14 | item = self.dequeue() 15 | self.s1.append(res) 16 | return item 17 | 18 | if __name__ == "__main__": 19 | qs = Queue() 20 | qs.enqueue(10) 21 | qs.enqueue(20) 22 | qs.enqueue(30) 23 | print(qs.dequeue()) 24 | print(qs.dequeue()) 25 | print(qs.dequeue()) -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Queue Via Stacks/queue_via_stacks.py: -------------------------------------------------------------------------------- 1 | class Queue: 2 | def __init__(self): 3 | self.s1, self.s2 = [], [] 4 | 5 | def enqueue(self, data): 6 | self.s1.append(data) 7 | 8 | def dequeue(self): 9 | if self.s1 == [] and self.s2 == []: 10 | return None 11 | if self.s2 == []: 12 | while not self.s1 == []: 13 | self.s2.append(self.s1.pop()) 14 | res = self.s2.pop() 15 | return res 16 | 17 | if __name__ == "__main__": 18 | qs = Queue() 19 | qs.enqueue(10) 20 | qs.enqueue(20) 21 | qs.enqueue(30) 22 | print(qs.dequeue()) 23 | print(qs.dequeue()) 24 | print(qs.dequeue()) -------------------------------------------------------------------------------- /Miscellaneous/Readme.md: -------------------------------------------------------------------------------- 1 | # Problems: 2 | 3 | * Tree Traversals :- PreOrder, InOrder, PostOrder and LevelOrder 4 | * Max Element in Binary Tree 5 | * Search in Binary Tree 6 | * Insert in Binary Tree 7 | * Count Nodes in Binary Tree 8 | * Reverse Level Order Traversal of Binary Tree 9 | * Height of Binary Tree (Non-recursive) 10 | * Delete Node in Binary Tree + (--Find deepest node in Binary Tree--) 11 | * Count number of leaf nodes + (--Full Nodes--) + (--Half Nodes--) 12 | * Check if two Binary Trees are identical 13 | * Diameter of Binary Tree 14 | * Find level having maximum sum in Binary Tree 15 | * Find all root to leaf paths in Binary Tree 16 | * Find if path with given sum exists in Binary Tree 17 | * Convert Binary tree to its mirror + (--Check mirror--) 18 | -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Delete Middle node/delete_middle_node.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | #Assuming the fact that last node cannot be deleted 7 | def delMiddleNode(mid): 8 | if mid.next == None: 9 | return 10 | temp = mid.next 11 | mid.data = temp.data 12 | mid.next = temp.next 13 | 14 | def printLL(node): 15 | while node != None: 16 | if node.next != None: 17 | print(str(node.data), end=' ') 18 | node = node.next 19 | 20 | 21 | if __name__ == "__main__": 22 | a = Node(1) 23 | b = Node(2) 24 | mid = Node(3) 25 | d = Node(4) 26 | e = Node(5) 27 | f = Node(6) 28 | 29 | a.next = b 30 | b.next = mid 31 | mid.next = d 32 | d.next = e 33 | e.next = f 34 | 35 | print("Original list:") 36 | printLL(a) 37 | print("\nAfter deleting the middle node:") 38 | delMiddleNode(mid) 39 | printLL(a) -------------------------------------------------------------------------------- /Miscellaneous/root_to_leaf_paths_equal_to_sum.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/bEmseDwEzG 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | bool pathWithGivenSumRec(Node *root, int sum){ 17 | if(root == NULL) return false; 18 | if(sum == root->data && root->left == NULL && root->right == NULL) 19 | return true; 20 | return pathWithGivenSumRec(root->left, sum - root->data) || pathWithGivenSumRec(root->right, sum - root->data); 21 | } 22 | 23 | int main(){ 24 | Node *root = newNode(1); 25 | root->left = newNode(2); 26 | root->right = newNode(3); 27 | root->left->left = newNode(4); 28 | root->left->right = newNode(5); 29 | root->right->left = newNode(6); 30 | root->right->right = newNode(7); 31 | cout< 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | int height(Node *root){ 17 | if(root == NULL) return 0; 18 | return(1 + max(height(root->left), height(root->right))); 19 | } 20 | 21 | int diameter(Node *root){ 22 | if(root == NULL)return 0; 23 | int lheight = height(root->left); 24 | int rheight = height(root->right); 25 | int ldiam = diameter(root->left); 26 | int rdiam = diameter(root->right); 27 | return max(lheight + rheight + 1, max(ldiam, rdiam)); 28 | } 29 | 30 | int main(){ 31 | Node *root = newNode(1); 32 | root->left = newNode(2); 33 | root->right = newNode(3); 34 | root->left->left = newNode(4); 35 | root->left->right = newNode(5); 36 | root->right->left = newNode(6); 37 | root->right->right = newNode(7); 38 | cout< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | void reverse_levelOrderTraversal(Node *root) 17 | { 18 | if(root == NULL)return; 19 | queue q; stack s; 20 | q.push(root); 21 | while(q.empty() == false){ 22 | Node* current = q.front(); 23 | s.push(current); 24 | q.pop(); 25 | if(current->left!=NULL){ 26 | q.push(current->left); 27 | } 28 | if(current->right!=NULL){ 29 | q.push(current->right); 30 | } 31 | } 32 | while(!s.empty()){ 33 | cout<data<<" "; 34 | s.pop(); 35 | } 36 | } 37 | 38 | int main(){ 39 | Node *root = newNode(1); 40 | root->left = newNode(2); 41 | root->right = newNode(3); 42 | root->left->left = newNode(4); 43 | root->left->right = newNode(5); 44 | reverse_levelOrderTraversal(root); 45 | 46 | } -------------------------------------------------------------------------------- /Miscellaneous/identical_trees.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/oETCC5zcyp 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | bool isIdentical(Node *t1, Node *t2){ 17 | if(t1 == NULL && t2 == NULL) return true; 18 | if(t1 == NULL || t2 == NULL) return false; 19 | return t1->data == t2->data && isIdentical(t1->left, t2->left) && isIdentical(t1->right, t2->right); 20 | } 21 | 22 | int main(){ 23 | Node *root = newNode(1); 24 | root->left = newNode(2); 25 | root->right = newNode(3); 26 | root->left->left = newNode(4); 27 | root->left->right = newNode(5); 28 | root->right->left = newNode(6); 29 | root->right->right = newNode(7); 30 | 31 | Node *root1 = newNode(1); 32 | root1->left = newNode(2); 33 | root1->right = newNode(3); 34 | root1->left->left = newNode(4); 35 | root1->left->right = newNode(5); 36 | root1->right->left = newNode(6); 37 | root1->right->right = newNode(7); 38 | cout< 0: 30 | s = input().split(" ") 31 | print(s[0], s[1]) 32 | if check_permutation_hashed(s[0], s[1]): 33 | print("Yes, equal") 34 | else: 35 | print("No, not equal") 36 | 37 | if check_permutation_sorted(s[0], s[1]): 38 | print("Yes, equal") 39 | else: 40 | print("No, not equal") 41 | tc -= 1 -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Rotate Matrix/rotate_matrix.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/mmXcbJQgMV 2 | def print_mat(cp_my_ip): 3 | for i in range(len(cp_my_ip)): 4 | for j in range(len(cp_my_ip[0])): 5 | print(cp_my_ip[i][j], end = ' ') 6 | print() 7 | 8 | def rotate_matrix(cp_my_ip): 9 | n = len(cp_my_ip) 10 | level, first, last = 0, 0, 0 11 | for level in range(n//2): #n/2 --> for 4x4 cp_my_ip, it will have 2 layers 12 | first = level 13 | last = n - first - 1 14 | for element in range(first, last): 15 | offset = element - first 16 | topleft = cp_my_ip[first][element] 17 | topright = cp_my_ip[element][last] 18 | bottomright = cp_my_ip[last][last - offset] 19 | bottomleft = cp_my_ip[last - offset][first] 20 | cp_my_ip[first][element] = bottomleft 21 | cp_my_ip[element][last] = topleft 22 | cp_my_ip[last][last - offset] = topright 23 | cp_my_ip[last - offset][first] = bottomright 24 | #shifting the col value to its pos, since its a clockwise rotation so, seven will be at 1 25 | print_mat(cp_my_ip) 26 | 27 | if __name__ == "__main__": 28 | rotate_matrix([[1,2,3],[4,5,6],[7,8,9]]) -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Return Kth To Last/return_kth_to_last.py: -------------------------------------------------------------------------------- 1 | class Node(): 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | class LinkedList(): 7 | def __init__(self): 8 | self.head = None 9 | 10 | def push(self, data): 11 | new_node = Node(data) 12 | new_node.next = self.head 13 | self.head = new_node 14 | 15 | def printLL(self): 16 | curr = self.head 17 | if curr is None: return 18 | while curr is not None: 19 | print(curr.data, end = ' ') 20 | curr = curr.next 21 | 22 | def returnkthToLast(self, k): 23 | curr = self.head 24 | if curr is None: return 25 | walker = curr 26 | runner = curr 27 | for i in range(k): 28 | if(not walker): #out of bounds 29 | return 30 | walker = walker.next 31 | while(walker): 32 | walker = walker.next 33 | runner = runner.next 34 | return runner.data 35 | 36 | if __name__ == "__main__": 37 | ll1 = LinkedList() 38 | k = int(input()) 39 | nodes = map(int, input().split()) 40 | for node in nodes: 41 | ll1.push(node) 42 | ll1.printLL() 43 | print("\nKth node from last is:" + str(ll1.returnkthToLast(k))) -------------------------------------------------------------------------------- /Miscellaneous/height_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/v9qf5xVojm 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | //Non-recursive 17 | void heightOfTree(Node *root){ 18 | if(root == NULL)return; 19 | queue q; 20 | q.push(root); 21 | q.push(NULL); 22 | int height = 1; 23 | while(!q.empty()){ 24 | Node *curr = q.front(); 25 | q.pop(); 26 | if(curr == NULL){ 27 | if(!q.empty()){ 28 | q.push(NULL); 29 | height++; 30 | } 31 | } 32 | else{ 33 | if(curr->left) 34 | q.push(curr->left); 35 | if(curr->right) 36 | q.push(curr->right); 37 | } 38 | } 39 | cout<left = newNode(2); 45 | root->right = newNode(3); 46 | root->left->left = newNode(4); 47 | root->left->right = newNode(5); 48 | root->right->left = newNode(6); 49 | root->right->right = newNode(7); 50 | heightOfTree(root); 51 | } -------------------------------------------------------------------------------- /Miscellaneous/root_to_leaf_paths.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/6VVrDyB2s4 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | void printPath(int paths[], int len){ 17 | for(int i=0; idata; 25 | len++; 26 | if(root->left == NULL and root->right == NULL) 27 | printPath(paths, len); 28 | else{ 29 | rootToLeafPaths(root->left, paths, len); 30 | rootToLeafPaths(root->right, paths, len); 31 | } 32 | } 33 | 34 | void wrapper(Node *root){ 35 | if(root == NULL) return; 36 | int paths[1000]; 37 | int len = 0; 38 | rootToLeafPaths(root, paths, len); 39 | } 40 | 41 | 42 | int main(){ 43 | Node *root = newNode(1); 44 | root->left = newNode(2); 45 | root->right = newNode(3); 46 | root->left->left = newNode(4); 47 | root->left->right = newNode(5); 48 | root->right->left = newNode(6); 49 | root->right->right = newNode(7); 50 | wrapper(root); 51 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Sum Lists/sum_lists_backward.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/v63gM4frIH 2 | class Node: 3 | def __init__(self, data, next = None): 4 | self.data, self.next = data, next 5 | 6 | def printLL(head): 7 | temp = head 8 | while(temp): 9 | print(temp.data, end = ' ') 10 | temp = temp.next 11 | 12 | def countLL(head): 13 | curr, count = head, 0 14 | while(curr): 15 | count += 1 16 | curr = curr.next 17 | return count 18 | 19 | def sum_lists(head1, head2): 20 | if head1 is None or head2 is None: 21 | return None 22 | 23 | temp = prev = result = None 24 | carry = 0 25 | 26 | while head1 or head2 or carry: 27 | sum_ = carry 28 | if head1: 29 | sum_ += head1.data 30 | head1 = head1.next 31 | if head2: 32 | sum_ += head2.data 33 | head2 = head2.next 34 | 35 | if result: 36 | result.next = Node(sum_ % 10) 37 | result = result.next 38 | else: 39 | result = Node(sum_ % 10) 40 | temp = result 41 | 42 | carry = sum_ // 10 43 | return temp 44 | 45 | 46 | if __name__ == "__main__": 47 | num1 = Node(1,Node(2,Node(3))) 48 | num2 = Node(4,Node(9,Node(5))) 49 | result = sum_lists(num1, num2) 50 | printLL(result) -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Partition/partition.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | class LinkedList: 7 | def __init__(self): 8 | self.head = None 9 | 10 | def push(self, new_data): 11 | new_node = Node(new_data) 12 | new_node.next = self.head 13 | self.head = new_node 14 | 15 | def printLL(self): 16 | temp = self.head 17 | while(temp): 18 | print(temp.data, end = ' ') 19 | temp = temp.next 20 | 21 | #Stable version 22 | def partition_around_x(self, x): 23 | curr = self.head 24 | dummy1 = dummy2 = Node(0) 25 | x1, x2 = dummy1, dummy2 26 | dummy1.next = curr 27 | 28 | while(curr): 29 | if(curr.data < x): 30 | x1.next = curr 31 | x1 = x1.next 32 | else: 33 | x2.next = curr 34 | x2 = x2.next 35 | curr = curr.next 36 | x2.next = None 37 | x1.next = dummy2.next 38 | return dummy1.next 39 | 40 | 41 | if __name__ == "__main__": 42 | ll = LinkedList() 43 | inp = list(map(int, input().split())) 44 | for i in inp: 45 | ll.push(i) 46 | ll.printLL() 47 | print() 48 | temp = ll.partition_around_x(5) 49 | ll.printLL() -------------------------------------------------------------------------------- /Miscellaneous/max_in_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node{ 4 | int data; 5 | Node *left, *right; 6 | }; 7 | 8 | Node *newNode(int data){ 9 | Node *curr = new Node(); 10 | curr->data = data; 11 | curr->left = curr->right = NULL; 12 | return curr; 13 | } 14 | 15 | //recursive 16 | int maxInTreeRec(Node *root){ 17 | if(root == NULL) return 0; 18 | int max_val = INT_MIN; 19 | int left = maxInTreeRec(root->left); 20 | int right = maxInTreeRec(root->right); 21 | max_val = max(max_val, max(left, max(right, root->data))); 22 | return max_val; 23 | } 24 | 25 | //Non-recursive 26 | void maxInTree(Node *root){ 27 | if(root == NULL)return; 28 | queue q; 29 | q.push(root); 30 | int max = INT_MIN; 31 | while(!q.empty()){ 32 | Node *curr = q.front(); 33 | q.pop(); 34 | if(curr->data > max) 35 | max = curr->data; 36 | if(curr->left) q.push(curr->left); 37 | if(curr->right) q.push(curr->right); 38 | } 39 | cout<left = newNode(2); 45 | root->right = newNode(3); 46 | root->left->left = newNode(4); 47 | root->left->right = newNode(5); 48 | root->right->left = newNode(6); 49 | root->right->right = newNode(7); 50 | maxInTree(root); 51 | cout< 0): 30 | return False 31 | check = check | (1 << ord(char)) 32 | return True 33 | 34 | if __name__ == '__main__': 35 | tc = int(input()) 36 | while tc > 0: 37 | st = str(input()) 38 | if unique_hashed(st): 39 | print("Is Unique") 40 | else: 41 | print("Not Unique") 42 | if unique_sorted(st): 43 | print("Is Unique") 44 | else: 45 | print("Not Unique") 46 | if unique_bit(st): 47 | print("Is Unique") 48 | else: 49 | print("Not Unique") 50 | tc -= 1 -------------------------------------------------------------------------------- /Miscellaneous/count_nodes.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/c7Z5Z9kWZT 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | void levelOrderCount(Node *root) 17 | { 18 | if(root == NULL)return; 19 | queue q; 20 | int cnt = 0; 21 | q.push(root); 22 | while(q.empty() == false){ 23 | Node* current = q.front(); 24 | //cout<data<<" "; 25 | cnt++; 26 | q.pop(); 27 | if(current->left!=NULL){ 28 | q.push(current->left); 29 | } 30 | if(current->right!=NULL){ 31 | q.push(current->right); 32 | } 33 | } 34 | cout<left) + levelOrderCountRec(root->right); 43 | } 44 | 45 | 46 | int main(){ 47 | Node *root = newNode(1); 48 | root->left = newNode(2); 49 | root->right = newNode(3); 50 | root->left->left = newNode(4); 51 | root->left->right = newNode(5); 52 | root->right->left = newNode(6); 53 | root->right->right = newNode(7); 54 | levelOrderCount(root); 55 | cout<= len(x) or x[i] != x[i+1]: 9 | result += x[i] 10 | result += str(count_compression) 11 | count_compression = 0 12 | if len(result) < len(x): 13 | return result 14 | else: 15 | return x 16 | 17 | def lookaheadCount(x): 18 | count_compression = 0 19 | final_count = 0 20 | for i in range(len(x)): 21 | count_compression += 1 22 | if i + 1 >= len(x) or x[i] != x[i+1]: 23 | final_count += count_compression 24 | count_compression = 0 25 | return final_count 26 | 27 | def lookahead_compression(x): 28 | if len(x) < 1: 29 | return "" 30 | compressed_count = lookaheadCount(x) 31 | if compressed_count > len(x): 32 | return x 33 | count_compression = 0 34 | result = "" 35 | for i in range(len(x)): 36 | count_compression += 1 37 | if i + 1 >= len(x) or x[i] != x[i+1]: 38 | result += x[i] 39 | result += str(count_compression) 40 | count_compression = 0 41 | return result 42 | 43 | if __name__ == "__main__": 44 | print(string_compression("aaabbccddeeff")) 45 | print(lookahead_compression("aaabbccddeeff")) -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Loop Detection/loop_detection.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/UTnyDna7oa 2 | class Node: 3 | def __init__(self, data, next = None): 4 | self.data, self.next = data, next 5 | 6 | def printLL(head): 7 | temp = head 8 | while(temp): 9 | print(temp.data, end = ' ') 10 | temp = temp.next 11 | 12 | def countLL(head): 13 | curr, count = head, 0 14 | while(curr): 15 | count += 1 16 | curr = curr.next 17 | return count 18 | 19 | def checkTail(head3, head4): 20 | while head3.next is not None: 21 | head3 = head3.next 22 | while head4.next is not None: 23 | head4 = head4.next 24 | 25 | if(head3 == head4): return 1 26 | else: return 0 27 | 28 | def isLoop(head): 29 | if head is None: return None 30 | slow = fast = head 31 | 32 | while slow and fast and fast.next: 33 | slow = slow.next 34 | fast = fast.next.next 35 | if slow == fast: break 36 | 37 | if fast == None: return None 38 | else: 39 | slow = head 40 | while slow != fast: 41 | slow = slow.next 42 | fast = fast.next 43 | return fast 44 | 45 | if __name__ == "__main__": 46 | node = Node(70,Node(80)) 47 | head = Node(50,Node(20,node)) 48 | head.next.next = head.next 49 | 50 | found = isLoop(head) 51 | if found is not None: 52 | print("Loop detected at %s" % (found.data)) 53 | else: print("Not detected\n") -------------------------------------------------------------------------------- /Miscellaneous/search_in_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node{ 4 | int data; 5 | Node *left, *right; 6 | }; 7 | 8 | Node *newNode(int data){ 9 | Node *curr = new Node(); 10 | curr->data = data; 11 | curr->left = curr->right = NULL; 12 | return curr; 13 | } 14 | 15 | //recursive 16 | bool searchInTreeRec(Node* root, int data){ 17 | if(root == NULL) return 0; 18 | if(root->data == data)return 1; 19 | bool res = searchInTreeRec(root->left, data); 20 | if(!res) 21 | return searchInTreeRec(root->right, data); 22 | else 23 | return res; 24 | } 25 | 26 | //Non-recursive 27 | bool searchInTree(Node *root, int data){ 28 | if(root == NULL)return 0; 29 | if(root->data == data)return 1; 30 | bool found = false; 31 | queue q; 32 | q.push(root); 33 | int max = INT_MIN; 34 | while(!q.empty()){ 35 | Node *curr = q.front(); 36 | q.pop(); 37 | if(curr->data == data) return 1; 38 | if(curr->left) q.push(curr->left); 39 | if(curr->right) q.push(curr->right); 40 | } 41 | return 0; 42 | } 43 | 44 | int main(){ 45 | Node *root = newNode(1); 46 | root->left = newNode(2); 47 | root->right = newNode(3); 48 | root->left->left = newNode(4); 49 | root->left->right = newNode(5); 50 | root->right->left = newNode(6); 51 | root->right->right = newNode(7); 52 | cout< 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | int maxSumPerLevel(Node *root){ 17 | if(root == NULL) return 0; 18 | Node *curr, *temp; 19 | queue q; 20 | q.push(root); 21 | q.push(NULL); 22 | int max_sum = INT_MIN, level = 1, sum = 0, max_level = 0; 23 | while(!q.empty()){ 24 | curr = q.front(); 25 | q.pop(); 26 | if(curr == NULL){ 27 | if(sum > max_sum){ 28 | max_sum = sum; 29 | max_level = level; 30 | } 31 | sum = 0; 32 | if(!q.empty())q.push(NULL); 33 | level++; 34 | } 35 | else{ 36 | sum += curr->data; 37 | if(curr->left) 38 | q.push(curr->left); 39 | if(curr->right) 40 | q.push(curr->right); 41 | } 42 | } 43 | return max_sum; 44 | } 45 | 46 | int main(){ 47 | Node *root = newNode(1); 48 | root->left = newNode(2); 49 | root->right = newNode(3); 50 | root->left->left = newNode(4); 51 | root->left->right = newNode(5); 52 | root->right->left = newNode(6); 53 | root->right->right = newNode(7); 54 | cout< 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | //recursive 17 | Node* convertMirror(Node *root){ 18 | if(root == NULL) return NULL; 19 | convertMirror(root->left); 20 | convertMirror(root->right); 21 | Node *temp = root->left; 22 | root->left = root->right; 23 | root->right = temp; 24 | return root; 25 | } 26 | 27 | void inOrder(Node *root){ 28 | if(root == NULL) return; 29 | inOrder(root->left); 30 | cout<data<<" "; 31 | inOrder(root->right); 32 | } 33 | 34 | bool checkMirror(Node *r1, Node *r2){ 35 | if(!r1 && !r2) return true; 36 | if(!r1 || !r2) return false; 37 | //if(r1->data != r2->data) return false; 38 | else return r1->data == r2->data && checkMirror(r1->left, r2->right) && checkMirror(r1->right, r2->left); 39 | } 40 | 41 | int main(){ 42 | Node *a = newNode(1); 43 | Node *b = newNode(1); 44 | a->left = newNode(2); 45 | a->right = newNode(3); 46 | a->left->left = newNode(4); 47 | a->left->right = newNode(5); 48 | b->left = newNode(3); 49 | b->right = newNode(2); 50 | b->right->left = newNode(5); 51 | b->right->right = newNode(4); 52 | cout< 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | //recursive 17 | int numberOfLeavesRec(Node *root){ 18 | if(root == NULL) return 0; 19 | if(root->left == NULL && root->right == NULL) return 1; 20 | else{ 21 | return numberOfLeavesRec(root->left) + numberOfLeavesRec(root->right); 22 | } 23 | } 24 | 25 | //non-recursive 26 | int numberOfLeaves(Node *root){ 27 | if(root == NULL) return 0; 28 | Node *curr; 29 | queue q; 30 | q.push(root); 31 | int count = 0; 32 | while(!q.empty()){ 33 | curr = q.front(); q.pop(); 34 | if(curr->left == NULL && curr->right == NULL){ 35 | count+=1; 36 | } 37 | if(curr->left)q.push(curr->left); 38 | if(curr->right)q.push(curr->right); 39 | } 40 | return count; 41 | } 42 | 43 | //For finding full nodes --> Total - leaf 44 | //For half nodes --> XOR left and right subtree 45 | 46 | int main(){ 47 | Node *root = newNode(1); 48 | root->left = newNode(2); 49 | root->right = newNode(3); 50 | root->left->left = newNode(4); 51 | root->left->right = newNode(5); 52 | root->right->left = newNode(6); 53 | root->right->right = newNode(7); 54 | cout< 1: 3 | return False 4 | if len(s1) < 1 and len(s2) < 1: 5 | return False 6 | 7 | if s1 > s2: 8 | s1, s2 = s1, s2 9 | else: 10 | s1, s2 = s2, s1 11 | 12 | hash_ = [0] * (256) 13 | 14 | for x in s1: 15 | hash_[ord(x)] += 1 16 | 17 | for x in s2: 18 | hash_[ord(x)] -= 1 19 | 20 | count_occr = 0 21 | for x in range(256): 22 | if hash_[x] > 0: 23 | count_occr += 1 24 | return count_occr <= 1 25 | 26 | def oneAway(s1, s2): 27 | if abs(len(s1) - len(s2)) > 1: 28 | return False 29 | if len(s1) < 1 and len(s2) < 1: 30 | return False 31 | 32 | if s1 > s2: 33 | s1, s2 = s1, s2 34 | else: 35 | s1, s2 = s2, s1 36 | 37 | m, n = len(s1), len(s2) 38 | _found = False 39 | i, j = 0, 0 40 | while i 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | void inorder(Node *root){ 17 | if(root == NULL) return; 18 | inorder(root->left); 19 | cout<data<<" "; 20 | inorder(root->right); 21 | } 22 | 23 | void preorder(Node *root){ 24 | if(root == NULL) return; 25 | cout<data<<" "; 26 | inorder(root->left); 27 | inorder(root->right); 28 | } 29 | 30 | void postorder(Node *root){ 31 | if(root == NULL) return; 32 | inorder(root->left); 33 | inorder(root->right); 34 | cout<data<<" "; 35 | } 36 | 37 | int getHeight(Node *root){ 38 | if(root == NULL) return 0; 39 | return max(1 + getHeight(root->left), 1 + getHeight(root->right)); 40 | } 41 | 42 | void printCurrentLevel(Node *root, int current){ 43 | if(root == NULL)return; 44 | if(current==1)cout<data<<" "; 45 | else if(current>1){ 46 | printCurrentLevel(root->left, current-1); 47 | printCurrentLevel(root->right, current-1); 48 | } 49 | } 50 | 51 | void levelOrder(Node *root){ 52 | int h = getHeight(root); 53 | if(h==0)return; 54 | 55 | for(int i=1; i<=h; i++){ 56 | printCurrentLevel(root, i); 57 | } 58 | } 59 | 60 | 61 | int main(){ 62 | Node *root = newNode(1); 63 | root->left = newNode(2); 64 | root->right = newNode(3); 65 | root->left->left = newNode(4); 66 | root->left->right = newNode(5); 67 | root->right->left = newNode(6); 68 | root->right->right = newNode(7); 69 | inorder(root); 70 | cout<<"\n"; 71 | preorder(root); 72 | cout<<"\n"; 73 | postorder(root); 74 | cout<<"\n"; 75 | levelOrder(root); 76 | } -------------------------------------------------------------------------------- /Miscellaneous/path_with_given_sum.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/hVsJkaT2vQ 2 | #include 3 | using namespace std; 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | //recursive 17 | bool pathWithGivenSumRec(Node *root, int sum){ 18 | if(root == NULL) return (sum == 0); 19 | int rsum = sum - root->data; 20 | if(root->left and root->right || (!root->left and !root->right)) 21 | return pathWithGivenSumRec(root->left, rsum) || pathWithGivenSumRec(root->right, rsum); 22 | //if(root->left = NULL) return pathWithGivenSumRec(root->right, rsum); 23 | //if(root->right == NULL) return pathWithGivenSumRec(root->left, rsum); 24 | else if(root->left) 25 | return pathWithGivenSumRec(root->left, rsum) ; 26 | else 27 | return pathWithGivenSumRec(root->right, rsum); 28 | } 29 | 30 | //non-recursive 31 | bool pathWithGivenSum(Node *root, int sum){ 32 | if(root == NULL) return sum == 0; 33 | queue q; 34 | q.push(root); 35 | while(!q.empty()){ 36 | Node *top = q.front(); 37 | q.pop(); 38 | int rsum = sum - top->data; 39 | if(rsum == 0) return 1; //path found in tree 40 | else{ 41 | if(top->left) 42 | q.push(top->left); 43 | if(top->right) 44 | q.push(top->right); 45 | } 46 | } 47 | return false; 48 | } 49 | 50 | int main(){ 51 | Node *root = newNode(1); 52 | root->left = newNode(2); 53 | root->right = newNode(3); 54 | root->left->left = newNode(4); 55 | root->left->right = newNode(5); 56 | root->right->left = newNode(6); 57 | root->right->right = newNode(7); 58 | cout< 3 | using namespace std; 4 | 5 | struct Animal{ 6 | int arrivalTime; 7 | bool check; 8 | }; 9 | 10 | class AnimalQueue{ 11 | protected: 12 | queue dogs; 13 | queue cats; 14 | int order = 0; 15 | public: 16 | Animal getOut(string c){ 17 | Animal res; 18 | if(c == "dog"){ 19 | res = dogs.front(); 20 | dogs.pop(); 21 | } 22 | else{ 23 | res = cats.front(); 24 | cats.pop(); 25 | } 26 | return res; 27 | } 28 | void enqueue(Animal A){ 29 | if(A.check){ 30 | dogs.push(A); 31 | order++; 32 | } 33 | else{ 34 | cats.push(A); 35 | order++; 36 | } 37 | } 38 | 39 | Animal dequeueDog(){ 40 | return getOut("dog"); 41 | } 42 | 43 | Animal dequeueCat(){ 44 | return getOut("cat"); 45 | } 46 | 47 | Animal dequeueAny(){ 48 | if(dogs.empty()) 49 | return getOut("cat"); 50 | else if(cats.empty()) 51 | return getOut("dog"); 52 | else{ 53 | if(dogs.front().arrivalTime < cats.front().arrivalTime){ 54 | return getOut("dog"); 55 | } 56 | else 57 | return getOut("cat"); 58 | } 59 | } 60 | }; 61 | 62 | 63 | int main(){ 64 | Animal dog, cat; 65 | dog.check = true; 66 | cat.check = false; 67 | AnimalQueue aq; 68 | aq.enqueue(dog); 69 | aq.enqueue(cat); 70 | aq.enqueue(dog); 71 | aq.enqueue(cat); 72 | Animal x = aq.dequeueAny(); 73 | if(x.check) cout<<"Dog dequeued\n"; 74 | else cout<<"Cat dequeued\n"; 75 | Animal y = aq.dequeueDog(); 76 | if(y.check)cout<<"Dog dequeued\n"; 77 | Animal z = aq.dequeueCat(); 78 | if(!z.check)cout<<"Cat dequeued\n"; 79 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Zero Matrix/zero_matrix.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/cIVwnlYTED 2 | def printMat(m): 3 | for i in range(len(m)): 4 | for j in range(len(m[0])): 5 | print(m[i][j], end = ' ') 6 | print() 7 | 8 | def nullifyRow(m, row): 9 | for i in range(1, len(m)): 10 | m[row][i] = 0 11 | 12 | def nullifyColumn(m, col): 13 | for i in range(1, len(m[0])): 14 | m[i][col] = 0 15 | ''' 16 | def zero_matrix(m): 17 | if len(m) == 0: return 18 | rowz, colz = False, False 19 | 20 | for i in range(len(m)): 21 | if m[0][i] == 0: 22 | rowz = True 23 | break 24 | for i in range(len(m[0])): 25 | if m[i][0] == 0: 26 | colz = True 27 | break 28 | 29 | for i in range(1, len(m)): 30 | for j in range(1, len(m[0])): 31 | if m[i][j] == 0: 32 | m[0][i] = 0 33 | m[j][0] = 0 34 | 35 | for i in range(1, len(m)): 36 | if m[i][0] == 0: 37 | nullifyRow(m, i) 38 | for i in range(1, len(m[0])): 39 | if m[0][i] == 0: 40 | nullifyRow(m, i) 41 | 42 | if rowz: 43 | nullifyRow(m, 0) 44 | if colz: 45 | nullifyColumn(m, 0) 46 | printMat(m) 47 | ''' 48 | 49 | def zero_matrix(mat): 50 | n = len(mat) 51 | if n == 0: return mat 52 | m = len(mat[0]) 53 | zero_rows, zero_cols = [], [] 54 | for r in range(n): 55 | for c in range(m): 56 | if mat[r][c] == 0: 57 | zero_rows.append(r) 58 | zero_cols.append(c) 59 | break 60 | for r in zero_rows: 61 | for c in range(m): 62 | mat[r][c] = 0 63 | for c in zero_cols: 64 | for r in range(n): 65 | mat[r][c] = 0 66 | printMat(mat) 67 | 68 | if __name__ == "__main__": 69 | mat1 = [[1,1,1,1,1],[1,0,1,1,1],[1,1,1,1,1],[1,1,1,0,1],[2,3,4,5,6]] 70 | mat2 = [[1,0,1,0,1],[0,0,0,0,0],[1,0,1,0,1],[0,0,0,0,0],[2,0,4,0,6]] 71 | zero_matrix(mat1) 72 | #zero_matrix(mat2) 73 | -------------------------------------------------------------------------------- /Miscellaneous/insert_in_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node{ 4 | int data; 5 | Node *left, *right; 6 | }; 7 | 8 | Node *newNode(int data){ 9 | Node *curr = new Node(); 10 | curr->data = data; 11 | curr->left = curr->right = NULL; 12 | return curr; 13 | } 14 | 15 | //recursive 16 | Node* insertInTreeRec(Node* root, int data){ 17 | if(root == NULL) return NULL; 18 | if(root->left == NULL){ 19 | root->left = newNode(data); 20 | return root->left; 21 | } 22 | else if(root->right == NULL){ 23 | root->right = newNode(data); 24 | return root->right; 25 | } 26 | else{ 27 | insertInTreeRec(root->left, data); 28 | insertInTreeRec(root->right, data); 29 | } 30 | return NULL; 31 | } 32 | 33 | //Non-recursive 34 | void insertInTree(Node *root, int data){ 35 | if(root == NULL) return; 36 | queue q; 37 | q.push(root); 38 | 39 | while(!q.empty()){ 40 | Node* curr = q.front(); 41 | q.pop(); 42 | if(curr->left == NULL){ 43 | curr->left = newNode(data); 44 | break; 45 | //return curr->left; 46 | } 47 | else 48 | q.push(curr->left); 49 | 50 | if(curr->right == NULL){ 51 | curr->right = newNode(data); 52 | break; 53 | //return curr->right; 54 | } 55 | else 56 | q.push(curr->right); 57 | } 58 | return; 59 | } 60 | 61 | void inOrder(Node *root){ 62 | if(root == NULL)return; 63 | inOrder(root->left); 64 | cout<data<<" "; 65 | inOrder(root->right); 66 | } 67 | 68 | int main(){ 69 | Node *root = newNode(1); 70 | root->left = newNode(2); 71 | root->right = newNode(3); 72 | root->left->left = newNode(4); 73 | root->left->right = newNode(5); 74 | root->right->left = newNode(6); 75 | root->right->right = newNode(7); 76 | //if(insertInTree(root, 10) != NULL) 77 | // cout<data; 78 | insertInTreeRec(root, 12); 79 | inOrder(root); 80 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/String Rotation/string_rotation.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/cIVwnlYTED 2 | #include // Include every standard library 3 | using namespace std; 4 | 5 | typedef long long LL; 6 | typedef pair pii; 7 | typedef pair pll; 8 | typedef pair pss; 9 | typedef vector vi; 10 | typedef vector vvi; 11 | typedef vector vii; 12 | typedef vector vl; 13 | typedef vector vvl; 14 | 15 | double EPS=1e-9; 16 | int INF=1000000005; 17 | long long INFF=1000000000000000005LL; 18 | double PI=acos(-1); 19 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 20 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 21 | 22 | #define DEBUG fprintf(stderr, "====TESTING====\n") 23 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 24 | #define debug(...) fprintf(stderr, __VA_ARGS__) 25 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 26 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 27 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 28 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 29 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 30 | #define FOREACH(a, b) for (auto&(a) : (b)) 31 | #define REP(i, n) FOR(i, 0, n) 32 | #define REPN(i, n) FORN(i, 1, n) 33 | #define MAX(a, b) a=max(a, b) 34 | #define MIN(a, b) a=min(a, b) 35 | #define SQR(x) ((LL)(x) * (x)) 36 | #define RESET(a, b) memset(a, b, sizeof(a)) 37 | #define fi first 38 | #define se second 39 | #define mp make_pair 40 | #define pb push_back 41 | #define ALL(v) v.begin(), v.end() 42 | #define ALLA(arr, sz) arr, arr + sz 43 | #define SIZE(v) (int)v.size() 44 | #define SORT(v) sort(ALL(v)) 45 | #define REVERSE(v) reverse(ALL(v)) 46 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 47 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 48 | #define PERMUTE next_permutation 49 | #define TC(t) while (t--) 50 | 51 | int main() 52 | { 53 | string x1, x2; 54 | cin>>x1>>x2; 55 | 56 | if(x1.length() > 0 && x2.length() > 0 && x1.length()==x2.length()) 57 | string result = x1 + x2; 58 | if(result.find(x2) != string::npos) 59 | cout<<"x2 is substring of x1"; 60 | else 61 | cout<<"x1 is not substring of x2"; 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Three in One/three_in_one.py: -------------------------------------------------------------------------------- 1 | ''' 2 | #Long approach 3 | def __init__(self): 4 | self.n, self.k = a, b 5 | stackData, topOfStacks, nextIndex = [], [], [] 6 | nextAvailable = 0 7 | for i in range(self.n): 8 | stackData.append(0) 9 | for i in range(self.n - 1): 10 | nextIndex.append(i + 1) 11 | nextIndex.append(-1) 12 | for i in range(self.k): 13 | topOfStacks.append(-1) 14 | 15 | def push(self, k, data): 16 | if self.nextAvailable == -1: 17 | print("SO") #overflow 18 | return 19 | temp, self.nextAvailable, self.nextIndex[temp], self.topOfStacks[k], self.stackData[k] = \ 20 | self.nextAvailable, self.nextIndex[temp], self.topOfStacks[k], temp, data 21 | 22 | def pop(self, k): 23 | if self.nextAvailable == -1: 24 | print("SU") #underflow 25 | return -1 26 | temp, self.topOfStacks[k], self.extIndex[temp], self.nextAvailable = \ 27 | self.topOfStacks[k], self.nextIndex[temp], self.nextAvailable, temp 28 | return self.stackData[temp] 29 | ''' 30 | 31 | class Kstacks: 32 | #static fix length solution 33 | def __init__(self): 34 | self.array = [None, None, None] 35 | self.current = [0, 1, 2] 36 | 37 | def push(self, item, stack_number): 38 | if not stack_number in [0, 1, 2]: 39 | raise Exception("Bad stack number") 40 | while len(self.array) <= self.current[stack_number]: 41 | self.array += [None] * len(self.array) 42 | self.array[self.current[stack_number]] = item 43 | self.current[stack_number] += 3 44 | 45 | def pop(self, stack_number): 46 | if not stack_number in [0, 1, 2]: 47 | raise Exception("Bad stack number") 48 | if self.current[stack_number] > 3: 49 | self.current[stack_number] -= 3 50 | item = self.array[self.current[stack_number]] 51 | self.array[self.current[stack_number]] = None 52 | print(item) 53 | return item 54 | 55 | if __name__ == '__main__': 56 | ks = Kstacks() 57 | ks.push(10, 0) 58 | ks.push(11, 0) 59 | ks.push(12, 0) 60 | ks.push(13, 1) 61 | ks.pop(0) -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Intersection/intersection.py: -------------------------------------------------------------------------------- 1 | #https://ide.geeksforgeeks.org/qBxCku5tML 2 | class Node: 3 | def __init__(self, data, next = None): 4 | self.data, self.next = data, next 5 | 6 | def printLL(head): 7 | temp = head 8 | while(temp): 9 | print(temp.data, end = ' ') 10 | temp = temp.next 11 | 12 | def countLL(head): 13 | curr, count = head, 0 14 | while(curr): 15 | count += 1 16 | curr = curr.next 17 | return count 18 | 19 | def checkTail(head3, head4): 20 | while head3.next is not None: 21 | head3 = head3.next 22 | while head4.next is not None: 23 | head4 = head4.next 24 | 25 | if(head3 == head4): return 1 26 | else: return 0 27 | 28 | def advanceKNodes(longer, k): 29 | if k == 0: return longer 30 | for i in range(k): 31 | longer = longer.next 32 | return longer 33 | 34 | #compare and return 35 | def checkIntersection1(head3, head4): 36 | if head3 == None or head4 == None: return None 37 | if not checkTail(head3, head4): return None 38 | l1, l2 = countLL(head3), countLL(head4) 39 | shorter = head3 if l1 < l2 else head4 40 | longer = head4 if l1 < l2 else head3 41 | k = abs(l1 - l2) 42 | more_longer = advanceKNodes(longer, k) 43 | while more_longer and shorter: 44 | if more_longer == shorter: 45 | return more_longer 46 | more_longer = more_longer.next 47 | shorter = shorter.next 48 | return None 49 | 50 | #naive --> hashing 51 | def checkIntersection(head3, head4): 52 | nodes = {} 53 | node = head3 54 | while node: 55 | nodes[node] = True 56 | node = node.next 57 | node = head4 58 | while node: 59 | if node in nodes: 60 | return node 61 | node = node.next 62 | return None 63 | 64 | if __name__ == "__main__": 65 | node = Node(70,Node(80)) 66 | head3 = Node(50,Node(20,node)) 67 | head4 = Node(60,Node(90,Node(10,node))) 68 | h_r = checkIntersection(head3, head4) 69 | h_c = checkIntersection1(head3, head4) 70 | 71 | if h_r is None: print("Not intersecting") 72 | else: print("Intersecting node is %s " %(h_r.data)) 73 | 74 | if h_c is None: print("Not intersecting") 75 | else: print("Intersecting node is %s " %(h_c.data)) -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Palindrome Permutation/palindrome_permutation.py: -------------------------------------------------------------------------------- 1 | def getFrequency(x): 2 | ind = -1 3 | if x >= 'a' and x <= 'z': 4 | ind = x - 'a' 5 | if x >= 'A' and x <= 'Z': 6 | ind = x - 'A' 7 | return ind 8 | 9 | def palindromePermutation(mystr): 10 | if len(mystr) < 1: 11 | return False 12 | hash_ = [0] * 26 13 | i, ctoi = 0, 0 14 | 15 | for i in range(len(mystr)): 16 | ctoi = getFrequency(str[i]) 17 | if ctoi != -1: 18 | hash_[ord(ctoi)] += 1 19 | found_n = False 20 | for i in range(27): 21 | if hash_[i] % 2 == 1 and found_n: 22 | return False 23 | if hash_[i] % 2 == 1 and (not found_n): 24 | found_n = True 25 | return found_n 26 | 27 | def palindromePermutationCountOnGo(mystr): 28 | if len(mystr) < 1: 29 | return False 30 | _hash = [0] * 26 31 | i, ctoi, count_odd = 0 32 | 33 | for i in range(len(mystr)): 34 | ctoi = getFrequency(str[i]) 35 | if ctoi != -1: 36 | _hash[ord(ctoi)] += 1 37 | if _hash[ord(ctoi)] % 2: 38 | count_odd += 1 39 | else: 40 | count_odd -= 1 41 | return count_odd<=1 42 | 43 | def toggle(ind, bit_vector): 44 | if ind < 0: 45 | return bit_vector; 46 | mask = 1 << ind 47 | #toggle 48 | if (mask & bit_vector) == 0: 49 | bit_vector = bit_vector | mask 50 | else: 51 | bit_vector = bit_vector & ~mask 52 | return bit_vector 53 | 54 | def createBitVector(x): 55 | i, bit_vector = 0 56 | for i in range(len(x)): 57 | bit_vector = toggle(getFrequency(x[i]), bit_vector) 58 | return bit_vector 59 | 60 | def checkOneSetBit(bit_vector): 61 | return ((bit_vector) & (bit_vector-1) == 0) 62 | 63 | def palindromePermutationBit(x): 64 | if x.length() < 1: 65 | return False 66 | bit_vector = createBitVector(x) 67 | return bit_vector == 0 | checkOneSetBit(bit_vector) 68 | 69 | if __name__ == "__main__": 70 | ip = "TACTD COA"; 71 | if palindromePermutation(ip): print("Yes\n") 72 | else: 73 | print("No\n") 74 | if palindromePermutationCountOnGo(ip): 75 | print("Yes\n") 76 | else: 77 | print("No\n") 78 | if palindromePermutationBit(ip): 79 | print("Yes\n") 80 | else: 81 | print("No\n") -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Sort Stack/sort_stack.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/KSXSyr24oM 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | stack sort_stack(stack s1){ 52 | stack s2; 53 | while(!s1.empty()){ 54 | int top = s1.top(); 55 | s1.pop(); 56 | 57 | while(!s2.empty() && s2.top() > top){ 58 | s1.push(s2.top()); s2.pop(); 59 | } 60 | s2.push(top); 61 | } 62 | return s2; 63 | } 64 | 65 | int main(){ 66 | stack a; 67 | a.push(34); 68 | a.push(21); 69 | a.push(9); 70 | a.push(78); 71 | a.push(56); 72 | stack sorted = sort_stack(a); 73 | while(!sorted.empty()){ 74 | cout< // Include every standard library 4 | using namespace std; 5 | 6 | typedef long long LL; 7 | typedef pair pii; 8 | typedef pair pll; 9 | typedef pair pss; 10 | typedef vector vi; 11 | typedef vector vvi; 12 | typedef vector vii; 13 | typedef vector vl; 14 | typedef vector vvl; 15 | 16 | double EPS=1e-9; 17 | int INF=1000000005; 18 | long long INFF=1000000000000000005LL; 19 | double PI=acos(-1); 20 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 21 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 22 | 23 | #define DEBUG fprintf(stderr, "====TESTING====\n") 24 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 25 | #define debug(...) fprintf(stderr, __VA_ARGS__) 26 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 27 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 28 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 29 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 30 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 31 | #define FOREACH(a, b) for (auto&(a) : (b)) 32 | #define REP(i, n) FOR(i, 0, n) 33 | #define REPN(i, n) FORN(i, 1, n) 34 | #define MAX(a, b) a=max(a, b) 35 | #define MIN(a, b) a=min(a, b) 36 | #define SQR(x) ((LL)(x) * (x)) 37 | #define RESET(a, b) memset(a, b, sizeof(a)) 38 | #define fi first 39 | #define se second 40 | #define mp make_pair 41 | #define pb push_back 42 | #define ALL(v) v.begin(), v.end() 43 | #define ALLA(arr, sz) arr, arr + sz 44 | #define SIZE(v) (int)v.size() 45 | #define SORT(v) sort(ALL(v)) 46 | #define REVERSE(v) reverse(ALL(v)) 47 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 48 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 49 | #define PERMUTE next_permutation 50 | #define TC(t) while (t--) 51 | 52 | void urlify(char *str, int len) 53 | { 54 | int space_count=0; 55 | int i=0, j=0; 56 | FOR(i, 0, len){ 57 | if (str[i] == ' ') { 58 | space_count++; 59 | } 60 | } 61 | int extendedLen = len + 2 * space_count; 62 | i = extendedLen - 1; 63 | FORD(j, len - 1, 0){ 64 | if (str[j] != ' ') { 65 | str[i--] = str[j]; 66 | } else { 67 | str[i--] = '0'; 68 | str[i--] = '2'; 69 | str[i--] = '%'; 70 | } 71 | } 72 | } 73 | 74 | int main() 75 | { 76 | char str[]= "Mr John Smith "; 77 | cout <<"Actual string:"< // Include every standard library 2 | using namespace std; 3 | typedef long long LL; 4 | typedef pair pii; 5 | typedef pair pll; 6 | typedef pair pss; 7 | typedef vector vi; 8 | typedef vector vvi; 9 | typedef vector vii; 10 | typedef vector vl; 11 | typedef vector vvl; 12 | 13 | double EPS=1e-9; 14 | int INF=1000000005; 15 | long long INFF=1000000000000000005LL; 16 | double PI=acos(-1); 17 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 18 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 19 | 20 | #define DEBUG fprintf(stderr, "====TESTING====\n") 21 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 22 | #define debug(...) fprintf(stderr, __VA_ARGS__) 23 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 24 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 25 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 26 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 27 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 28 | #define FOREACH(a, b) for (auto&(a) : (b)) 29 | #define REP(i, n) FOR(i, 0, n) 30 | #define REPN(i, n) FORN(i, 1, n) 31 | #define MAX(a, b) a=max(a, b) 32 | #define MIN(a, b) a=min(a, b) 33 | #define SQR(x) ((LL)(x) * (x)) 34 | #define RESET(a, b) memset(a, b, sizeof(a)) 35 | #define fi first 36 | #define se second 37 | #define mp make_pair 38 | #define pb push_back 39 | #define ALL(v) v.begin(), v.end() 40 | #define ALLA(arr, sz) arr, arr + sz 41 | #define SIZE(v) (int)v.size() 42 | #define SORT(v) sort(ALL(v)) 43 | #define REVERSE(v) reverse(ALL(v)) 44 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 45 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 46 | #define PERMUTE next_permutation 47 | #define TC(t) while (t--) 48 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 49 | 50 | //Making dequeue operation costly 51 | class Queue{ 52 | public: 53 | stack s1, s2; 54 | void enqueue(int data){ 55 | s1.push(data); 56 | } 57 | int dequeue(){ 58 | if(s1.empty() && s2.empty()) return INT_MIN; 59 | 60 | if(s2.empty()){ 61 | while(!s1.empty()){ 62 | s2.push(s1.top()); 63 | s1.pop(); 64 | } 65 | } 66 | int front = s2.top(); //front of queue 67 | s2.pop(); 68 | return front; 69 | } 70 | }; 71 | 72 | int main(){ 73 | Queue qs; 74 | qs.enqueue(10); 75 | qs.enqueue(20); 76 | qs.enqueue(30); 77 | cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | //Making dequeue operation costly 52 | class Queue{ 53 | public: 54 | stack s1; 55 | void enqueue(int data){ 56 | s1.push(data); 57 | } 58 | int dequeue(){ 59 | if(s1.empty()) { 60 | cout<<"Empty stack..!"; 61 | return INT_MIN; 62 | } 63 | int top = s1.top(); 64 | s1.pop(); 65 | if(s1.empty()) return top; 66 | int current = dequeue(); 67 | s1.push(top); 68 | return current; 69 | } 70 | }; 71 | 72 | int main(){ 73 | Queue qs; 74 | qs.enqueue(10); 75 | qs.enqueue(20); 76 | qs.enqueue(30); 77 | cout< 2 | using namespace std; 3 | struct Node{ 4 | int data; 5 | Node *left, *right; 6 | }; 7 | 8 | Node *newNode(int data){ 9 | Node *curr = new Node(); 10 | curr->data = data; 11 | curr->left = curr->right = NULL; 12 | return curr; 13 | } 14 | 15 | void deleteDeepest(Node *root, Node* deepest_node){ 16 | if(root == NULL || deepest_node == NULL) return; 17 | queue q; 18 | q.push(root); 19 | Node *curr; 20 | 21 | while(!q.empty()){ 22 | curr = q.front(); 23 | q.pop(); 24 | if(curr == deepest_node){ 25 | curr = NULL; 26 | delete deepest_node; 27 | return; 28 | } 29 | if(curr->right){ 30 | if(curr->right == deepest_node){ 31 | curr->right = NULL; 32 | delete deepest_node; 33 | return; 34 | }else{ 35 | q.push(curr->right); 36 | } 37 | } 38 | if(curr->left){ 39 | if(curr->left == deepest_node){ 40 | curr->left = NULL; 41 | delete deepest_node; 42 | return; 43 | }else{ 44 | q.push(curr->left); 45 | } 46 | } 47 | } 48 | } 49 | 50 | Node* deleteNode(Node* root, int todelete){ 51 | if(root == NULL) return NULL; 52 | if(root->left == NULL && root->right == NULL){ 53 | if(root->data == todelete) 54 | return NULL; 55 | else 56 | return root; 57 | } 58 | else{ 59 | queue q; 60 | q.push(root); 61 | Node *key, *curr; 62 | while(!q.empty()){ 63 | curr = q.front(); 64 | q.pop(); 65 | if(curr->data == todelete){ 66 | key = curr; 67 | } 68 | if(curr->left) 69 | q.push(curr->left); 70 | if(curr->right) 71 | q.push(curr->right); 72 | } 73 | if(key != NULL){ 74 | int k = curr->data; 75 | deleteDeepest(root, curr); 76 | key->data = k; 77 | } 78 | return root; 79 | } 80 | return NULL; 81 | } 82 | 83 | void inOrder(Node *root){ 84 | if(root == NULL)return; 85 | inOrder(root->left); 86 | cout<data<<" "; 87 | inOrder(root->right); 88 | } 89 | 90 | int main(){ 91 | Node *root = newNode(1); 92 | root->left = newNode(2); 93 | root->right = newNode(3); 94 | root->left->left = newNode(4); 95 | root->left->right = newNode(5); 96 | root->right->left = newNode(6); 97 | root->right->right = newNode(7); 98 | Node *temp = deleteNode(root, 4); 99 | inOrder(temp); 100 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Zero Matrix/zero_matrix_v1.cpp: -------------------------------------------------------------------------------- 1 | #include // Include every standard library 2 | using namespace std; 3 | 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | int main() 52 | { 53 | int t,m,n,i,j; 54 | cin>>t; 55 | while(t--){ 56 | cin>>m>>n; 57 | int arr[m+10][n+10],rows[m+10],cols[n+10]; 58 | for(i=0; i>arr[i][j]; 67 | if(arr[i][j]==0){ 68 | rows[i] = 1; 69 | cols[j] = 1; 70 | } 71 | } 72 | } 73 | 74 | // cout< // Include every standard library 4 | using namespace std; 5 | 6 | typedef long long LL; 7 | typedef pair pii; 8 | typedef pair pll; 9 | typedef pair pss; 10 | typedef vector vi; 11 | typedef vector vvi; 12 | typedef vector vii; 13 | typedef vector vl; 14 | typedef vector vvl; 15 | 16 | double EPS = 1e-9; 17 | int INF = 1000000005; 18 | long long INFF = 1000000000000000005LL; 19 | double PI = acos(-1); 20 | int dirx[8] = { -1, 0, 0, 1, -1, -1, 1, 1 }; 21 | int diry[8] = { 0, 1, -1, 0, -1, 1, -1, 1 }; 22 | 23 | #define DEBUG fprintf(stderr, "====TESTING====\n") 24 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 25 | #define debug(...) fprintf(stderr, __VA_ARGS__) 26 | #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) 27 | #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) 28 | #define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a)) 29 | #define FORSQ(a, b, c) for (int(a) = (b); (a) * (a) <= (c); ++(a)) 30 | #define FORC(a, b, c) for (char(a) = (b); (a) <= (c); ++(a)) 31 | #define FOREACH(a, b) for (auto&(a) : (b)) 32 | #define REP(i, n) FOR(i, 0, n) 33 | #define REPN(i, n) FORN(i, 1, n) 34 | #define MAX(a, b) a = max(a, b) 35 | #define MIN(a, b) a = min(a, b) 36 | #define SQR(x) ((LL)(x) * (x)) 37 | #define RESET(a, b) memset(a, b, sizeof(a)) 38 | #define fi first 39 | #define se second 40 | #define mp make_pair 41 | #define pb push_back 42 | #define ALL(v) v.begin(), v.end() 43 | #define ALLA(arr, sz) arr, arr + sz 44 | #define SIZE(v) (int)v.size() 45 | #define SORT(v) sort(ALL(v)) 46 | #define REVERSE(v) reverse(ALL(v)) 47 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 48 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 49 | #define PERMUTE next_permutation 50 | #define TC(t) while (t--) 51 | 52 | bool checkPermutationSort(string x, string y){ 53 | if(x.length() != y.length())return false; 54 | 55 | sort(x.begin(), x.end()); 56 | sort(y.begin(), y.end()); 57 | int i; 58 | FOR(i, 0, x.length() - 1){ 59 | if(x[i] != y[i]) 60 | return false; 61 | } 62 | return true; 63 | } 64 | 65 | bool checkPermutationHash(string x, string y){ 66 | vector hash(26); //considering only a-z for now hence 26 characters 67 | hash = {0}; 68 | 69 | int i, j; 70 | FOR(i, 0, x.length() - 1){ 71 | hash[x[i] - 'a']++; 72 | } 73 | FOR(i, 0, y.length() - 1){ 74 | if(! (hash[y[i] - 'a'])) return false; 75 | hash[y[i] -'a']--; 76 | } 77 | return true; 78 | } 79 | 80 | int main(){ 81 | int t; cin>>t; 82 | TC(t){ 83 | string x, y; 84 | cin>>x>>y; 85 | if(checkPermutationSort(x, y))cout<<"True\n"; 86 | else cout<<"False\n"; 87 | 88 | if(checkPermutationHash(x, y))cout<<"True\n"; 89 | else cout<<"False\n"; 90 | 91 | } 92 | } -------------------------------------------------------------------------------- /Chapter 3 - Stacks and Queues/Stack Of Plates/stack_of_plates.py: -------------------------------------------------------------------------------- 1 | class SetStack: 2 | def __init__(self, sz): 3 | self.stacks = [] #list of lists 4 | self.size = sz #capacity of each stack 5 | 6 | def spush(self, value): 7 | #when stack is empty 8 | if self.stacks == []: 9 | self.stacks.append([value]) 10 | else: 11 | #len(last stack in array) > total capacity 12 | if len(self.stacks[-1]) >= self.size: 13 | self.stacks.append([value]) #append new stack to the set and push element into it 14 | #append element to last stack in the set 15 | else: 16 | self.stacks[-1].append(value) 17 | 18 | def spop(self): 19 | if self.stacks == []: 20 | print("Empty stack") 21 | return 22 | popped = self.stacks[-1][-1] 23 | #if length of last stack in set is 1, then remove stack from set 24 | if len(self.stacks[-1]) == 1: 25 | del self.stacks[-1] 26 | else: 27 | del self.stacks[-1][-1] 28 | return popped 29 | 30 | def spopAt(self, index): 31 | if self.stacks == []: 32 | print("Empty stack") 33 | return 34 | elif index-1 > len(self.stacks): 35 | print("Index out of bounds") 36 | return 37 | else: 38 | popped = self.stacks[index-1][-1] 39 | #if len(stack at index) is just one, then remove the stack from set 40 | if len(self.stacks[index-1]) == 1: 41 | del self.stacks[-1] 42 | #if len(stacks) == index i.e. --> the element to be popped is from last stack from the set 43 | elif len(self.stacks) == index: 44 | del self.stacks[-1][-1] 45 | #perform rollover operations 46 | else: 47 | #move element on top of S3 to bottom of S2 where S = [S1, S2, S3) 48 | self.stacks[index-1][-1] = self.stacks[index][0] 49 | #repeatedly do the above for all the elements below the top of S3 --> move them one above their actual position 50 | for i in range(index, len(self.stacks)): 51 | for j in range(0, len(self.stacks[i])-1): 52 | self.stacks[i][j] = self.stacks[i][j+1] 53 | if i < len(self.stacks) - 1: 54 | self.stacks[i][-1] = self.stacks[i+1][0] 55 | #perform pop to change the bottom of last stack in set 56 | del self.stacks[-1][-1] 57 | 58 | if len(self.stacks[-1]) == 0: 59 | del self.stacks[-1] 60 | return popped 61 | 62 | if __name__ == "__main__": 63 | ss = SetStack(3) 64 | ss.spush(1) 65 | ss.spush(2) 66 | ss.spush(3) 67 | ss.spush(4) 68 | ss.spush(5) 69 | ss.spush(6) 70 | print(ss.spop()) 71 | print(ss.spop()) 72 | ss.spush(7) 73 | ss.spush(8) 74 | ss.spush(9) 75 | print(ss.spopAt(2)) 76 | print(ss.spopAt(1)) 77 | -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Is Unique/is_unique.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/PXfVawytO8 2 | 3 | #include // Include every standard library 4 | using namespace std; 5 | 6 | typedef long long LL; 7 | typedef pair pii; 8 | typedef pair pll; 9 | typedef pair pss; 10 | typedef vector vi; 11 | typedef vector vvi; 12 | typedef vector vii; 13 | typedef vector vl; 14 | typedef vector vvl; 15 | 16 | double EPS = 1e-9; 17 | int INF = 1000000005; 18 | long long INFF = 1000000000000000005LL; 19 | double PI = acos(-1); 20 | int dirx[8] = { -1, 0, 0, 1, -1, -1, 1, 1 }; 21 | int diry[8] = { 0, 1, -1, 0, -1, 1, -1, 1 }; 22 | 23 | #define DEBUG fprintf(stderr, "====TESTING====\n") 24 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 25 | #define debug(...) fprintf(stderr, __VA_ARGS__) 26 | #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) 27 | #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) 28 | #define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a)) 29 | #define FORSQ(a, b, c) for (int(a) = (b); (a) * (a) <= (c); ++(a)) 30 | #define FORC(a, b, c) for (char(a) = (b); (a) <= (c); ++(a)) 31 | #define FOREACH(a, b) for (auto&(a) : (b)) 32 | #define REP(i, n) FOR(i, 0, n) 33 | #define REPN(i, n) FORN(i, 1, n) 34 | #define MAX(a, b) a = max(a, b) 35 | #define MIN(a, b) a = min(a, b) 36 | #define SQR(x) ((LL)(x) * (x)) 37 | #define RESET(a, b) memset(a, b, sizeof(a)) 38 | #define fi first 39 | #define se second 40 | #define mp make_pair 41 | #define pb push_back 42 | #define ALL(v) v.begin(), v.end() 43 | #define ALLA(arr, sz) arr, arr + sz 44 | #define SIZE(v) (int)v.size() 45 | #define SORT(v) sort(ALL(v)) 46 | #define REVERSE(v) reverse(ALL(v)) 47 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 48 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 49 | #define PERMUTE next_permutation 50 | #define TC(t) while (t--) 51 | 52 | //hashing occurrences of characters 53 | // TC: O(n) SC: O(n) 54 | bool isUniqueHashing(string x){ 55 | if(x.length() < 1) return false; 56 | 57 | vector bset(128); //ASCI is 128 chars 58 | int i; 59 | bset = {0}; 60 | FOR(i, 0, x.length() - 1){ 61 | if(bset[x[i] - 'a']){ 62 | return false; 63 | } 64 | bset[x[i] - 'a'] = true; 65 | } 66 | return true; 67 | } 68 | 69 | //useful only when the input modification is permitted 70 | // TC: O(n logn) SC: O(1) 71 | bool isUniqueSort(string x){ 72 | if(x.length() < 1) return false; 73 | 74 | sort(x.begin(), x.end()); 75 | FOR(i, 0, x.length() - 2){ 76 | if(x[i] == x[i + 1]) 77 | return false; 78 | } 79 | return true; 80 | } 81 | 82 | //check bit first, then set bit 83 | //uses constant space --> n * k (n is length of string and k is the bits in each char within string) 84 | bool isUniqueBit(string x){ 85 | if(x.length() < 1) return false; 86 | 87 | int check = 0; 88 | int value = x[i] - 'a'; 89 | FOR(i, 0, x.length() - 1){ 90 | if((check & (1 << value)) > 0) return false; 91 | check = check | (1 << value); 92 | } 93 | return true; 94 | } 95 | 96 | int main(){ 97 | 98 | int t; cin>>t; 99 | TC(t){ 100 | string x; 101 | cin>>x; 102 | if(isUniqueSort(x))cout<<"True\n"; 103 | else cout<<"False\n"; 104 | 105 | if(isUniqueHashing(x))cout<<"True\n"; 106 | else cout<<"False\n"; 107 | 108 | if(isUniqueBit(x))cout<<"True\n"; 109 | else cout<<"False\n"; 110 | } 111 | } -------------------------------------------------------------------------------- /Miscellaneous/tree_traversals_non_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | Node *newNode(int data){ 10 | Node *curr = new Node(); 11 | curr->data = data; 12 | curr->left = curr->right = NULL; 13 | return curr; 14 | } 15 | 16 | void inorder(Node *root){ 17 | //First push everything in stack moving left (L) 18 | //As there is no leftmost //pop the current (V) 19 | //Go on right and perform same (R) 20 | if(root == NULL) return; 21 | stack s; 22 | Node *curr = root; 23 | while(!s.empty() && curr != NULL){ 24 | while(curr != NULL){ 25 | s.push(curr); 26 | curr = curr->left; 27 | } 28 | curr = s.top(); 29 | s.pop(); 30 | cout<data<<" "; 31 | curr = curr->right; 32 | } 33 | } 34 | 35 | void preorder(Node *root){ 36 | if(root == NULL) return; 37 | stack s; 38 | s.push(root); 39 | while(!s.empty()){ 40 | Node *curr = s.top(); 41 | s.pop(); 42 | cout<data<<" "; 43 | if(curr->right) 44 | s.push(curr->right); 45 | if(curr->left) 46 | s.push(curr->left); 47 | } 48 | } 49 | 50 | //Two stacks 51 | void postorder(Node *root){ 52 | //Another stack ensures that instead of going for VLR (pre-order) we take the V 53 | //and push it in another stack to guarantee RLV (Also, here left is pushed first and then right so we have right out first) 54 | //LIFO ensures that V occurs at the end and first L and R are looked into 55 | if(root == NULL) return; 56 | stack s1; 57 | stack s2; 58 | s1.push(root); 59 | while(!s1.empty()){ 60 | Node *curr = s1.top(); 61 | s1.pop(); 62 | s2.push(curr); 63 | if(curr->left) 64 | s1.push(curr->left); 65 | if(curr->right) 66 | s1.push(curr->right); 67 | } 68 | while(!s2.empty()){ 69 | cout<data<<" "; 70 | s2.pop(); 71 | } 72 | } 73 | 74 | //1stack 75 | void postorder1(Node *root){ 76 | if(root == NULL) return; 77 | stack s; 78 | Node *curr = root; 79 | while(1){ 80 | while(curr != NULL){ 81 | s.push(curr); 82 | s.push(curr); 83 | curr = curr->left; 84 | } 85 | if(s.empty()) return; 86 | curr = s.top(); 87 | s.pop(); 88 | if(!s.empty() && s.top() == curr)curr = curr->right; 89 | else{ 90 | cout<data<<" "; 91 | curr = NULL; 92 | } 93 | } 94 | 95 | } 96 | 97 | int getHeight(Node *root){ 98 | if(root == NULL) return 0; 99 | return max(1 + getHeight(root->left), 1 + getHeight(root->right)); 100 | } 101 | 102 | void levelOrder(Node *root) 103 | { 104 | if(root == NULL)return; 105 | queue q; 106 | q.push(root); 107 | while(q.empty() == false){ 108 | Node* current = q.front(); 109 | cout<data<<" "; 110 | q.pop(); 111 | if(current->left!=NULL){ 112 | q.push(current->left); 113 | } 114 | if(current->right!=NULL){ 115 | q.push(current->right); 116 | } 117 | } 118 | } 119 | 120 | int main(){ 121 | Node *root = newNode(1); 122 | root->left = newNode(2); 123 | root->right = newNode(3); 124 | root->left->left = newNode(4); 125 | root->left->right = newNode(5); 126 | levelOrder(root); 127 | postorder(root); 128 | postorder1(root); 129 | preorder(root); 130 | inorder(root); 131 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/String Compression/string_compression.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/99cYaz4W3i 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | 50 | string stringCompression(string x){ 51 | if(x.length() < 1) return ""; 52 | int i, count_compression = 0; 53 | string result = ""; 54 | FOR(i, 0, x.length() - 1){ 55 | count_compression++; 56 | if(i+1 >= x.length() || x[i] != x[i+1]){ 57 | result += x[i]; 58 | result += to_string(count_compression); 59 | count_compression = 0; 60 | } 61 | } 62 | cout<= x.length() || x[i] != x[i+1]){ 74 | length_compression += 1 + count_compression; 75 | count_compression = 0; 76 | } 77 | } 78 | return length_compression; 79 | } 80 | 81 | string lookAheadCompression(string x){ 82 | if(x.length() < 1) return ""; 83 | int count_size = countCompression(x); 84 | if(count_size < x.length()) 85 | return x; 86 | 87 | int count_compression = 0; 88 | string result = ""; 89 | FOR(i, 0, x.length() - 1){ 90 | count_compression++; 91 | if(i+1 >= x.length() || x[i] != x[i+1]){ 92 | result += x[i]; 93 | result += to_string(count_compression); 94 | count_compression = 0; 95 | } 96 | } 97 | return result; 98 | } 99 | 100 | int main() 101 | { 102 | string ip = "aaabbbccdddeefghiiijjkk"; 103 | cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | class StackMin{ 52 | stack minStack; 53 | int minEle, temp; 54 | 55 | public: 56 | bool isEmpty(){ 57 | if(minStack.empty()){ 58 | //cout<<"Stack is empty."<<"\n"; 59 | return true; 60 | } 61 | return false; 62 | } 63 | 64 | void getPeek(){ 65 | if(isEmpty()){ 66 | cout<<"Stack is empty."<<"\n"; 67 | return; 68 | } 69 | int top = minStack.top(); 70 | cout<<"Current top - "; 71 | if(top < minEle)cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | class KStacks{ 52 | int *stackData, *topOfStacks, *nextIndex; 53 | int n, k, nextAvailable; 54 | 55 | public: 56 | KStacks(int a, int b){ 57 | n = a; k = b; 58 | stackData = new int[n]; 59 | topOfStacks = new int[k]; 60 | nextIndex = new int[n]; 61 | nextAvailable = 0; 62 | int x; 63 | FOR(x, 0, n) topOfStacks[x] = -1; 64 | FOR(x, 0, n-1) nextIndex[x] = x + 1; 65 | nextIndex[n-1] = -1; 66 | } 67 | 68 | void push(int k, int data){ 69 | if(nextAvailable == -1){ 70 | cout<<"SO"<<"\n"; //stackoverflow 71 | return; 72 | } 73 | 74 | //very similar to 3 way swapping --> 75 | //a->b->c->d 76 | 77 | int temp = nextAvailable; 78 | nextAvailable = nextIndex[temp]; 79 | nextIndex[temp] = topOfStacks[k]; 80 | topOfStacks[k] = temp; 81 | 82 | //push operation 83 | stackData[temp] = data; 84 | } 85 | 86 | int pop(int k){ 87 | if(topOfStacks[k] == -1){ 88 | cout<<"Empty stack..!"<<"\n"; 89 | return -1; 90 | } 91 | 92 | //reverse of push 3 way swapping 93 | int temp = topOfStacks[k]; 94 | topOfStacks[k] = nextIndex[temp]; 95 | nextIndex[temp] = nextAvailable; 96 | nextAvailable = temp; 97 | return stackData[temp]; 98 | } 99 | }; 100 | 101 | int main(){ 102 | int n = 6, k = 10; 103 | KStacks ks(n, k); 104 | ks.push(0, 10); 105 | ks.push(0, 11); 106 | ks.push(0, 12); 107 | ks.push(1, 13); 108 | cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | class StackSet{ 52 | 53 | int capacity; 54 | vector> setStack; 55 | 56 | public: 57 | StackSet(int c){ 58 | capacity = c; 59 | setStack = vector>(); 60 | } 61 | 62 | void spush(int data){ 63 | if(setStack.back().size() == capacity) 64 | setStack.push_back(stack()); 65 | setStack.back().push(data); 66 | } 67 | 68 | int spop(){ 69 | if(setStack.size() == 1 && setStack[0].empty()) 70 | return INT_MIN; 71 | int t = setStack.back().top(); 72 | setStack.back().pop(); 73 | if(setStack.back().empty() && setStack.size() > 1) 74 | setStack.pop_back(); 75 | return t; 76 | } 77 | 78 | void spopAt(int index) 79 | { 80 | int t; 81 | if (setStack[index].size() > 1) 82 | setStack[index].pop(); 83 | else 84 | { 85 | if (setStack.size() > 1) 86 | setStack.erase(setStack.begin() + index); 87 | else // we only have one stack 88 | setStack[index].pop(); 89 | } 90 | } 91 | 92 | int size() const 93 | { 94 | int initial = 0; 95 | for (const std::stack& s : setStack) 96 | initial += s.size(); 97 | return initial; 98 | } 99 | bool empty() const 100 | { 101 | return size() == 0; 102 | } 103 | 104 | int top() const 105 | { 106 | assert(!empty()); 107 | return setStack.back().top(); 108 | } 109 | }; 110 | 111 | 112 | int main(){ 113 | StackSet s(4); 114 | s.spush(10); 115 | s.spush(20); 116 | s.spush(30); 117 | s.spush(40); 118 | s.spop(); 119 | s.spop(); 120 | s.spush(50); 121 | s.spush(60); 122 | s.spush(70); 123 | s.spush(80); 124 | s.spopAt(0); 125 | s.spopAt(1); 126 | return 0; 127 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Delete Middle node/delete_middle_node.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/2WHjXZwea9 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | void countLL(Node *head){ 72 | if(head == NULL)return; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | } 79 | 80 | Node *insertNode(int data, Node *head){ 81 | Node *newNode = createNode(data); 82 | if(head == NULL) 83 | head = newNode; 84 | else{ 85 | head->next = newNode; 86 | head = newNode; 87 | } 88 | return head; 89 | } 90 | 91 | Node *insertNodeEnd(int data, Node *head) 92 | { 93 | Node *newNode=createNode(data); 94 | Node *traverse=head; 95 | if(head==NULL){ 96 | newNode->next=NULL; 97 | head=newNode; 98 | return head; 99 | } 100 | while(traverse->next!=NULL) 101 | traverse=traverse->next; 102 | traverse->next=newNode; 103 | newNode->next=NULL; 104 | return head; 105 | } 106 | 107 | Node *removeMiddleNode(Node *head, Node *middle){ 108 | if(head == NULL || middle == NULL) return NULL; 109 | Node *temp = middle->next; 110 | middle->data = temp->data; 111 | middle->next = temp->next; 112 | return head; 113 | } 114 | 115 | int main(){ 116 | //n - number of nodes in LL 117 | //int n, data; 118 | //cin>>n; 119 | Node *head = createNode(10); 120 | Node *a = createNode(20); 121 | Node *b = createNode(30); 122 | Node *c = createNode(40); 123 | Node *d = createNode(50); 124 | Node *e = createNode(60); 125 | head->next = a; 126 | a->next = b; 127 | b->next = c; 128 | c->next = d; 129 | d->next = e; 130 | printLL(head); 131 | cout<<"\n"; 132 | head = removeMiddleNode(head, c); 133 | printLL(head); 134 | cout<<"\n"; 135 | } 136 | -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Return Kth To Last/return_kth_to_last.cpp: -------------------------------------------------------------------------------- 1 | // 2 | 3 | #include // Include every standard library 4 | using namespace std; 5 | typedef long long LL; 6 | typedef pair pii; 7 | typedef pair pll; 8 | typedef pair pss; 9 | typedef vector vi; 10 | typedef vector vvi; 11 | typedef vector vii; 12 | typedef vector vl; 13 | typedef vector vvl; 14 | 15 | double EPS=1e-9; 16 | int INF=1000000005; 17 | long long INFF=1000000000000000005LL; 18 | double PI=acos(-1); 19 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 20 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 21 | 22 | #define DEBUG fprintf(stderr, "====TESTING====\n") 23 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 24 | #define debug(...) fprintf(stderr, __VA_ARGS__) 25 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 26 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 27 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 28 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 29 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 30 | #define FOREACH(a, b) for (auto&(a) : (b)) 31 | #define REP(i, n) FOR(i, 0, n) 32 | #define REPN(i, n) FORN(i, 1, n) 33 | #define MAX(a, b) a=max(a, b) 34 | #define MIN(a, b) a=min(a, b) 35 | #define SQR(x) ((LL)(x) * (x)) 36 | #define RESET(a, b) memset(a, b, sizeof(a)) 37 | #define fi first 38 | #define se second 39 | #define mp make_pair 40 | #define pb push_back 41 | #define ALL(v) v.begin(), v.end() 42 | #define ALLA(arr, sz) arr, arr + sz 43 | #define SIZE(v) (int)v.size() 44 | #define SORT(v) sort(ALL(v)) 45 | #define REVERSE(v) reverse(ALL(v)) 46 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 47 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 48 | #define PERMUTE next_permutation 49 | #define TC(t) while (t--) 50 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 51 | 52 | struct Node{ 53 | int data; 54 | struct Node *next; 55 | }; 56 | 57 | Node* createNode(int data){ 58 | Node *new_node = new Node(); 59 | new_node->data = data; 60 | new_node->next = NULL; 61 | return new_node; 62 | } 63 | 64 | void printLL(Node *head){ 65 | if(head == NULL)return; 66 | while(head != NULL){ 67 | cout<data<<" "; 68 | head = head->next; 69 | } 70 | } 71 | 72 | void countLL(Node *head){ 73 | if(head == NULL)return; 74 | int node_count = 0; 75 | while(head != NULL){ 76 | node_count++; 77 | head = head->next; 78 | } 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | head->next = newNode; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | Node *insertNodeEnd(int data, Node *head) 93 | { 94 | Node *newNode=createNode(data); 95 | Node *traverse=head; 96 | if(head==NULL){ 97 | newNode->next=NULL; 98 | head=newNode; 99 | return head; 100 | } 101 | while(traverse->next!=NULL) 102 | traverse=traverse->next; 103 | traverse->next=newNode; 104 | newNode->next=NULL; 105 | return head; 106 | } 107 | 108 | Node *kthNodeToLast(Node *head, int &i, int k){ 109 | if(head == NULL) return NULL; 110 | Node *nnode = kthNodeToLast(head->next, i, k); 111 | i += 1; 112 | if(i == k) 113 | return head; 114 | return nnode; 115 | } 116 | 117 | Node *kthNodeToLastIter(Node *head, int k){ 118 | if(head == NULL) return NULL; 119 | Node *b = head, *c = head; 120 | int j; 121 | FOR(j, 0, k){ 122 | if(b == NULL) return NULL; 123 | b = b->next; 124 | } 125 | while(b!=NULL){ 126 | b = b->next; 127 | c = c->next; 128 | } 129 | return c; 130 | } 131 | int main(){ 132 | //n - number of nodes in LL 133 | 134 | Node *head = NULL; 135 | int n, k, data, i, j = 0; 136 | cin>>n>>k; 137 | FOR(i, 0, n){ 138 | cin>>data; 139 | head = insertNodeEnd(data, head); 140 | } 141 | printLL(head); 142 | cout<<"\n"; 143 | Node *result = kthNodeToLast(head, j, k); 144 | cout<data; 145 | 146 | Node *result2 = kthNodeToLastIter(head, k); 147 | cout<data<<"\n"; 148 | cout<<"\n"; 149 | 150 | } 151 | -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Palindrome Permutation/palindrome_permutation.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/1YN376nxPW 2 | 3 | #include // Include every standard library 4 | using namespace std; 5 | 6 | typedef long long LL; 7 | typedef pair pii; 8 | typedef pair pll; 9 | typedef pair pss; 10 | typedef vector vi; 11 | typedef vector vvi; 12 | typedef vector vii; 13 | typedef vector vl; 14 | typedef vector vvl; 15 | 16 | double EPS=1e-9; 17 | int INF=1000000005; 18 | long long INFF=1000000000000000005LL; 19 | double PI=acos(-1); 20 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 21 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 22 | 23 | #define DEBUG fprintf(stderr, "====TESTING====\n") 24 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 25 | #define debug(...) fprintf(stderr, __VA_ARGS__) 26 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 27 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 28 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 29 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 30 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 31 | #define FOREACH(a, b) for (auto&(a) : (b)) 32 | #define REP(i, n) FOR(i, 0, n) 33 | #define REPN(i, n) FORN(i, 1, n) 34 | #define MAX(a, b) a=max(a, b) 35 | #define MIN(a, b) a=min(a, b) 36 | #define SQR(x) ((LL)(x) * (x)) 37 | #define RESET(a, b) memset(a, b, sizeof(a)) 38 | #define fi first 39 | #define se second 40 | #define mp make_pair 41 | #define pb push_back 42 | #define ALL(v) v.begin(), v.end() 43 | #define ALLA(arr, sz) arr, arr + sz 44 | #define SIZE(v) (int)v.size() 45 | #define SORT(v) sort(ALL(v)) 46 | #define REVERSE(v) reverse(ALL(v)) 47 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 48 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 49 | #define PERMUTE next_permutation 50 | #define TC(t) while (t--) 51 | 52 | int getFrequency(char x){ 53 | int ind = -1; 54 | if(x >= 'a' && x <= 'z') 55 | ind = x - 'a'; 56 | if(x >= 'A' && x <= 'Z') 57 | ind = x - 'A'; 58 | return ind; 59 | } 60 | 61 | bool palindromePermutation(string str){ 62 | if(str.length() < 1) return false; 63 | int hash[26] = {0}; int i, ctoi; 64 | 65 | FOR(i, 0, str.length()){ 66 | ctoi = getFrequency(str[i]); 67 | if(ctoi != -1) 68 | hash[ctoi]++; 69 | } 70 | bool found_n = false; 71 | FOR(i, 0, 27){ 72 | if(hash[i] % 2 == 1 && found_n) return false; 73 | if(hash[i] % 2 == 1 && !found_n) found_n = true; 74 | } 75 | return found_n; 76 | } 77 | 78 | bool palindromePermutationCountOnGo(string str){ 79 | if(str.length() < 1) return false; 80 | int hash[26] = {0}; 81 | int i, ctoi, count_odd = 0; 82 | 83 | FOR(i, 0, str.length()){ 84 | ctoi = getFrequency(str[i]); 85 | if(ctoi != -1) 86 | hash[ctoi]++; 87 | if(hash[ctoi] % 2 ) 88 | count_odd++; 89 | else 90 | count_odd--; 91 | } 92 | return count_odd<=1; 93 | } 94 | 95 | int toggle(int ind, int bit_vector){ 96 | if(ind < 0) return bit_vector; 97 | int mask = 1 << ind; 98 | //toggle 99 | if((mask & bit_vector) == 0) 100 | bit_vector = bit_vector | mask; 101 | else 102 | bit_vector = bit_vector & ~mask; 103 | return bit_vector; 104 | } 105 | 106 | int createBitVector(string x){ 107 | int i, bit_vector = 0; 108 | FOR(i, 0, x.length()){ 109 | bit_vector = toggle(getFrequency(x[i]), bit_vector); 110 | } 111 | return bit_vector; 112 | } 113 | 114 | bool checkOneSetBit(int bit_vector){ 115 | return ((bit_vector) & (bit_vector-1) == 0); 116 | } 117 | 118 | bool palindromePermutationBit(string x){ 119 | if(x.length() < 1) return false; 120 | int bit_vector = createBitVector(x); 121 | return bit_vector == 0 || checkOneSetBit(bit_vector); 122 | } 123 | 124 | int main() 125 | { 126 | string ip = "TACTD COA"; 127 | if(palindromePermutation(ip)) cout<<"Yes"<<"\n"; 128 | else cout<<"No"<<"\n"; 129 | if(palindromePermutationCountOnGo(ip)) cout<<"Yes"<<"\n"; 130 | else cout<<"No"<<"\n"; 131 | if(palindromePermutationBit(ip)) cout<<"Yes"<<"\n"; 132 | else cout<<"No"<<"\n"; 133 | return 0; 134 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Loop Detection/loop_detection.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/xdxRbrBUi7 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | Node *insertNodeEnd(int data, Node *head) 93 | { 94 | Node *newNode=createNode(data); 95 | Node *traverse=head; 96 | if(head==NULL){ 97 | newNode->next=NULL; 98 | head=newNode; 99 | return head; 100 | } 101 | while(traverse->next!=NULL) 102 | traverse=traverse->next; 103 | traverse->next=newNode; 104 | newNode->next=NULL; 105 | return head; 106 | } 107 | 108 | Node *isLoop(Node *head){ 109 | if(head == NULL) return NULL; 110 | Node *runner = head, *walker = head; 111 | 112 | while(runner != NULL and runner->next != NULL){ 113 | walker = walker->next; 114 | runner = runner->next->next; 115 | if(runner == walker) break; 116 | } 117 | 118 | if(runner == NULL || runner->next == NULL) return NULL; 119 | walker = head; 120 | while(walker != runner){ 121 | walker = walker->next; 122 | runner = runner->next; 123 | } 124 | return runner; //returns start of loop in linked list 125 | } 126 | 127 | int main(){ 128 | Node *list1 = createNode(3); 129 | list1->next = createNode(6); 130 | list1->next->next = createNode(9); 131 | list1->next->next->next = createNode(12); 132 | list1->next->next->next->next = createNode(15); 133 | list1->next->next->next->next->next = list1->next->next; 134 | Node *start = isLoop(list1); 135 | if(start == NULL) 136 | cout<<"No Loop\n"; 137 | else 138 | cout<<"Detected Loop at node:-"<data<<"\n"; 139 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/One Away/one_away.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/1YN376nxPW 2 | #include // Include every standard library 3 | using namespace std; 4 | 5 | typedef long long LL; 6 | typedef pair pii; 7 | typedef pair pll; 8 | typedef pair pss; 9 | typedef vector vi; 10 | typedef vector vvi; 11 | typedef vector vii; 12 | typedef vector vl; 13 | typedef vector vvl; 14 | 15 | double EPS=1e-9; 16 | int INF=1000000005; 17 | long long INFF=1000000000000000005LL; 18 | double PI=acos(-1); 19 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 20 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 21 | 22 | #define DEBUG fprintf(stderr, "====TESTING====\n") 23 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 24 | #define debug(...) fprintf(stderr, __VA_ARGS__) 25 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 26 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 27 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 28 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 29 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 30 | #define FOREACH(a, b) for (auto&(a) : (b)) 31 | #define REP(i, n) FOR(i, 0, n) 32 | #define REPN(i, n) FORN(i, 1, n) 33 | #define MAX(a, b) a=max(a, b) 34 | #define MIN(a, b) a=min(a, b) 35 | #define SQR(x) ((LL)(x) * (x)) 36 | #define RESET(a, b) memset(a, b, sizeof(a)) 37 | #define fi first 38 | #define se second 39 | #define mp make_pair 40 | #define pb push_back 41 | #define ALL(v) v.begin(), v.end() 42 | #define ALLA(arr, sz) arr, arr + sz 43 | #define SIZE(v) (int)v.size() 44 | #define SORT(v) sort(ALL(v)) 45 | #define REVERSE(v) reverse(ALL(v)) 46 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 47 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 48 | #define PERMUTE next_permutation 49 | #define TC(t) while (t--) 50 | 51 | int getFrequency(char x){ 52 | int ind = -1; 53 | if(x >= 'a' && x <= 'z') 54 | ind = x - 'a'; 55 | if(x >= 'A' && x <= 'Z') 56 | ind = x - 'A'; 57 | return ind; 58 | } 59 | bool oneAwayHashed(string s1, string s2){ 60 | if(s1.length() < 1 || s2.length() < 1) return false; 61 | if(abs(s1.length() - s2.length()) > 1) return false; 62 | 63 | int visited[256] = {0}; 64 | int i,j; 65 | if(s1.length() >= s2.length()){ 66 | s1 = s1; s2 = s2; 67 | } 68 | else{ 69 | s1 = s2; s2 = s1; 70 | } 71 | 72 | FOR(i, 0, s1.length()) visited[s1[i]]++; 73 | FOR(i, 0, s2.length()) visited[s2[i]]--; 74 | 75 | int count = 0; 76 | FOR(i, 0, 256){ 77 | if(visited[i]> 0) 78 | count += visited[i]; 79 | } 80 | return count <= 1; 81 | } 82 | 83 | bool oneAway(string s1, string s2){ 84 | if(s1.length() < 1 || s2.length() < 1) return false; 85 | if(abs(s1.length() - s2.length()) > 1) return false; 86 | 87 | //bigger_str = s1, smaller_str = s2 88 | if(s1.length() >= s2.length()){ 89 | s1 = s1; s2 = s2; 90 | } 91 | else{ 92 | s1 = s2; s2 = s1; 93 | } 94 | cout< "tail" "pale" will break this loop 101 | found = true; 102 | 103 | //replace operation 104 | if(s1.length() == s2.length())j++; //move shorter pointer only when both strings are of same length. 105 | //If they are moved when they are of unequal lengths; it will be big problem 106 | /* 107 | Example: bale and pal 108 | b != p:- and len(bale) != len(pal) So increment only i here. 109 | i.e. increment only longer pointer to bring the [b + len(ale)] and len(pal) in sync for next iteration 110 | */ 111 | } 112 | else 113 | j++; //move shorter pointer ahead when both chars in s1 and s3 are ruqal 114 | i++; //increment longer pointer always while scanning. 115 | } 116 | return true; 117 | } 118 | 119 | int main() 120 | { 121 | string s1 = "pale", s2 = "bale", s3 = "pale", s4 = "pal", s5 = "bble", s6 = "xale"; 122 | cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | Node *insertNodeEnd(int data, Node *head) 93 | { 94 | Node *newNode=createNode(data); 95 | Node *traverse=head; 96 | if(head==NULL){ 97 | newNode->next=NULL; 98 | head=newNode; 99 | return head; 100 | } 101 | while(traverse->next!=NULL) 102 | traverse=traverse->next; 103 | traverse->next=newNode; 104 | newNode->next=NULL; 105 | return head; 106 | } 107 | 108 | Node *isLoop(Node *head){ 109 | if(head == NULL) return NULL; 110 | Node *runner = head, *walker = head; 111 | 112 | while(runner != NULL and runner->next != NULL){ 113 | walker = walker->next; 114 | runner = runner->next->next; 115 | if(runner == walker) break; 116 | } 117 | 118 | if(runner == NULL || runner->next == NULL) return NULL; 119 | walker = head; 120 | while(walker != runner){ 121 | walker = walker->next; 122 | runner = runner->next; 123 | } 124 | return runner; //returns start of loop in linked list 125 | } 126 | 127 | 128 | int main(){ 129 | Node *list1 = createNode(3); 130 | list1->next = createNode(6); 131 | list1->next->next = createNode(9); 132 | list1->next->next->next = createNode(12); 133 | list1->next->next->next->next = createNode(15); 134 | list1->next->next->next->next->next = list1->next->next; 135 | Node *start = isLoop(list1); 136 | if(start == NULL) 137 | cout<<"No Loop\n"; 138 | else{ 139 | cout<<"Detected Loop at node:- "<data<<"\n"; 140 | Node *np = start; 141 | while(np->next != start) 142 | np = np->next; 143 | np->next = NULL; 144 | cout<<"Removed Loop after node:- "<data<<"\n"; 145 | printLL(list1); 146 | } 147 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Sum Lists/sum_lists_forward1.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/FMjQyB0bkf 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | void *insertNode(int data, Node * &head){ 82 | Node *newNode = createNode(data); 83 | newNode->next = head; 84 | head = newNode; 85 | } 86 | 87 | Node *insertNodeEnd(int data, Node *head) 88 | { 89 | Node *newNode=createNode(data); 90 | Node *traverse=head; 91 | if(head==NULL){ 92 | newNode->next=NULL; 93 | head=newNode; 94 | return head; 95 | } 96 | while(traverse->next!=NULL) 97 | traverse=traverse->next; 98 | traverse->next=newNode; 99 | newNode->next=NULL; 100 | return head; 101 | } 102 | 103 | void *pad(Node * &head1, int diff){ 104 | Node *head = head1; 105 | for(int i=0; inext : NULL, head2 ? head2->next : NULL, carry); 113 | int sum = carry + (head1 ? head1->data :0) + (head2 ? head2->data :0); 114 | insertNode(sum % 10, result); 115 | carry = (sum > 9) ? 1: 0; 116 | return result; 117 | } 118 | 119 | Node *addition_by_lists(Node *head1, Node *head2){ 120 | int l1 = countLL(head1); 121 | int l2 = countLL(head2); 122 | if(l1 < l2) 123 | pad(head1, abs(l1-l2)); 124 | else 125 | pad(head2, abs(l1-l2)); 126 | int carry = 0; 127 | Node *result_f = add_lists_sz(head1, head2, carry); 128 | if(carry){ 129 | insertNode(carry, result_f); 130 | } 131 | return result_f; 132 | } 133 | 134 | int main(){ 135 | Node *head1 = NULL, *head2 = NULL; 136 | int m, n, data, i; 137 | cin>>m>>n; 138 | FOR(i, 0, m){ 139 | cin>>data; 140 | head1 = insertNodeEnd(data, head1); 141 | } 142 | //printLL(head1); 143 | 144 | FOR(i, 0, n){ 145 | cin>>data; 146 | head2 = insertNodeEnd(data, head2); 147 | } 148 | //printLL(head2); 149 | cout<<"\n"; 150 | //Node *head = 151 | Node *f_r = addition_by_lists(head1, head2); 152 | printLL(f_r); 153 | } -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Zero Matrix/zero_matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/cIVwnlYTED 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | void printMatrix(vector > matrix, int n){ 52 | int i, j; 53 | FOR(i, 0, n){ 54 | FOR(j, 0, n) 55 | cout< > &fill, int row){ 61 | int i; 62 | FOR(i, 0, fill.size()) 63 | fill[row][i] = 0; 64 | } 65 | 66 | void nullifyCol(vector > &fill, int col){ 67 | int i; 68 | FOR(i, 0, fill[0].size()) 69 | fill[i][col] = 0; 70 | } 71 | void setZero(vector > &fill, int n){ 72 | if(fill[0].size() <= 0 || fill.size() <= 0) return; 73 | int rsz = fill.size(), csz = fill[0].size(); 74 | vector rowZero(rsz, 0); 75 | vector colZero(csz, 0); 76 | int i,j; 77 | FOR(i, 0, n){ 78 | FOR(j, 0, n){ 79 | if(fill[i][j]==0){ 80 | rowZero[i] = 1; 81 | colZero[j] = 1; 82 | } 83 | } 84 | } 85 | 86 | FOR(i, 0, fill.size()){ 87 | if(rowZero[i]) 88 | nullifyRow(fill, i); 89 | } 90 | 91 | FOR(j, 0, fill[0].size()){ 92 | if(colZero[j]) 93 | nullifyCol(fill, j); 94 | } 95 | } 96 | 97 | void setZeroSpaceOptimised(vector > &fill, int n){ 98 | if(fill.size() <= 0 || fill[0].size() <= 0) return; 99 | //check for 0th rows and cols and set the bools if 0 is present 100 | //check remaining matrix and if any 0 found set i0 or 0j 101 | //next nullify all rows and cols for which i0 or 0j is true 102 | //recheck the true set in step 1 and nullify the 0th col and row 103 | bool row_zero = false, col_zero = false; 104 | int i,j,k,l; 105 | 106 | FOR(i, 0, fill[0].size()) 107 | if(fill[i][0] == 0){ 108 | col_zero = true; 109 | break; 110 | } 111 | 112 | FOR(i, 0, fill.size()) 113 | if(fill[0][i] == 0){ 114 | row_zero = true; 115 | break; 116 | } 117 | 118 | FOR(i, 1, fill.size()){ 119 | FOR(j, 1, fill[0].size()){ 120 | if(fill[i][j] == 0){ 121 | fill[i][0] = 0; 122 | fill[0][j] = 0; 123 | } 124 | } 125 | } 126 | 127 | FOR(i, 1, fill.size()){ 128 | if(fill[i][0] == 0) 129 | nullifyRow(fill, i); 130 | } 131 | 132 | FOR(j, 1, fill[0].size()){ 133 | if(fill[0][j] == 0) 134 | nullifyCol(fill, j); 135 | } 136 | 137 | if(row_zero) 138 | nullifyRow(fill, 0); 139 | if(col_zero) 140 | nullifyCol(fill, 0); 141 | 142 | // printMatrix(fill, n); 143 | } 144 | 145 | int main() 146 | { 147 | int n, i, j; 148 | cin>>n; //dimension 149 | vector > fill(n); 150 | int x; 151 | FOR(i, 0, n){ 152 | FOR(j, 0, n){ 153 | cin>>x; 154 | fill[i].push_back(x); 155 | } 156 | } 157 | printMatrix(fill, n); 158 | //setZero(fill, n); 159 | //cout<<"Set to Zero:-\n"; 160 | //printMatrix(fill, n); 161 | setZeroSpaceOptimised(fill, n); 162 | cout<<"Set to Zero Optimised:-\n"; 163 | printMatrix(fill, n); 164 | return 0; 165 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Palindrome/palindrome.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/QF136EYlfH 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | Node *insertNodeEnd(int data, Node *head) 93 | { 94 | Node *newNode=createNode(data); 95 | Node *traverse=head; 96 | if(head==NULL){ 97 | newNode->next=NULL; 98 | head=newNode; 99 | return head; 100 | } 101 | while(traverse->next!=NULL) 102 | traverse=traverse->next; 103 | traverse->next=newNode; 104 | newNode->next=NULL; 105 | return head; 106 | } 107 | 108 | //Stack based extra space 109 | bool isSLLPalindrome1(Node *head){ 110 | if(head == NULL) return false; 111 | Node *walker = head, *runner = head; 112 | stack st; 113 | 114 | while(runner!=NULL && runner->next!=NULL){ 115 | st.push((int)walker->data); 116 | walker = walker->next; 117 | runner = runner->next->next; 118 | } 119 | if(runner!=NULL) 120 | walker = walker->next; 121 | 122 | while(walker != NULL){ 123 | int top = (int)st.top(); 124 | cout<data) 127 | return false; 128 | walker = walker->next; 129 | } 130 | return true; 131 | } 132 | 133 | 134 | Node *reverseLL(Node *head){ 135 | Node *current = head, *next = NULL, *prev = NULL; 136 | 137 | while(current != NULL){ 138 | next = current->next; 139 | current->next = prev; 140 | prev = current; 141 | current = current->next; 142 | } 143 | head = prev; 144 | return head; 145 | } 146 | 147 | bool isEqual(Node *head, Node *rev){ 148 | if(head == NULL || rev == NULL) return false; 149 | 150 | while(head != NULL && rev != NULL){ 151 | if(head->data != rev->data)return false; 152 | head = head->next; 153 | rev = rev->next; 154 | } 155 | return head == NULL && rev == NULL; 156 | } 157 | 158 | //reverse SLL 159 | bool isSLLPalindrome2(Node *head){ 160 | if(head == NULL) return false; 161 | Node *revhead = reverseLL(head); 162 | bool res = isEqual(head, revhead); 163 | if(res)cout<<"1\n"; 164 | else cout<<"0\n"; 165 | } 166 | 167 | int main(){ 168 | Node *head = NULL; 169 | int n,data, i; cin>>n; 170 | FOR(i, 0, n){ 171 | cin>>data; 172 | head = insertNodeEnd(data, head); 173 | } 174 | printLL(head); 175 | cout<<"\n"; 176 | cout< // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | void countLL(Node *head){ 72 | if(head == NULL)return; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | } 79 | 80 | Node *insertNode(int data, Node *head){ 81 | Node *newNode = createNode(data); 82 | if(head == NULL) 83 | head = newNode; 84 | else{ 85 | head->next = newNode; 86 | head = newNode; 87 | } 88 | return head; 89 | } 90 | 91 | Node *insertNodeEnd(int data, Node *head) 92 | { 93 | Node *newNode=createNode(data); 94 | Node *traverse=head; 95 | if(head==NULL){ 96 | newNode->next=NULL; 97 | head=newNode; 98 | return head; 99 | } 100 | while(traverse->next!=NULL) 101 | traverse=traverse->next; 102 | traverse->next=newNode; 103 | newNode->next=NULL; 104 | return head; 105 | } 106 | 107 | //Non stable version 108 | //Extra space --> Use 2 ll pointers and seggregate based on x 109 | Node *partitionUnstable(Node *head, int x){ 110 | if(head == NULL) return NULL; 111 | 112 | Node *curr = head, *tail = head; 113 | 114 | while(curr != NULL){ 115 | Node *next = curr->next; 116 | 117 | if(curr->data < x){ 118 | curr->next = head; 119 | head = curr; 120 | } 121 | else{ 122 | tail->next = curr; 123 | tail = curr; 124 | } 125 | curr = next; 126 | } 127 | tail->next = NULL; 128 | return head; 129 | } 130 | 131 | 132 | //Stable version 133 | //Use 2 queue and dummy nodes 134 | Node *partitionStable(Node *head, int x){ 135 | if(head == NULL) return NULL; 136 | Node *d1 = createNode(0); 137 | d1->next = head; 138 | //cout<data<<"\n"; 139 | Node *d2 = createNode(0); 140 | //cout<data<<"\n"; 141 | Node *x1 = d1, *x2 = d2; 142 | 143 | while(head != NULL){ 144 | if(head->data < x){ 145 | x1->next = head; 146 | x1 = x1->next; 147 | } 148 | else{ 149 | x2->next = head; 150 | x2 = x2->next; 151 | } 152 | head = head->next; 153 | } 154 | x2->next = NULL; 155 | x1->next = d2->next; 156 | return d1->next; 157 | } 158 | 159 | 160 | int main(){ 161 | /*Node* head = createNode(1); 162 | head->next = createNode(2); 163 | head->next->next = createNode(3); 164 | head->next->next->next = createNode(4); 165 | head->next->next->next->next = createNode(4);*/ 166 | 167 | //n - number of nodes in LL 168 | 169 | Node *head = NULL; 170 | int n,data, i; cin>>n; 171 | FOR(i, 0, n){ 172 | cin>>data; 173 | head = insertNodeEnd(data, head); 174 | } 175 | printLL(head); 176 | //cout<<"\n"; 177 | //head = partitionUnstable(head, 5); 178 | //printLL(head); 179 | cout<<"\n"; 180 | head = partitionStable(head, 5); 181 | printLL(head); 182 | } 183 | -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Sum Lists/sum_lists_backward.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/9tF9U5WhpC 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | void countLL(Node *head){ 72 | if(head == NULL)return; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | } 79 | 80 | Node *insertNode(int data, Node *head){ 81 | Node *newNode = createNode(data); 82 | if(head == NULL) 83 | head = newNode; 84 | else{ 85 | head->next = newNode; 86 | head = newNode; 87 | } 88 | return head; 89 | } 90 | 91 | Node *insertNodeEnd(int data, Node *head) 92 | { 93 | Node *newNode=createNode(data); 94 | Node *traverse=head; 95 | if(head==NULL){ 96 | newNode->next=NULL; 97 | head=newNode; 98 | return head; 99 | } 100 | while(traverse->next!=NULL) 101 | traverse=traverse->next; 102 | traverse->next=newNode; 103 | newNode->next=NULL; 104 | return head; 105 | } 106 | 107 | /* 108 | Least significant digit(Unit's place) --> on left 109 | Most significant digit(Hundred's place) --> on right 110 | If the numbers are 321 and 654, the LL will be represented as:- 111 | 1->2->3 112 | 4->5->6 113 | Now even if the LL's are of different size it doesnt matter here. 114 | Because we are dealing with units to hundred's place from L-R 115 | */ 116 | 117 | Node *addrecursive(Node *head1, Node *head2, int carry){ 118 | if(head1 == NULL && head2 == NULL && carry == 0) return NULL; 119 | int sum = carry; 120 | if(head1) 121 | sum += head1->data; 122 | if(head2) 123 | sum += head2->data; 124 | //carry = sum > 9 ? 1 : 0; 125 | //sum = sum % 10; 126 | Node *result = createNode(sum % 10); 127 | result->next = addrecursive(head1 ? head1->next : NULL, head2 ? head2->next : NULL, carry); 128 | return result; 129 | } 130 | 131 | Node *addition_by_lists(Node *head1, Node *head2){ 132 | if(head1 == NULL || head2 == NULL) return NULL; 133 | Node *temp, *prev = NULL; 134 | Node *result = NULL; 135 | int sum, carry = 0; 136 | 137 | while(head1 != NULL || head2 != NULL){ 138 | sum = carry + (head1 ? head1->data:0) + (head2 ? head2->data:0); 139 | 140 | if(sum >= 10) 141 | carry = 1; 142 | else 143 | carry = 0; 144 | sum %= 10; 145 | 146 | temp = createNode(sum); 147 | 148 | if(result == NULL) 149 | result = temp; 150 | else 151 | prev->next = temp; 152 | prev = temp; 153 | 154 | if(head1) head1 = head1->next; 155 | if(head2) head2 = head2->next; 156 | } 157 | if(carry > 0) 158 | temp->next = createNode(carry); 159 | return result; 160 | } 161 | 162 | int main(){ 163 | Node *head1 = NULL, *head2 = NULL; 164 | int m, n, data, i; 165 | cin>>m>>n; 166 | FOR(i, 0, m){ 167 | cin>>data; 168 | head1 = insertNodeEnd(data, head1); 169 | } 170 | //printLL(head1); 171 | 172 | FOR(i, 0, n){ 173 | cin>>data; 174 | head2 = insertNodeEnd(data, head2); 175 | } 176 | //printLL(head2); 177 | cout<<"\n"; 178 | //Node *head = addition_by_lists(head1, head2); 179 | //printLL(head); 180 | 181 | //printLL(head2); 182 | cout<<"\n"; 183 | Node *head4 = addrecursive(head1, head2, 0); 184 | printLL(head4); 185 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Sum Lists/sum_lists_forward.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/elbhFhdSAG 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | Node *insertNodeEnd(int data, Node *head) 93 | { 94 | Node *newNode=createNode(data); 95 | Node *traverse=head; 96 | if(head==NULL){ 97 | newNode->next=NULL; 98 | head=newNode; 99 | return head; 100 | } 101 | while(traverse->next!=NULL) 102 | traverse=traverse->next; 103 | traverse->next=newNode; 104 | newNode->next=NULL; 105 | return head; 106 | } 107 | 108 | /* 109 | Here we perform LL addition as the numbers appear in the input 110 | The size of both the LL's matter here because the hundredth's place is on left followed by unit's to the right 111 | 112 | 3 2 1 -A 113 | 8 9 6 -B 114 | 115 | 4 5 6 -C 116 | 8 9 -D 117 | 118 | A and B has no issues. C and D will have a problem as 8 gets aligned to hundredth's place. 119 | However its actual place value is tens place 120 | */ 121 | 122 | Node *addition_same_sz(Node *head1, Node* head2, int *carry){ 123 | if(head1 == NULL || head2 == NULL)return NULL; 124 | int sum; 125 | Node *result = new Node(); 126 | result->next = addition_same_sz(head1->next, head2->next, carry); 127 | sum = head1->data + head2->data + *carry; 128 | *carry = sum/10; 129 | sum = sum % 10; 130 | result->data = sum; 131 | return result; 132 | } 133 | 134 | void swapHeads(Node **a, Node **b){ 135 | Node *t = *a; 136 | *a = *b; 137 | *b = t; 138 | } 139 | 140 | void push(struct Node** head_ref, int new_data) 141 | { 142 | Node *new_node = new Node(); 143 | new_node->data = new_data; 144 | new_node->next = (*head_ref); 145 | (*head_ref) = new_node; 146 | } 147 | 148 | void add_carry_to_remaining(Node *head1, Node *curr, int *carry, Node **result){ 149 | int sum; 150 | if(head1 != curr){ 151 | add_carry_to_remaining(head1->next, curr, carry, result); 152 | sum = head1->data + *carry; 153 | *carry = sum/10; 154 | sum %= 10; 155 | } 156 | push(result, sum); 157 | } 158 | 159 | void addition_by_lists_forward(Node *head1, Node *head2, Node **result){ 160 | if(head1 == NULL){ 161 | *result = head2; 162 | return; 163 | } 164 | if(head2 == NULL) 165 | { 166 | *result = head1; 167 | return; 168 | } 169 | Node *curr; 170 | int length1 = countLL(head1); 171 | int length2 = countLL(head2); 172 | int carry = 0; 173 | 174 | if(length1 == length2){ 175 | *result = addition_same_sz(head1, head2, &carry); 176 | } 177 | 178 | else{ 179 | int diff = abs(length1 - length2); 180 | if(length1 < length2){ 181 | swapHeads(&head1, &head2); 182 | } 183 | curr = head1; 184 | while(diff--) 185 | curr = curr->next; 186 | 187 | *result = addition_same_sz(curr, head2, &carry); 188 | add_carry_to_remaining(head1, curr, &carry, result); 189 | } 190 | 191 | if(carry) 192 | push(result, carry); 193 | } 194 | 195 | int main(){ 196 | Node *head1 = NULL, *head2 = NULL; 197 | int m, n, data, i; 198 | cin>>m>>n; 199 | FOR(i, 0, m){ 200 | cin>>data; 201 | head1 = insertNodeEnd(data, head1); 202 | } 203 | 204 | FOR(i, 0, n){ 205 | cin>>data; 206 | head2 = insertNodeEnd(data, head2); 207 | } 208 | Node *result = NULL; 209 | addition_by_lists_forward(head1, head2, &result); 210 | printLL(result); 211 | } -------------------------------------------------------------------------------- /Chapter 2 - Linked Lists/Remove Dups/remove_dups.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/iD9gf1qZBS 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | void countLL(Node *head){ 72 | if(head == NULL)return; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | } 79 | 80 | Node *insertNode(int data, Node *head){ 81 | Node *newNode = createNode(data); 82 | if(head == NULL) 83 | head = newNode; 84 | else{ 85 | head->next = newNode; 86 | head = newNode; 87 | } 88 | return head; 89 | } 90 | 91 | Node *insertNodeEnd(int data, Node *head) 92 | { 93 | Node *newNode=createNode(data); 94 | Node *traverse=head; 95 | if(head==NULL){ 96 | newNode->next=NULL; 97 | head=newNode; 98 | return head; 99 | } 100 | while(traverse->next!=NULL) 101 | traverse=traverse->next; 102 | traverse->next=newNode; 103 | newNode->next=NULL; 104 | return head; 105 | } 106 | 107 | //O(n^2) 108 | Node *removedupsNormal(Node *head){ 109 | if(head == NULL) return NULL; 110 | Node *walker = head; 111 | Node *runner; 112 | while(walker != NULL){ 113 | runner = walker; 114 | while(runner->next != NULL){ 115 | if(runner->next->data == walker->data){ 116 | Node *temp = runner->next; 117 | runner->next = runner->next->next; 118 | delete temp; 119 | } 120 | else 121 | runner = runner->next; 122 | } 123 | walker = walker->next; 124 | } 125 | return head; 126 | } 127 | 128 | //O(n) 129 | //this fails for testcase 1 2 3 4 4 3 : it checks removes only consecutive dups 130 | Node *removedupsHashed(Node *head){ 131 | if(head == NULL)return NULL; 132 | vector count_int(256, 0); 133 | 134 | Node *prev = head; 135 | Node *current = prev->next; 136 | 137 | while(current != NULL){ 138 | if(count_int[current->data] == 1){ 139 | Node *temp = current; 140 | if(current->next != NULL){ 141 | current = current->next; 142 | prev->next = current; 143 | } 144 | else 145 | prev->next = NULL; 146 | delete temp; 147 | } 148 | else 149 | count_int[current->data] = 1; 150 | prev = current; 151 | current = current->next; 152 | } 153 | return head; 154 | } 155 | 156 | Node *removedupsSet(Node *head){ 157 | if(head == NULL)return NULL; 158 | set count_int; 159 | Node *prev = head; 160 | Node *current = prev->next; 161 | 162 | while(current != NULL){ 163 | if(count_int.find(current->data) != count_int.end()){ 164 | Node *temp = current; 165 | if(current->next != NULL){ 166 | current = current->next; 167 | prev->next = current; 168 | } 169 | else 170 | prev->next = NULL; 171 | delete temp; 172 | } 173 | else 174 | count_int.insert(current->data); 175 | prev = current; 176 | current = current->next; 177 | } 178 | return head; 179 | } 180 | 181 | int main(){ 182 | /*Node* head = createNode(1); 183 | head->next = createNode(2); 184 | head->next->next = createNode(3); 185 | head->next->next->next = createNode(4); 186 | head->next->next->next->next = createNode(4);*/ 187 | 188 | //n - number of nodes in LL 189 | 190 | Node *head = NULL; 191 | int n,data, i; cin>>n; 192 | FOR(i, 0, n){ 193 | cin>>data; 194 | head = insertNodeEnd(data, head); 195 | } 196 | printLL(head); 197 | cout<<"\n"; 198 | removedupsHashed(head); 199 | printLL(head); 200 | cout<<"\n"; 201 | removedupsNormal(head); 202 | printLL(head); 203 | cout<<"\n"; 204 | removedupsSet(head); 205 | printLL(head); 206 | } 207 | 208 | /* 209 | 5 210 | 1 2 3 4 4 211 | 6 212 | 1 2 3 4 4 5 213 | */ -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Rotate Matrix/rotate_matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://ide.geeksforgeeks.org/BvVj4bLVkH 2 | #include // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | /* 52 | Approach 1: Take transpose of cp_my_ip and then reverse the rows for clockwise 90' rotation. 53 | Obviously if we reverse the columns we will get anticlockwise 90' rotation. 54 | Approach 2: As mentioned in the book, rotating invididual elements layer by layer. 55 | I have solved it perform anticlockwise 90' rotation, it can be done similarly for clockwise rotatation. 56 | */ 57 | /* 58 | Anticlockwise: Find transpose of cp_my_ip(Tm) and then reverse columns of Tm 59 | Clockwise: Find Tm and then reverse rows of TM 60 | */ 61 | 62 | void transpose(vector > &a, int n){ 63 | for(int i=0; i > &to_reverse, int n){ 71 | for(int i=0; i > &to_reverse, int n){ 79 | for(int i=0; i>n; 89 | vector > my_ip(n); 90 | int x; 91 | for(int i=0; i>x; 94 | my_ip[i].push_back(x); 95 | } 96 | } 97 | auto cp_my_ip = my_ip; 98 | 99 | cout<<"Approach 1:-\n"; 100 | 101 | //clockwise :- transpose + rowwise transformation 102 | /* 103 | 1 2 3 1 4 7 7 4 1 104 | 4 5 6 --> 2 5 8 --> 8 5 2 105 | 7 8 9 3 6 9 9 6 3 106 | */ 107 | 108 | 109 | //anticlockwise :- transpose + rowwise + columnwise + rowwise transformation 110 | /* 111 | 1 2 3 1 4 7 7 4 1 9 6 3 3 6 9 112 | 4 5 6 --> 2 5 8 --> 8 5 2 --> 8 5 2 --> 2 5 8 113 | 7 8 9 3 6 9 9 6 3 7 4 1 1 4 7 114 | */ 115 | 116 | transpose(my_ip, n); 117 | cout<<"Transposed:-\n"; 118 | for(int i=0; i for 4x4 cp_my_ip, it will have 2 layers 159 | { 160 | first = level; 161 | last = n - first - 1; 162 | for (int element = first; element < last; element++){ 163 | int offset = element - first; 164 | int topleft = cp_my_ip[first][element]; 165 | int topright = cp_my_ip[element][last]; 166 | int bottomright = cp_my_ip[last][last - offset]; 167 | int bottomleft = cp_my_ip[last - offset][first]; 168 | cp_my_ip[first][element] = bottomleft; 169 | cp_my_ip[element][last] = topleft; 170 | cp_my_ip[last][last - offset] = topright; 171 | cp_my_ip[last - offset][first] = bottomright; 172 | //shifting the col value to its pos, since its a clockwise rotation so, seven will be at 1 173 | } 174 | 175 | } 176 | //clockwise 90 degrees 177 | cout<<"Clockwise 90 degrees\n"; 178 | for(int i=0; i // Include every standard library 3 | using namespace std; 4 | typedef long long LL; 5 | typedef pair pii; 6 | typedef pair pll; 7 | typedef pair pss; 8 | typedef vector vi; 9 | typedef vector vvi; 10 | typedef vector vii; 11 | typedef vector vl; 12 | typedef vector vvl; 13 | 14 | double EPS=1e-9; 15 | int INF=1000000005; 16 | long long INFF=1000000000000000005LL; 17 | double PI=acos(-1); 18 | int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 }; 19 | int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 }; 20 | 21 | #define DEBUG fprintf(stderr, "====TESTING====\n") 22 | #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 23 | #define debug(...) fprintf(stderr, __VA_ARGS__) 24 | #define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a)) 25 | #define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a)) 26 | #define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a)) 27 | #define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a)) 28 | #define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a)) 29 | #define FOREACH(a, b) for (auto&(a) : (b)) 30 | #define REP(i, n) FOR(i, 0, n) 31 | #define REPN(i, n) FORN(i, 1, n) 32 | #define MAX(a, b) a=max(a, b) 33 | #define MIN(a, b) a=min(a, b) 34 | #define SQR(x) ((LL)(x) * (x)) 35 | #define RESET(a, b) memset(a, b, sizeof(a)) 36 | #define fi first 37 | #define se second 38 | #define mp make_pair 39 | #define pb push_back 40 | #define ALL(v) v.begin(), v.end() 41 | #define ALLA(arr, sz) arr, arr + sz 42 | #define SIZE(v) (int)v.size() 43 | #define SORT(v) sort(ALL(v)) 44 | #define REVERSE(v) reverse(ALL(v)) 45 | #define SORTA(arr, sz) sort(ALLA(arr, sz)) 46 | #define REVERSEA(arr, sz) reverse(ALLA(arr, sz)) 47 | #define PERMUTE next_permutation 48 | #define TC(t) while (t--) 49 | #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) 50 | 51 | struct Node{ 52 | int data; 53 | struct Node *next; 54 | }; 55 | 56 | Node* createNode(int data){ 57 | Node *new_node = new Node(); 58 | new_node->data = data; 59 | new_node->next = NULL; 60 | return new_node; 61 | } 62 | 63 | void printLL(Node *head){ 64 | if(head == NULL)return; 65 | while(head != NULL){ 66 | cout<data<<" "; 67 | head = head->next; 68 | } 69 | } 70 | 71 | int countLL(Node *head){ 72 | if(head == NULL)return 0; 73 | int node_count = 0; 74 | while(head != NULL){ 75 | node_count++; 76 | head = head->next; 77 | } 78 | return node_count; 79 | } 80 | 81 | Node *insertNode(int data, Node *head){ 82 | Node *newNode = createNode(data); 83 | if(head == NULL) 84 | head = newNode; 85 | else{ 86 | newNode->next = head; 87 | head = newNode; 88 | } 89 | return head; 90 | } 91 | 92 | 93 | Node *insertNodeEnd(int data, Node *head) 94 | { 95 | Node *newNode=createNode(data); 96 | Node *traverse=head; 97 | if(head==NULL){ 98 | newNode->next=NULL; 99 | head=newNode; 100 | return head; 101 | } 102 | while(traverse->next!=NULL) 103 | traverse=traverse->next; 104 | traverse->next=newNode; 105 | newNode->next=NULL; 106 | return head; 107 | } 108 | 109 | 110 | bool checkTail(Node *he, Node *she){ 111 | if(he == NULL && she == NULL)return 0; 112 | while(he->next != NULL) 113 | he = he->next; 114 | 115 | while(she->next != NULL) 116 | she = she->next; 117 | 118 | if(he == she){ 119 | cout<data<<"\n"; 120 | return 1; 121 | } 122 | else return 0; 123 | } 124 | 125 | Node *incrementPointer(Node* head, int diff){ 126 | if(head == NULL) return NULL; 127 | int i; 128 | FOR(i, 0, diff){ 129 | if(head == NULL) return NULL; 130 | head = head->next; 131 | } 132 | return head; 133 | } 134 | 135 | Node *intersectionHelper(Node *zack, Node *cody){ 136 | if(zack == NULL && cody == NULL)return NULL; 137 | while(zack && cody){ 138 | if(zack == cody) 139 | return zack; 140 | zack = zack->next; 141 | cody = cody->next; 142 | } 143 | return NULL; 144 | } 145 | 146 | Node *checkIntersection(Node *harry, Node *potter){ 147 | if(harry == NULL && potter == NULL)return NULL; 148 | if(!checkTail(harry, potter)) return NULL; 149 | 150 | int h_length = countLL(harry), p_length = countLL(potter); 151 | cout<<"\n"< p_length && diff_hp > 0){ 157 | new_hp = incrementPointer(harry, diff_hp); 158 | cout<<"New pointer:"<data<<"\n"; 159 | if(new_hp == NULL) return NULL; 160 | i_intersection = intersectionHelper(new_hp, potter); 161 | } 162 | else if(h_length < p_length && diff_hp > 0){ 163 | new_hp = incrementPointer(potter, diff_hp); 164 | cout<<"New pointer:"<data<<"\n"; 165 | if(new_hp == NULL) return NULL; 166 | i_intersection = intersectionHelper(new_hp, potter); 167 | } 168 | else{ 169 | cout<<"Something is wrong!!\n"; 170 | exit(0); 171 | } 172 | return i_intersection; 173 | } 174 | 175 | int main(){ 176 | /*Node *list1 = NULL, *list2 = NULL; 177 | int n, m, data, i; 178 | cin>>n>>m; 179 | 180 | FOR(i, 0, n){ 181 | cin>>data; 182 | list1 = insertNode(data, list1); 183 | } 184 | 185 | FOR(i, 0, m){ 186 | cin>>data; 187 | list2 = insertNode(data, list2); 188 | }*/ 189 | 190 | Node *list1 = createNode(3); 191 | list1->next = createNode(6); 192 | list1->next->next = createNode(9); 193 | list1->next->next->next = createNode(12); 194 | list1->next->next->next->next = createNode(15); 195 | list1->next->next->next->next->next = createNode(18); 196 | 197 | Node * list2 = createNode(7); 198 | list2->next = createNode(10); 199 | list2->next->next = list1->next->next->next; 200 | 201 | printLL(list1); 202 | cout<<"\n"; 203 | printLL(list2); 204 | 205 | Node *intersect = checkIntersection(list1, list2); 206 | if(intersect == NULL)cout<<"Intersection node not found!!"; 207 | else cout<<"Intersection node is:-"<data<<""; 208 | } -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Cracking the Coding Interview (CtCI) Solutions" 2 | 3 | This repository contains C++ and Python solutions to the problems in the sixth edition of [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/) by [Gayle Lackmann McDowell](http://www.gayle.com/). 4 | 5 | ### Chapter 1: 6 | 7 | * Is Unique - _Determine if a string has all unique characters_ **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#is-unique)** 8 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/Is%20Unique/is_unique.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Is%20Unique/is_unique.cpp)_** 9 | * Check Permutation - _Check if one string is a permutation of another_ **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#check-permutation)** 10 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/Check%20Permutation/check_permutation.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Check%20Permutation/check_permutation.py)_** 11 | * URLify - _Replace all spaces in string with '%20'_ **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#urlify)** 12 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/URLify/urlify.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/URLify/urlify.py)_** 13 | * Palindrome Permutation - *_Check if string is permutation of its palindrome_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#palindrome-permutation)** 14 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/Palindrome%20Permutation/palindrome_permutation.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Palindrome%20Permutation/palindrome_permutation.py)_** 15 | * One Away - *_Check if two strings are one or zero edits away_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#one-away)** 16 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/One%20Away/one_away.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/One%20Away/one_away.py)_** 17 | * String Compression - *_Perform string compression using counts of repeated characters_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#string-compression)** 18 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/String%20Compression/string_compression.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/String%20Compression/string_compression.py)_** 19 | * Rotate Matrix - *_Rotate given nxn image by 90 degrees inplace_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#rotate-matrix)** 20 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/Rotate%20Matrix/rotate_matrix.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Rotate%20Matrix/rotate_matrix.py)_** 21 | * Zero Matrix - *_Replace other elements in rows and columns if element is 0_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#zero-matrix)** 22 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/Zero%20Matrix/zero_matrix.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Zero%20Matrix/zero_matrix.py)_** 23 | * String Rotation - *_Check if string s2 is rotation of string s1 using isSubstring()_* **_→_** **[Overview](/Chapter%201%20-%20Arrays%20and%20Strings#string-rotation)** 24 | * **_[C++](/Chapter%201%20-%20Arrays%20and%20Strings/String%20Rotation/string_rotation.cpp)_** **|** **_[Python](/Chapter%201%20-%20Arrays%20and%20Strings/Zero%20Matrix/string_rotation.py)_** 25 | 26 | ### Chapter 2: 27 | * Remove Dups - *_Remove duplicates from unsorted linked list_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Remove%20Dups/remove_dups.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Remove%20Dups/remove_dups.py)_** 28 | * Return Kth To Last - *_Find kth to last element of singly linked list_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Return%20Kth%20To%20Last/return_kth_to_last.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Return%20Kth%20To%20Last/return_kth_to_last.py)_** 29 | * Delete middle node - *_Delete a node in middle of singly linked list_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Delete%20Middle%20node/delete_middle_node.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Delete%20Middle%20node%20/delete_middle_node.py)_** 30 | * Partition - *_Partition singly linked list around x_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Partition/partition.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Partition/partition.py)_** 31 | * Intersection - *_Given 2 SLL, check if they intersect_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Intersection/Intersection.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Intersection/Intersection.py)_** 32 | * Loop Detection - *_Detect loop in Circular Linked List_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Loop%20Detection/loop_detection.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Loop%20Detection/loop_detection.py)_** 33 | * Sum Lists - *_Add 2 numbers represented by Linked Lists_* **_→_** **_[C++](/Chapter%202%20-%20Linked%20Lists/Sum%20Lists/sum_lists_forward1.cpp)_** **|** **_[Python](/Chapter%202%20-%20Linked%20Lists/Sum%20Lists/sum_lists_backward.py)_** 34 | 35 | ### Chapter 3: 36 | * Three In One - *_Implement k(3) stacks using single array_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Three%20in%20One/three_in_one.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Three%20in%20One/three_in_one.py)_** 37 | * Stack Min - *_Design min stack that performs push, pop and min in O(1)_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Stacks%20Min/stack_min.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Stack%20Min/stack_min.py)_** 38 | * Stack Of Plates - *_Implement set of stacks with popAt operation_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Stack%20Of%20Plates/stack_of_plates.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Stack%20Of%20Plates/stack_of_plates.py)_** 39 | * Queue Via Stacks - *_Implement queue data structure with 2 stacks_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Queue%20Via%20Stacks/queue_via_stacks.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Queue%20Via%20Stacks/queue_via_stacks.py)_** 40 | * Sort Stacks - *_Sort stack in ascending order using a temporary stack_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Sort%20Stack/sort_stack.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Sort%20Stack/sort_stack.py)_** 41 | * Animal Shelter - *_Design system to allocate animals on FIFO basis from animal shelter_* **_→_** **_[C++](/Chapter%203%20-%20Stacks%20and%20Queues/Animal%20Shelter/animal_shelter.cpp)_** **|** **_[Python](/Chapter%203%20-%20Stacks%20and%20Queues/Animal%20Shelter/animal_shelter.py)_** 42 | 43 | 44 | ## Todo's: 45 | - [ ] Readme per chapter explaining solutions 46 | - [ ] Blog posts per chapter 47 | - [ ] Code refactoring 48 | - [ ] Alternatives to organise readme in better manner -------------------------------------------------------------------------------- /Chapter 1 - Arrays and Strings/Readme.md: -------------------------------------------------------------------------------- 1 | ## Condensed Summary 2 | 3 | ### Is Unique 4 | 5 | * **Problem Statement** **→** Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? 6 | 7 | * **Key points** :- 8 | 9 | 1. Clarify if the string has ASCII or Unicode character encoding. 10 | 11 | 2. ASCII encoding has 128 characters and extended ASCII has 256 characters. 12 | 3. [ASCII character codes table](https://www.petefreitag.com/cheatsheets/ascii-codes/) 13 | 14 | 4. When you encounter count/unique element problems in string; it is highly likely that hash table data will be required. 15 | 16 | * **Approach** :- 17 | 1. Create array of boolean values where each value indicates if character is contained in string. If we encounter any character twice, return false. 18 | 19 | 2. Use bit-vector instead of boolean array to reduce space. 20 | 21 | 3. Sort string and linearly check neighbouring characters. 22 | 23 | ### Check Permutation 24 | 25 | * **Problem Statement** **→** Given two stirngs, write a method to decide if one is a permutation of the other 26 | 27 | * **Key points** :- 28 | 1. Clarify if permutation is case sensitive, if whitespace is significant and are repeated characters allowed. 29 | 30 | 2. Two strings of different length cannot be permutations of each other. 31 | 32 | 3. Permutation - Two strings with same character counts 33 | 34 | * **Approach** :- 35 | 1. Sort both the strings. 36 | 37 | 2. Hash the count of characters in string one. Now, iterate over string two and decrement the value in hashtable. 38 | 39 | ### URLify 40 | 41 | * **Problem Statement** **→** Write a method to replace all spaces in string with "%20". You may assume that string has sufficient space at the end to hold additional characters. 42 | 43 | * **Key points** :- 44 | 1. Clairfy whether you are allowed to modify string inplace. 45 | 46 | 2. Think of additional space counts. 47 | 48 | 3. For string manipulation problems(having extra spaces), editing the string backwards from end to start is preferred. 49 | 50 | * **Approach** :- 51 | 1. Get space count, triple the count to suffice space for additional characters. Scan from right to left; if you encounter space, insert 3 characters, else insert normal character. 52 | _Snippet_:- 53 | ``` 54 | int extendedLen = len + 2 * space_count; 55 | i = extendedLen - 1; 56 | FORD (j, len - 1, 0) { 57 | if (str[j] != ' ') { 58 | str[i--] = str[j]; 59 | } else { 60 | str[i--] = '0'; 61 | str[i--] = '2'; 62 | str[i--] = '%'; 63 | } 64 | } 65 | ``` 66 | 67 | ### Palindrome Permutation 68 | 69 | * **Problem Statement** **→** Given a string, write a function to check if a string is a permutation of palindrome. 70 | 71 | * **Key points** :- 72 | 1. Palindrome is a string that is same when read backwards and forwards. The aim is to find a permutation/variant of string that is a palindrome. 73 | 74 | 2. Even length palindrome strings have even count of all characters within string. Odd length palindrome strings have even count of all characters except one character within string. 75 | 76 | 3. For permutation of palindrome, a string cannot have more than one character whose count is odd(or specifically > 1) 77 | 78 | * **Approach** :- 79 | 1. Use hashtable, count occurences of each character within string. Now check for number of odd count characters. If its > 1, then return false. 80 | 81 | 2. Instead of checking number of odd count characters in the end, check for number of odd counts while scanning string L-R itself. 82 | 83 | ### One Away 84 | 85 | * **Problem Statement** **→** There are 3 types of edit taht can be performed. Insert, remove or replace a character. Given two strings, write a function to check if both of them are 1/0 edits away. 86 | 87 | * **Key points** :- 88 | 1. Replacement in this problem explicitly means that two strings differ only in one place. 89 | 90 | 2. Removal and Insertion also imply that one string is smaller than other 91 | 92 | 3. If two strings differ in length > 1, they aren't one/zero edits away. 93 | 94 | * **Approach** :- 95 | 1. Use hashtable, count occurences of each character within *the longer* string. Now scan through smaller string and decrement the count of occurences for characters encountered in hashtable. If final difference in count is <= 1, both the strings are one/zero edit away. 96 | 97 | 2. Find longer string. Take two pointers (i and j) each for long and short string. If s1[i] != s2[j] and len(s1) == len(s2) increment shorter pointer. Increment longer pointer always while scanning. 98 | _Snippet_:- 99 | ``` 100 | int i = 0, j = 0; 101 | bool found = false; //calculate difference - one away 102 | while(i < s1.length() && j < s2.length()){ 103 | if(s1[i] != s2[j]){ 104 | if(found) return false; // testcase --> "tail" "pale" will break this loop 105 | found = true; 106 | //replace operation 107 | if(s1.length() == s2.length())j++; //move shorter pointer only when both strings are of same length. 108 | //If they are moved when they are of unequal lengths; it will be big problem 109 | /* 110 | Example: bale and pal 111 | b != p:- and len(bale) != len(pal) So increment only i here. 112 | i.e. increment only longer pointer to bring the [b + len(ale)] and len(pal) in sync for next iteration 113 | */ 114 | } 115 | else 116 | j++; //move shorter pointer ahead when both chars in s1 and s3 are ruqal 117 | i++; //increment longer pointer always while scanning. 118 | } 119 | return true; 120 | } 121 | ``` 122 | 123 | ### String Compression 124 | 125 | * **Problem Statement** **→** Implement a method to perform basic string compression using the counts of repeated characters. If compressed string doesn't become smaller than the original string, your method should return original string. Assume string has only uppercase and lowercase letters. (a-zA-Z) 126 | 127 | * **Key points** :- 128 | 1. Clarify how the characters are placed in string. Take an example in this case. Are they sorted/un-sorted/spread randomly within the string. 129 | 130 | 2. When consecutive characters are placed next to each other, we can use look ahead comparison of characters at position i and i+1 within string. 131 | 132 | * **Approach** :- 133 | 1. Use hashing. Each occurence of character can be hashed and then the count can be appended in the string from backwards Similar to technique that was used in _problem URLify_. This takes O(n) space. 134 | 135 | 2. Lookahead comparison: When extra space is not allowed, use a global counter to count occurences of same character. Since same characters are placed next to each other(assumption), then this counter can be reset as and when charAt(i) != charAt(i+1). 136 | _Snippet_:- 137 | ``` 138 | FOR(i, 0, x.length() - 1){ 139 | count_compression++; 140 | if(i+1 >= x.length() || x[i] != x[i+1]){ 141 | length_compression += 1 + count_compression; 142 | count_compression = 0; 143 | } 144 | } 145 | ``` 146 | 147 | ### Rotate Matrix 148 | 149 | * **Problem Statement** **→** Given an image represented by matrix NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate image by 90 degrees. Can you do this inplace? 150 | 151 | * **Key points** :- 152 | 1. Look for patterns in the given sample testcase. Matrix rotation highly involves dealing with transpose of matrix. 153 | 154 | 2. Look at the 4 corners of input matrix and output matrix for the sample testcase. 155 | 156 | * **Approach** :- 157 | 1. Transpose matrix and then perform transformations(row-wise/column-wise) to bring the input matrix in desired output state. _My workaround_:- 158 | ``` 159 | //clockwise :- transpose + rowwise transformation 160 | /* 161 | 1 2 3 1 4 7 7 4 1 162 | 4 5 6 --> 2 5 8 --> 8 5 2 163 | 7 8 9 3 6 9 9 6 3 164 | */ 165 | 166 | //anticlockwise :- transpose + rowwise + columnwise + rowwise transformation 167 | /* 168 | 1 2 3 1 4 7 7 4 1 9 6 3 3 6 9 169 | 4 5 6 --> 2 5 8 --> 8 5 2 --> 8 5 2 --> 2 5 8 170 | 7 8 9 3 6 9 9 6 3 7 4 1 1 4 7 171 | */ 172 | ``` 173 | 2. Perform circular rotation on each layer, moving corner edges. Top to right, right to bottom, bottom to left and left to top. (Or vice versa) 174 | 175 | 176 | ### Zero Matrix 177 | 178 | * **Problem Statement** **→** Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. 179 | 180 | * **Key points** :- 181 | 1. Iterating through matrix and changing all the values for corresponding rows and columns for each 0 encountered is a wrong approach. (This will set the entire matrix filled with 0's) 182 | 183 | 2. There is no point in maintaining deep history for each exact location of 0's. If a row contains zero, that's the only necessary condition to set all the elements within same row as 0's. 184 | 185 | * **Approach** :- 186 | 1. Use 2 arrays to keep track of all rows with 0's and all columns with 0's. Nullify columns and rows based on these arrays. This approach consumes O(N) space, 187 | 188 | 2. Check if first row and first column have 0's. Iterate through matrix and for each 0 encountered, set its corresponding first row and first column ([i][0] and [0][j]) to 0. Nullify rows and columns based on values set in first row and first column. Nullify first row and first column, if necessary. 189 | 190 | ### String Rotation 191 | 192 | * **Problem Statement** **→** Assume you have method isSubString which checks if one word is substring of another. Given two strings, write code to check if s2 is rotation of s1 with just oneall to isSubString. 193 | 194 | * **Key points** :- 195 | 1. Rotation of string always have a point within stirng from where the rotation begins. Example:- "water" when rotated as "terwa" has "t" as the rotation point. 196 | 197 | 2. Multiple contactenation of one string produces all forms of subsets of rotations that are expected. 198 | 199 | * **Approach** :- 200 | 1. Concatenate original string(s1) with itself. Now check if s2 is substring of s1 by calling isSubString method --------------------------------------------------------------------------------