├── lists ├── double │ ├── insertCertainPos.c │ ├── insertTail.c │ ├── DLLNode.java │ ├── InsertHead.c │ ├── Main.java │ ├── doubleLinkedList.cpp │ └── treeUsingDoubly.cpp ├── single │ ├── deleteWithoutHeadPtr.cpp │ ├── ListNode.java │ ├── insertAtHead.cpp │ ├── findLengthOfLinkedList.c │ ├── Main.java │ ├── insertAtTail.cpp │ ├── LengthofLoop.cpp │ ├── insertANodeInTheMiddle.c │ ├── deleteANodeFrom_LinkedList.c │ └── reverseList.c ├── inbuilt │ ├── vector │ │ ├── Main.cpp │ │ └── vectors.java │ ├── arraylist │ │ ├── arrayList.java │ │ └── list.py │ └── linkedlist │ │ └── JavaLinkedList.java └── misc │ └── nth_node_from_end │ ├── Approach4.java │ ├── Approach3.java │ ├── Approach1.java │ ├── Approach6.java │ ├── Approach5.java │ └── Approach2.java ├── stacks ├── misc │ ├── evaluationofExpressions.cpp │ ├── balancedParanthesis.py │ ├── Check_Palindrome.c │ ├── minimumElementUsingStack.cpp │ ├── infixTopostfix.cpp │ ├── postfixEvaluation.py │ ├── prefixEvaluation.py │ ├── Infix_to_Prefix.c │ ├── infixToPostfix.py │ ├── balancedParanthesis.cpp │ └── infixToPrefix.py ├── reverse_stack │ ├── reverseStack.py │ └── reverseStack.cpp ├── array_stack │ ├── MainAR.java │ ├── basicPushPop.cpp │ └── ArrayStack.java └── linked_stack │ ├── MainLS.java │ ├── StackNode.java │ ├── basicPushPop.py │ └── LinkedStack.java ├── .github ├── images │ └── ds.jpg ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── pull_request_template.md └── CODE_OF_CONDUCT.md ├── .gitignore ├── strings ├── Strings.c ├── string.py ├── string.js ├── Strings.cpp ├── StringAnagram.cpp ├── Strings.go ├── suffixArray.cpp ├── Strings.java └── StringSearch.cpp ├── arrays ├── 1_d_arrays │ ├── oneDarray.java │ ├── order_statistics │ │ ├── kthLargestMaxSumSubarray.cpp │ │ ├── findSmallestIn2DMatrix.cpp │ │ ├── findLargest.cpp │ │ ├── largest3Elements.cpp │ │ ├── fndMeanMedianOfArray.cpp │ │ └── kthLargestSmallestElement.cpp │ ├── array_rotations │ │ ├── leftRotateInNTime.cpp │ │ ├── rotateMatrixBy90.cpp │ │ ├── rotateArray.java │ │ ├── rotateArrayCyclically.cpp │ │ ├── findMaxHammingDistance.cpp │ │ ├── rotateArrayByK.cpp │ │ ├── findPairWithGivenSumInRotatedArray.cpp │ │ └── findMaxValueWithOnlyRotationsAllowed.cpp │ ├── arrangement_rearrangement │ │ ├── rearrangeArrayAlternatively.py │ │ ├── replaceEvenWithFirst.cpp │ │ └── rearrangePositiveNegative.cpp │ ├── 1darrays.c │ ├── occurances │ │ ├── rowColSum.cpp │ │ ├── findMaxOddCount.cpp │ │ ├── occuranceOfParticularNum.cpp │ │ ├── findMissingNumWithDuplicatesGiven.cpp │ │ └── findPairsWithSumK.cpp │ ├── dynamic_programmming │ │ └── maximumSumSubarray.cpp │ ├── searchElementInBitonicArray.cpp │ └── dynamicarray.c ├── 2_d_arrays │ ├── 2darrays.c │ ├── dynamic2d.c │ ├── twoDarray.java │ ├── spiralOrderMatrix.cpp │ ├── jaggedArray.c │ └── spiralOrderMatric.java ├── 3_d_arrays │ ├── 3darrays.c │ ├── dynamic3d.c │ └── threeDarray.java ├── inbuilt │ └── arrays.java └── 4_d_arrays │ ├── fourDarray.java │ └── 4darrays.c ├── trees ├── binary_tree │ ├── BinaryTreeNode.java │ ├── Inorder.java │ ├── Postorder.java │ ├── topViewOfBinaryTree.cpp │ ├── Preorder.java │ ├── findLeafAndNonLeaf.cpp │ ├── IterativePreorder.java │ ├── LevelOrder.java │ ├── IterativeInorder.java │ ├── printOddEvenNodes_Tree.cpp │ ├── findHeightOfTree.cpp │ ├── ConstructMirrorTree.cpp │ ├── traversalUsingBTree.cpp │ ├── printLevelorder.c │ ├── printRightNodes.cpp │ ├── constructTreeInorder.c │ ├── IterativePostorder.java │ ├── printLevelOrder.cpp │ ├── PrintCousins.cpp │ ├── constructTreeInPost.cpp │ └── inordertraversal.c └── segment_tree │ └── SegmentTree.cpp ├── hashtable └── inbuilt │ ├── HighestFrequencyCharacter.java │ ├── Hashmap.java │ └── Treemap.java ├── graphs └── graphRepresentation.java ├── queues ├── circular_queue │ └── CircularQueueUsingArray.c └── linked_queue │ └── queueUsingLinkedList.c └── CONTRIBUTING.md /lists/double/insertCertainPos.c: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lists/single/deleteWithoutHeadPtr.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stacks/misc/evaluationofExpressions.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/images/ds.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TECHOUS/DSKaKhel/HEAD/.github/images/ds.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore IDE files 2 | *.vscode 3 | *.idea 4 | .settings 5 | 6 | #ignore exe files 7 | 8 | *.exe 9 | *.ipch 10 | *.bin 11 | *.exe 12 | 13 | # java files 14 | *.class 15 | *.jar 16 | *.war 17 | .classpath 18 | .project 19 | 20 | # c/c++ ignore files 21 | *.out -------------------------------------------------------------------------------- /stacks/reverse_stack/reverseStack.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__" : 2 | stack = [] 3 | stack.append(1) 4 | stack.append(2) 5 | stack.append(3) 6 | stack.append(4) 7 | stack.append(5) 8 | 9 | print("Stack = ", *stack) 10 | stack = stack[::-1] 11 | print("Reverse Stack = ", *stack) 12 | -------------------------------------------------------------------------------- /strings/Strings.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | char str[50]; 7 | printf("Enter any string\n"); 8 | gets(str); 9 | puts(str); 10 | 11 | printf("Length of the string %d",(int)strlen(str)); 12 | if(strcmp(str,"Hello World")==0) 13 | { 14 | printf("Strings are equal\n"); 15 | } 16 | } -------------------------------------------------------------------------------- /strings/string.py: -------------------------------------------------------------------------------- 1 | str = " Hello World" 2 | 3 | print(str) 4 | 5 | print(str.split(" ")) 6 | 7 | print(len(str)) 8 | 9 | print(str * 3) 10 | 11 | print(str + " hello") 12 | 13 | print(str[1]) 14 | 15 | print(str[-1]) 16 | 17 | print(str[0:3]) 18 | 19 | print(str[0:-1]) 20 | 21 | print(str[-4:-1]) 22 | 23 | print(str.replace('l','h')) 24 | 25 | print(str.strip()) 26 | 27 | print(str[::-1]) -------------------------------------------------------------------------------- /arrays/1_d_arrays/oneDarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * AUTHOR 3 | * GAURAV WALIA(GauravWalia19) 4 | * © copyright sep 2018 5 | */ 6 | import java.util.*; 7 | public class oneDarray 8 | { 9 | public static void main(String[] args) 10 | { 11 | System.out.println("hello"); 12 | Scanner scan = new Scanner(System.in); 13 | 14 | System.out.printf("Enter a num"); 15 | int a = scan.nextInt(); 16 | System.out.println(a); 17 | scan.close(); 18 | } 19 | } -------------------------------------------------------------------------------- /lists/inbuilt/vector/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | vector vect; 7 | vect.push_back(1); 8 | vect.push_back(2); 9 | vect.push_back(3); 10 | vect.push_back(4); 11 | vect.pop_back(); 12 | cout <<"EMPTY OR NOT: "<< vect.empty() < "; 18 | } 19 | cout << endl; 20 | } -------------------------------------------------------------------------------- /arrays/1_d_arrays/order_statistics/kthLargestMaxSumSubarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | 7 | int KthLargestMaxSumSubarray(int *arr,int size,int k){ 8 | 9 | 10 | 11 | return 0; 12 | } 13 | int main(){ 14 | 15 | int size,k; 16 | cin>>size; 17 | int *arr = new int[size]; 18 | for(int i = 0 ; i < size ; i++){ 19 | cin>>arr[i]; 20 | } 21 | cin>>k; 22 | 23 | int result = KthLargestMaxSumSubarray(arr,size,k); 24 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | 7 | int findLargest(int *arr,int size){ 8 | 9 | int max = INT_MIN; 10 | for(int i = 0 ; i < size ; i++){ 11 | if(arr[i] > max){ 12 | max = arr[i]; 13 | } 14 | } 15 | return max; 16 | 17 | } 18 | int main(){ 19 | int size; 20 | cin>>size; 21 | int *arr = new int[size]; 22 | for(int i = 0 ; i < size ; i++){ 23 | cin>>arr[i]; 24 | } 25 | 26 | int result = findLargest(arr,size); 27 | cout<<"The largest element is "< 2 | #include 3 | using namespace std; 4 | 5 | void rotateInN_Time(int *arr,int size,int k){ 6 | int mod = k % size; 7 | cout<<"The starting point is "<>size; 18 | cin>>k; 19 | int *arr = new int[size]; 20 | 21 | for(int i = 0 ; i < size ; i++){ 22 | cin>>arr[i]; 23 | } 24 | 25 | rotateInN_Time(arr,size,k); 26 | } -------------------------------------------------------------------------------- /arrays/1_d_arrays/arrangement_rearrangement/rearrangeArrayAlternatively.py: -------------------------------------------------------------------------------- 1 | ''' 2 | author : Shreya Pawaskar 3 | link : https://practice.geeksforgeeks.org/problems/-rearrange-array-alternately-1587115620/1 4 | ''' 5 | 6 | t=int(input()) 7 | for it in range(0,t): 8 | n=int(input()) 9 | l=input().split() 10 | for i in range(0,len(l)): 11 | l[i]=int(l[i]) 12 | 13 | l1=[]#o(1) 14 | 15 | for i in range(0,(len(l)//2)): 16 | l1.append(l[len(l)-1-i]) 17 | l1.append(l[i]) 18 | 19 | if len(l)%2!=0:#odd length 20 | l1.append(l[(len(l)//2)]) 21 | 22 | for j in range(0,len(l1)):#printing 23 | print(l1[j],end=" ") 24 | print(" ") 25 | -------------------------------------------------------------------------------- /stacks/linked_stack/StackNode.java: -------------------------------------------------------------------------------- 1 | public class StackNode 2 | { 3 | private int data; 4 | private StackNode next; 5 | 6 | //CONSTRUCTOR 7 | public StackNode(int value) 8 | { 9 | this.data = value; 10 | } 11 | //GETTERS 12 | public int getData() 13 | { 14 | return data; 15 | } 16 | public StackNode getNext() 17 | { 18 | return next; 19 | } 20 | //SETTERS 21 | public void setNext(StackNode next) 22 | { 23 | this.next = next; 24 | } 25 | public void setData(int data) 26 | { 27 | this.data = data; 28 | } 29 | public String toString() 30 | { 31 | return data+""; 32 | } 33 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /lists/inbuilt/arraylist/arrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class arrayList 3 | { 4 | public static void main(String[] args) 5 | { 6 | ArrayList array = new ArrayList(); //created arraylist 7 | array.add(0); 8 | array.add(1); 9 | array.add(2); 10 | array.add(3,5); 11 | array.set(1,-4); 12 | 13 | System.out.println(array.indexOf(2)); 14 | System.out.println(array.contains(9)); 15 | array.remove(0); 16 | System.out.println(array.isEmpty()); 17 | for(int i=0;i 4 | int main() 5 | { 6 | int n; //size of the array 7 | printf("Enter the size of the array\n"); 8 | scanf("%d",&n); 9 | int arr[n]; //declared array of size n 10 | 11 | printf("Enter elements of the array\n"); 12 | for(register int i=0;i 2 | #include 3 | #define SIZE 10 4 | int top = 0; 5 | int top1 = 0; 6 | int *stack; 7 | int *stack1; 8 | 9 | void push(int value) 10 | { 11 | stack[top++] = value; 12 | } 13 | void pushRev(int value) 14 | { 15 | stack1[top1++] = value; 16 | } 17 | 18 | int pop() 19 | { 20 | top--; 21 | return stack[top]; 22 | } 23 | void reverseStack() // this is with extra space 24 | { 25 | stack1 = (int * ) malloc(SIZE * sizeof(int)); 26 | while(top!=0) 27 | { 28 | pushRev(pop()); 29 | } 30 | 31 | for(int i = 0 ; i < top1 ; i++) 32 | { 33 | printf("%d",stack1[i]); 34 | } 35 | } 36 | int main() 37 | { 38 | stack = (int *) malloc (SIZE * sizeof(int)); 39 | push(1); 40 | push(2); 41 | push(3); 42 | push(4); 43 | push(5); 44 | reverseStack(); 45 | } 46 | -------------------------------------------------------------------------------- /trees/binary_tree/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | public class BinaryTreeNode 2 | { 3 | public int data; 4 | public BinaryTreeNode left; 5 | public BinaryTreeNode right; 6 | 7 | public BinaryTreeNode(int data) 8 | { 9 | this.data=data; 10 | left=null; 11 | right=null; 12 | } 13 | public int getData() 14 | { 15 | return data; 16 | } 17 | public void setData(int data) 18 | { 19 | this.data=data; 20 | } 21 | public BinaryTreeNode getLeft() 22 | { 23 | return left; 24 | } 25 | public void setLeft(BinaryTreeNode left) 26 | { 27 | this.left = left; 28 | } 29 | public BinaryTreeNode getRight() 30 | { 31 | return right; 32 | } 33 | public void setRight(BinaryTreeNode right) 34 | { 35 | this.right=right; 36 | } 37 | } -------------------------------------------------------------------------------- /arrays/2_d_arrays/2darrays.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 2 DIMENSIONAL ARRAY 3 | */ 4 | #include 5 | int main() 6 | { 7 | int R,C; 8 | printf("Enter the number of rows and cols of 2d array\n"); 9 | scanf("%d %d",&R,&C); 10 | int arr[R][C]; 11 | printf("Enter the elements of 2d array\n"); 12 | for(register int i=0;i 5 | int main() 6 | { 7 | int R,C,H; 8 | printf("Enter the rows,cols and height of the array\n"); 9 | scanf("%d %d %d",&R,&C,&H); 10 | int arr[R][C][H]; 11 | for(register int i=0;i 2 | #include 3 | 4 | int main() 5 | { 6 | int testcases; 7 | scanf("%d\n",&testcases ); 8 | while(testcases--) 9 | { 10 | int N,W; 11 | int X; 12 | char R; 13 | scanf("%d %d",&N,&W ); 14 | scanf("%d %c",&X,&R); 15 | int i , j, k; 16 | int arr[100][100]={0}; 17 | int sum = 0; 18 | k = 1; 19 | for(i = 0 ; k <=N ; i++) 20 | { 21 | for(j = 0 ; j < W && k <= N ; j++ ) 22 | { 23 | arr[i][j] = k; 24 | k = k+1; 25 | } 26 | } 27 | k = i; 28 | 29 | if(R == 'C') 30 | { 31 | for(i = 0 ; i <= k ; i++) 32 | { 33 | sum += arr[i][X-1]; 34 | } 35 | } 36 | else 37 | { 38 | for(i = 0 ; i < W ; i++) 39 | { 40 | sum = sum + arr[X-1][i]; 41 | } 42 | } 43 | printf("%d\n",sum ); 44 | } 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # HacktoberFest 22 2 | 3 | Please mention the PR subject as `DSKaKhel: Data Structure you are implementing` 4 | 5 | ## Data Structure Implementation you like to add 6 | 7 | Mention the algorithm name here 8 | 9 | ## Programming Language for Data Structure Implementation 10 | 11 | Mention the language name here in which you will submit the code 12 | 13 | ## Code file name with extension 14 | 15 | Enter the code file name with extensionhere 16 | *make sure you use camel casing for code files such as linkedList.c* 17 | 18 | ## What was the toughest question you got till now in the interviews ? 19 | 20 | enter the question here 21 | 22 | ## YOU ARE 23 | 24 | a student / professional (choose any one) 25 | 26 | ## GITHUB USERNAME 27 | 28 | enter your username here 29 | 30 | ### We are looking for a cool name for this repository for next hacktober fest please suggest below (optional) 31 | 32 | `_____________` 33 | 34 | Thanks for your contributions !! 35 | -------------------------------------------------------------------------------- /hashtable/inbuilt/HighestFrequencyCharacter.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Scanner; 3 | 4 | //Highest Frequency Character 5 | 6 | public class HighestFrequencyCharacter { 7 | public static void main(String[] args) { 8 | 9 | Scanner sc = new Scanner(System.in); 10 | String str = sc.nextLine(); 11 | 12 | HashMap hm = new HashMap<>(); 13 | for (int i = 0; i < str.length(); i++){ 14 | char ch = str.charAt(i); 15 | 16 | if (hm.containsKey(ch)){ 17 | int of = hm.get(ch); 18 | int nf = of+1; 19 | hm.put(ch,nf); 20 | } 21 | else{ 22 | hm.put(ch,1); 23 | } 24 | } 25 | 26 | char mfc = str.charAt(0); 27 | for (Character key : hm.keySet()){ 28 | if(hm.get(key)>hm.get(mfc)){ 29 | mfc=key; 30 | } 31 | } 32 | System.out.println(mfc); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /trees/binary_tree/Inorder.java: -------------------------------------------------------------------------------- 1 | public class Inorder 2 | { 3 | public static void main(String[] args) 4 | { 5 | BinaryTreeNode ROOT = null; 6 | BinaryTreeNode a = new BinaryTreeNode(1); 7 | BinaryTreeNode b = new BinaryTreeNode(2); 8 | BinaryTreeNode c = new BinaryTreeNode(3); 9 | BinaryTreeNode d = new BinaryTreeNode(4); 10 | BinaryTreeNode e = new BinaryTreeNode(5); 11 | BinaryTreeNode f = new BinaryTreeNode(6); 12 | BinaryTreeNode g = new BinaryTreeNode(7); 13 | 14 | ROOT=a; 15 | ROOT.setLeft(b); 16 | ROOT.setRight(c); 17 | b.setLeft(d); 18 | b.setRight(e); 19 | c.setLeft(f); 20 | c.setRight(g); 21 | 22 | inorder(ROOT); 23 | } 24 | public static void inorder(BinaryTreeNode ROOT) 25 | { 26 | if(ROOT==null) 27 | { 28 | return; 29 | } 30 | inorder(ROOT.left); 31 | System.out.print(ROOT.data+" "); 32 | inorder(ROOT.right); 33 | } 34 | } -------------------------------------------------------------------------------- /arrays/1_d_arrays/occurances/findMaxOddCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | long int findMaxOdd(long int *,long int); 8 | 9 | int main(){ 10 | long int size; 11 | cin>>size; 12 | long int * arr = new long int[size]; 13 | 14 | for(long int i = 0 ; i < size ; i++){ 15 | cin>>arr[i]; 16 | } 17 | 18 | long int result = findMaxOdd(arr,size); 19 | cout<<"The result is "< store; 24 | map :: iterator it; 25 | long int maximum = INT_MIN; 26 | for(long int i = 0 ; i < size ; i++){ 27 | if(arr[i] % 2 != 0){ 28 | store[arr[i]]++; 29 | } 30 | } 31 | 32 | for(it = store.begin() ; it != store.end() ; it++){ 33 | maximum = max(it->second,maximum); 34 | } 35 | it = store.find(maximum); 36 | 37 | 38 | return it->first; 39 | } -------------------------------------------------------------------------------- /arrays/inbuilt/arrays.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class arrays 3 | { 4 | public static void main(String[] args) 5 | { 6 | int[] arr = {1,2,3,4,5,6,7,8,9,10}; 7 | int[] b = {1,2,3,4,5,6,7,8,9,10}; 8 | 9 | //equals(int[],int[]) method 10 | System.out.println(Arrays.equals(arr,b)); 11 | 12 | //toString(int[]) 13 | System.out.println(Arrays.toString(arr)); 14 | 15 | //fill() 16 | Arrays.fill(b,10); 17 | for(int i=0;i<10;i++) 18 | { 19 | System.out.print(b[i]+" "); 20 | } 21 | System.out.println(); 22 | 23 | //sort() 24 | int[] c={34,23,35,23,1}; 25 | Arrays.sort(c); 26 | System.out.println(Arrays.toString(c)); 27 | 28 | //binarySearch() 29 | System.out.println(Arrays.binarySearch(c, 23)); 30 | 31 | //copyOf() 32 | int[] newarr = Arrays.copyOf(c, 2); 33 | System.out.println(Arrays.toString(newarr)); 34 | } 35 | } -------------------------------------------------------------------------------- /trees/binary_tree/Postorder.java: -------------------------------------------------------------------------------- 1 | public class Postorder 2 | { 3 | public static void main(String[] args) { 4 | BinaryTreeNode ROOT = null; 5 | BinaryTreeNode a = new BinaryTreeNode(1); 6 | BinaryTreeNode b = new BinaryTreeNode(2); 7 | BinaryTreeNode c = new BinaryTreeNode(3); 8 | BinaryTreeNode d = new BinaryTreeNode(4); 9 | BinaryTreeNode e = new BinaryTreeNode(5); 10 | BinaryTreeNode f = new BinaryTreeNode(6); 11 | BinaryTreeNode g = new BinaryTreeNode(7); 12 | 13 | ROOT=a; 14 | ROOT.setLeft(b); 15 | ROOT.setRight(c); 16 | b.setLeft(d); 17 | b.setRight(e); 18 | c.setLeft(f); 19 | c.setRight(g); 20 | 21 | postorder(ROOT); 22 | } 23 | public static void postorder(BinaryTreeNode ROOT) 24 | { 25 | if(ROOT==null) 26 | { 27 | return; 28 | } 29 | postorder(ROOT.left); 30 | postorder(ROOT.right); 31 | System.out.print(ROOT.data+" "); 32 | } 33 | } -------------------------------------------------------------------------------- /lists/single/insertAtHead.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | 7 | int data; 8 | struct node *next; 9 | }; 10 | 11 | node *head = NULL; 12 | 13 | void INSERT_HEAD(int value) 14 | { 15 | node *newNode; 16 | newNode = new node; 17 | newNode->data = value; 18 | 19 | if(head == NULL) 20 | { newNode->next = NULL; 21 | head = newNode; 22 | } 23 | else{ 24 | newNode->next = head; 25 | head = newNode; 26 | } 27 | 28 | cout<<"DATA INSERTED AT HEAD SUCCESSFULLY"<>choice; 36 | 37 | while(choice != -1) 38 | { 39 | switch(choice) 40 | { 41 | 42 | case 1: 43 | cout<<"ENTER THE ELEMENT"<>element; 45 | INSERT_HEAD(element); 46 | break; 47 | } 48 | cout<<"ENTER THE CHOICE\n1.INSERT AT HEAD"<>choice; 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/array_rotations/rotateMatrixBy90.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define size 3 4 | void rotate90clockwise(int arr[size][size]) 5 | { 6 | for(int i = 0 ; i < size/2 ; i++ ) 7 | { 8 | for(int j = 0 ; j < size - i - 1 ; j++) 9 | { 10 | int temp = arr[i][j]; 11 | arr[i][j] = arr[size - 1 -j][i]; 12 | arr[size-1-j][i] = arr[size-1- i][size-1-j]; 13 | arr[size-1-i][size-1-j] = arr[j][size-1-i]; 14 | arr[j][size-1-i] = temp; 15 | } 16 | } 17 | } 18 | 19 | void printMatrix(int arr[size][size]) 20 | { 21 | for (int i = 0; i < size; i++) { 22 | for (int j = 0; j < size; j++) 23 | printf("%d ",arr[i][j]); 24 | printf("\n"); 25 | } 26 | } 27 | int main() 28 | { 29 | int arr[size][size]; 30 | for(int i = 0 ; i < size ; i++) 31 | { 32 | for(int j = 0 ; j < size ; j++) 33 | { 34 | scanf("%d",&arr[i][j]); 35 | } 36 | } 37 | 38 | rotate90clockwise(arr); 39 | printf("The printed matrix is \n"); 40 | printMatrix(arr); 41 | } 42 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/order_statistics/largest3Elements.cpp: -------------------------------------------------------------------------------- 1 | /* find the largest 3 elements of the array */ 2 | 3 | 4 | 5 | 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | 12 | 13 | int findLargest(int *arr,int size){ 14 | 15 | sort(arr, arr + size); 16 | int check = 0, count = 1; 17 | 18 | for(int i = 1; i <= n; i++) 19 | { 20 | 21 | if(count<4) 22 | { 23 | if(check != arr[n - i]) 24 | { 25 | // to handle duplicate values 26 | cout << arr[n - i] << " "; 27 | check = arr[n - i]; 28 | count++; 29 | } 30 | } 31 | else 32 | break; 33 | } 34 | } 35 | int main(){ 36 | int size; 37 | cin>>size; 38 | int *arr = new int[size]; 39 | for(int i = 0 ; i < size ; i++){ 40 | cin>>arr[i]; 41 | } 42 | 43 | int result = findLargest(arr,size); 44 | cout<<"The largest element is "< 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | string str; 7 | cout << "Enter any string"< 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node * left; 8 | struct Node * right; 9 | }; 10 | 11 | struct Node * root = NULL; 12 | 13 | void insertTail(int value) 14 | { 15 | struct Node * tempNode; 16 | tempNode = (struct Node *) malloc (sizeof(struct Node)); 17 | 18 | tempNode->data = value; 19 | tempNode->left = NULL; 20 | tempNode->right = NULL; 21 | 22 | if(root == NULL) 23 | { 24 | root = tempNode; 25 | } 26 | else 27 | { 28 | struct Node * p; 29 | p = root; 30 | while(p->right != NULL) 31 | { 32 | p = p->right; 33 | } 34 | p->right = tempNode; 35 | tempNode -> left = p; 36 | } 37 | } 38 | 39 | void display() 40 | { 41 | struct Node * t = root; 42 | int i 43 | while(t != NULL) 44 | { 45 | printf("the node at pos %d is %d \n",t->data); 46 | t = t->right; 47 | } 48 | } 49 | 50 | 51 | 52 | int main() 53 | { 54 | insertTail(1); 55 | insertTail(2); 56 | insertTail(3); 57 | insertTail(4); 58 | insertTail(5); 59 | 60 | display(); 61 | } 62 | -------------------------------------------------------------------------------- /stacks/misc/Check_Palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char arr[10000]; 5 | char stack[10000]; 6 | int len = 0; 7 | 8 | void push(char ch){ 9 | stack[len] = ch; 10 | len++; 11 | } 12 | 13 | void pop(){ 14 | if(len) 15 | len--; 16 | else 17 | return; 18 | } 19 | 20 | char peek(){ 21 | if(len) 22 | return stack[len-1]; 23 | else 24 | return '\0'; 25 | } 26 | 27 | int main(){ 28 | printf("enter the string: "); 29 | scanf("%s",arr); 30 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | 11 | /* COUNT ALL THE CHARACTERS THAT NEED TO BE DELETED OR INSERTED TO MAKE THE STRING ANAGRAM */ 12 | 13 | int makeAnagram(string a, string b) { 14 | 15 | map storeCounts; 16 | map storeCounts1; 17 | 18 | map :: iterator it; 19 | int count = 0; 20 | 21 | 22 | for(int i = 0 ; i < a.length() ; i++){ 23 | storeCounts[a[i]]++; 24 | } 25 | for(int i = 0 ; i < b.length() ; i++){ 26 | storeCounts[b[i]]--; 27 | } 28 | for(it = storeCounts.begin() ; it != storeCounts.end() ; it++){ 29 | // cout<<"{"<first<<","<second<<"}"<second); 31 | } 32 | return count; 33 | 34 | } 35 | 36 | 37 | int main(){ 38 | 39 | string a; 40 | getline(cin, a); 41 | 42 | string b; 43 | getline(cin, b); 44 | 45 | int res = makeAnagram(a, b); 46 | cout< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | struct Node *left; 7 | struct Node *right; 8 | 9 | Node(int data){ 10 | this->data = data; 11 | this->left = NULL; 12 | this->right = NULL; 13 | } 14 | }; 15 | 16 | /* 17 | 1 --- height = 1 18 | / \ ==> level 0; 19 | 2 3 -- height = 2 20 | / \ / \ ==> level 1; 21 | 4 5 6 7 -- height = 3 ==> level 2 22 | 23 | */ 24 | void findTopView(struct Node *root){ 25 | 26 | 27 | 28 | } 29 | 30 | 31 | int main(){ 32 | struct Node *root = new Node(1); 33 | root->left = new Node(2); 34 | root->right = new Node(3); 35 | root->left->left = new Node(4); 36 | root->left->right = new Node(5); 37 | root->right->left = new Node(6); 38 | root->right->right = new Node(7); 39 | 40 | findTopView(root); 41 | } 42 | -------------------------------------------------------------------------------- /trees/binary_tree/Preorder.java: -------------------------------------------------------------------------------- 1 | public class Preorder 2 | { 3 | public static void main(String[] args) 4 | { 5 | BinaryTreeNode ROOT = null; 6 | BinaryTreeNode a = new BinaryTreeNode(1); 7 | BinaryTreeNode b = new BinaryTreeNode(2); 8 | BinaryTreeNode c = new BinaryTreeNode(3); 9 | BinaryTreeNode d = new BinaryTreeNode(4); 10 | BinaryTreeNode e = new BinaryTreeNode(5); 11 | BinaryTreeNode f = new BinaryTreeNode(6); 12 | BinaryTreeNode g = new BinaryTreeNode(7); 13 | 14 | ROOT=a; 15 | ROOT.setLeft(b); 16 | ROOT.setRight(c); 17 | b.setLeft(d); 18 | b.setRight(e); 19 | c.setLeft(f); 20 | c.setRight(g); 21 | 22 | preorder(ROOT); 23 | } 24 | public static void preorder(BinaryTreeNode ROOT) 25 | { 26 | if(ROOT==null) 27 | { 28 | return; 29 | } 30 | System.out.print(ROOT.getData()+" "); //root 31 | preorder(ROOT.getLeft()); //left 32 | preorder(ROOT.getRight()); //right 33 | } 34 | } -------------------------------------------------------------------------------- /lists/inbuilt/vector/vectors.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class vectors 3 | { 4 | public static void main(String[] args) 5 | { 6 | //this is threadsafe arraylist 7 | Vector arr = new Vector(); 8 | arr.ensureCapacity(11); //ensures the capacity 9 | System.out.println(arr.capacity()); 10 | System.out.println(arr.size()); 11 | arr.add(1); 12 | arr.add(2); 13 | arr.add(3); 14 | arr.add(4); 15 | arr.add(5); 16 | //arr.clear(); 17 | //creating arraylist 18 | ArrayList array = new ArrayList(); 19 | array.add(0); 20 | array.add(2); 21 | array.add(1000); 22 | arr.addAll(array); 23 | 24 | System.out.println(arr.lastIndexOf(2)); 25 | arr.remove(0); //remove the element at the index 26 | System.out.println(arr.isEmpty()); 27 | System.out.println(arr.indexOf(1000)); 28 | System.out.println(arr.contains(1000)); 29 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | /*Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.*/ 9 | 10 | int maxContigeous(int *arr,int size){ 11 | int max_ending = 0,max_so_far = INT_MIN,beg = 0, end = 0; 12 | 13 | for(int i = 0 ; i < size ; i++){ 14 | max_ending = max_ending + arr[i]; 15 | 16 | 17 | if(max_so_far < max_ending){ 18 | max_so_far = max_ending; 19 | end = i; 20 | } 21 | if(max_ending < 0){ 22 | beg = i+1; 23 | max_ending = 0; 24 | } 25 | } 26 | 27 | for(int i = beg ; i < end ; i++){ 28 | cout<>size; 35 | int *arr = new int[size]; 36 | for(int i = 0 ; i < size ;i++){ 37 | cin>>arr[i]; 38 | } 39 | 40 | result= maxContigeous(arr,size); 41 | cout<<"\nThe max contigious subarray is "< 2 | #include 3 | 4 | /* Make the structure of the linked list */ 5 | 6 | struct node 7 | { 8 | int data; 9 | struct node* link; 10 | }; 11 | 12 | struct node* root; 13 | 14 | void insertHead(int value) 15 | { 16 | struct node* tempNode; //declare a temp variable 17 | tempNode = (struct node*)malloc(sizeof(struct node));// assign memory 18 | tempNode->data = value; // inserting the value 19 | tempNode->link = NULL; // cause if its the first element 20 | if(root == NULL) // if no elements in the list 21 | { 22 | root = tempNode; // head points to the newNode 23 | } 24 | else // if root is noot the first node 25 | { 26 | tempNode->link = root; 27 | root = tempNode; 28 | } 29 | 30 | } 31 | int length() 32 | { 33 | int count = 0; 34 | struct node* tempNode; 35 | tempNode = root; 36 | 37 | while(tempNode != NULL) 38 | { 39 | count++; 40 | tempNode = tempNode->link; 41 | } 42 | return count; 43 | } 44 | 45 | int main() 46 | { 47 | insertHead(5); 48 | insertHead(6); 49 | insertHead(7); 50 | insertHead(8); 51 | 52 | int length1 = length(); 53 | printf("The length is %d",length1); 54 | } 55 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/array_rotations/rotateArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class rotateArray 3 | { 4 | public static void main(String[] args) 5 | { 6 | Scanner in = new Scanner(System.in); 7 | int arraySize = in.nextInt(); 8 | int[] arr = new int[arraySize]; 9 | for(int i=0;i 5 | #include 6 | int main() 7 | { 8 | int rows; 9 | printf("Enter the rows of the array\n"); 10 | scanf("%d",&rows); 11 | int cols; 12 | printf("Enter the cols of the array\n"); 13 | scanf("%d",&cols); 14 | int **arr = (int**)malloc(sizeof(int *)*rows); 15 | for(register int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /* Time complexity of my programme is O(n * k); 7 | 8 | k stands for the no of rotations needed 9 | */ 10 | 11 | 12 | 13 | void cyclicallyRotateArray(int *arr,int size,int k){ 14 | 15 | 16 | while(k--){ 17 | 18 | 19 | int temp = arr[size-1]; 20 | 21 | for(int i = size-1; i > 0 ; i--){ 22 | 23 | arr[i] = arr[i-1]; 24 | } 25 | 26 | arr[0] = temp; 27 | } 28 | 29 | } 30 | 31 | void printArray(int *arr,int size){ 32 | 33 | for(int i = 0 ; i < size ; i++){ 34 | cout<>size; 42 | cout<<"Enter the no of rotations"<>k; 44 | int *arr = new int(size); 45 | 46 | cout<<"Enter the elements of the array"<>arr[i]; 49 | } 50 | 51 | cout<<"Rotating the array cyclically"< 2 | #include 3 | 4 | int top = 0; 5 | int * STACK; 6 | void push(int value) 7 | { 8 | STACK[top++] = value; 9 | } 10 | int pop() 11 | { 12 | top--; 13 | return STACK[top]; 14 | } 15 | 16 | void display() 17 | { 18 | for(int i = top ; i >= 0 ; i--) 19 | { 20 | printf("%d\n",STACK[i]); 21 | } 22 | } 23 | 24 | int main() 25 | { 26 | int size,choice,element; 27 | printf("Enter the size of the stack\n"); 28 | scanf("%d",&size); 29 | 30 | STACK = (int *) malloc(size * sizeof(int)); 31 | printf("ENTER YOUR CHOICE\n1.PUSH()\n2.POP() and display the popped element\n3.display()\n"); 32 | scanf("%d",&choice); 33 | while(choice != -1) 34 | { 35 | switch(choice) 36 | { 37 | case 1: 38 | printf("\nENTER THE ELEMENT TO PUSH\n"); 39 | scanf("%d",&element); 40 | push(element); 41 | break; 42 | case 2: 43 | printf("\nThe popped element is : %d\n",pop()); 44 | break; 45 | case 3: 46 | printf("\nTHIS IS THE DISPLAY PART\n"); 47 | display(); 48 | break; 49 | } 50 | printf("\nENTER YOUR CHOICE\n1.PUSH()\n2.POP() and display the popped element\n3.display()\n"); 51 | scanf("%d",&choice); 52 | } 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /arrays/2_d_arrays/spiralOrderMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int rows,cols,i,j,k; 7 | scanf("%d",&rows); 8 | scanf("%d",&cols); 9 | int arr[rows][cols] = {0}; 10 | 11 | for(i = 0 ; i < rows ; i++) 12 | { 13 | for(j = 0 ; j < cols ; j++) 14 | { 15 | scanf("%d",&arr[i][j]); 16 | } 17 | } 18 | 19 | int startingRow = 0; 20 | int startingCol = 0; 21 | int endingRow = rows-1; 22 | int endingCol = cols-1; 23 | 24 | while(startingRow <= endingRow && startingCol <= endingCol) 25 | { 26 | for(j = startingCol ; j <= endingCol ; j++) 27 | { 28 | printf("%d\n",arr[startingRow][j]); 29 | } 30 | startingRow++; 31 | 32 | for(j = startingRow ; j <= endingRow ; j++) 33 | { 34 | printf("%d\n",arr[j][endingCol]); 35 | } 36 | endingCol--; 37 | 38 | if(startingCol < endingRow) 39 | { 40 | for(j = endingCol ; j>=startingCol ; --j) 41 | { 42 | printf("%d\n",arr[endingRow][j]); 43 | } 44 | endingRow--; 45 | } 46 | if(startingCol=startingRow ; --j) 49 | { 50 | printf("%d\n",arr[j][startingCol]); 51 | } 52 | startingCol++; 53 | } 54 | } 55 | return 0 ; 56 | } 57 | -------------------------------------------------------------------------------- /lists/single/insertAtTail.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node{ 6 | 7 | 8 | int data; 9 | struct Node *next; 10 | }; 11 | struct Node* head = NULL; // at start the head is null 12 | 13 | 14 | void Insert_TAIL(int value){ 15 | 16 | 17 | struct Node *temp = new Node; 18 | struct Node *container; 19 | temp->data = value; 20 | temp->next = NULL; 21 | 22 | container = head ; 23 | 24 | if(head == NULL) 25 | { 26 | head = temp; 27 | } 28 | else 29 | { 30 | 31 | while( container->next != NULL) 32 | { 33 | container=container->next; 34 | } 35 | 36 | container->next = temp; 37 | 38 | 39 | } 40 | cout<<"ENTERED INTO TAIL SUCCESSFULLY "<>choice; 51 | 52 | while(choice != -1) 53 | { 54 | 55 | switch(choice) 56 | { 57 | 58 | case 1: 59 | cout<<"ENTER THE ELEMENT TO ENTER"<>element; 61 | Insert_TAIL(element); 62 | break; 63 | } 64 | cout<<"ENTER 1 to push towards tail"<>choice; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /lists/single/LengthofLoop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | int countNodes(struct Node *n) { 11 | int res = 1; 12 | struct Node *temp = n; 13 | while (temp->next != n) 14 | { 15 | res++; 16 | temp = temp->next; 17 | } 18 | return res; 19 | } 20 | 21 | int countNodesinLoop(struct Node *list) { 22 | struct Node *slow_p = list, *fast_p = list; 23 | 24 | while (slow_p && fast_p && fast_p->next) { 25 | slow_p = slow_p->next; 26 | fast_p = fast_p->next->next; 27 | 28 | if (slow_p == fast_p) 29 | return countNodes(slow_p); 30 | } 31 | 32 | return 0; 33 | } 34 | 35 | struct Node *newNode(int key) 36 | { 37 | struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); 38 | temp->data = key; 39 | temp->next = NULL; 40 | return temp; 41 | } 42 | 43 | int main() 44 | { 45 | struct Node *head = newNode(1); 46 | head->next = newNode(2); 47 | head->next->next = newNode(3); 48 | head->next->next->next = newNode(4); 49 | head->next->next->next->next = newNode(5); 50 | head->next->next->next->next->next = head->next; 51 | cout << "The number of nodes in the loop is: "< 2 | #include 3 | 4 | struct Node{ 5 | int data; 6 | struct Node * left ; 7 | struct Node * right; 8 | }; 9 | struct Node * root = NULL; 10 | 11 | 12 | void insertHead (int value) 13 | { 14 | struct Node * temp; 15 | temp = (struct Node *) malloc (sizeof(struct Node)); 16 | temp->data = value; 17 | temp->left = NULL; 18 | temp->right = NULL; 19 | 20 | 21 | if(root == NULL) 22 | { 23 | root = temp; 24 | } 25 | else 26 | { 27 | temp -> right = root; // storing the root address in temp->right; 28 | root->left = temp; // root->left is the left node of the new root created 29 | root = temp; // assigning the new Node as root; 30 | } 31 | } 32 | 33 | int length() 34 | { 35 | 36 | struct Node * t = root; 37 | int count = 0; 38 | 39 | while(t != NULL) 40 | { 41 | count++; 42 | t = t->right; 43 | } 44 | 45 | return count; 46 | } 47 | 48 | void display() 49 | { 50 | struct Node * t = root; 51 | while(t != NULL) 52 | { 53 | printf("%d ",t->data); 54 | t = t->right; 55 | } 56 | 57 | printf("\nthe count is %d \n",length()); 58 | } 59 | 60 | int main() 61 | { 62 | insertHead(1); 63 | insertHead(2); 64 | insertHead(3); 65 | insertHead(4); 66 | insertHead(5); 67 | 68 | 69 | display(); 70 | } 71 | -------------------------------------------------------------------------------- /trees/binary_tree/findLeafAndNonLeaf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node{ 6 | int data; 7 | struct Node *left; 8 | struct Node *right; 9 | 10 | Node(int data){ 11 | 12 | this->data = data; 13 | this->left = NULL; 14 | this->right = NULL; 15 | } 16 | }; 17 | 18 | 19 | int countLeafNodes(struct Node *root){ 20 | 21 | if(root == NULL){ 22 | return 0; 23 | } 24 | 25 | if(root->left == NULL && root->right == NULL){ 26 | return 1; 27 | } 28 | 29 | return countLeafNodes(root->left) + countLeafNodes(root->right); 30 | 31 | } 32 | 33 | int countNonLeafNodes(struct Node *root){ 34 | 35 | if(root == NULL || (root->left == NULL && root->right == NULL)) 36 | { 37 | return 0; 38 | } 39 | 40 | return 1 + countNonLeafNodes(root->left) + countNonLeafNodes(root->right); 41 | } 42 | 43 | int main(){ 44 | 45 | struct Node *root = new Node(1); 46 | 47 | root->left = new Node(2); 48 | root->left->left = new Node(3); 49 | root->left->right = new Node(4); 50 | root->right = new Node(5); 51 | root->right->left = new Node(6); 52 | root->right->right = new Node(7); 53 | 54 | 55 | int leaf = countLeafNodes(root); 56 | int nonLeaf = countNonLeafNodes(root); 57 | cout<<"The Leaf Nodes are " << leaf << endl; 58 | cout<<"the Non Leaf Nodes are " << nonLeaf << endl; 59 | } 60 | -------------------------------------------------------------------------------- /arrays/2_d_arrays/jaggedArray.c: -------------------------------------------------------------------------------- 1 | /* 2 | * JAGGED ARRAYS 3 | * # # # # # 4 | * # # # 5 | * # # # # 6 | * # # 7 | * # # # # # 8 | */ 9 | #include 10 | #include 11 | int main() 12 | { 13 | int rows; //rows of jagged arrays 14 | printf("Enter the rows of the jagged array\n"); 15 | scanf("%d",&rows); 16 | 17 | int **arr=(int **)malloc(sizeof(int *)*rows); 18 | int jagged_cols[rows]; //eg 5,3,4,2,5 19 | printf("Enter the variable cols\n"); 20 | for(register int i=0;i s = new Stack(); 32 | s.push(ROOT); 33 | while(!s.empty()) 34 | { 35 | BinaryTreeNode tmp= s.pop(); 36 | System.out.print(tmp.data+" "); 37 | 38 | if(tmp.right!=null) 39 | { 40 | s.push(tmp.right); 41 | } 42 | if(tmp.left!=null) 43 | { 44 | s.push(tmp.left); 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /trees/binary_tree/LevelOrder.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LevelOrder 3 | { 4 | public static void main(String[] args) { 5 | BinaryTreeNode ROOT = null; 6 | BinaryTreeNode a = new BinaryTreeNode(1); 7 | BinaryTreeNode b = new BinaryTreeNode(2); 8 | BinaryTreeNode c = new BinaryTreeNode(3); 9 | BinaryTreeNode d = new BinaryTreeNode(4); 10 | BinaryTreeNode e = new BinaryTreeNode(5); 11 | BinaryTreeNode f = new BinaryTreeNode(6); 12 | BinaryTreeNode g = new BinaryTreeNode(7); 13 | 14 | ROOT=a; 15 | ROOT.setLeft(b); 16 | ROOT.setRight(c); 17 | b.setLeft(d); 18 | b.setRight(e); 19 | c.setLeft(f); 20 | c.setRight(g); 21 | 22 | levelorder(ROOT); 23 | } 24 | public static void levelorder(BinaryTreeNode ROOT) 25 | { 26 | if(ROOT==null) 27 | { 28 | return; 29 | } 30 | Queue Q = new LinkedList(); 31 | BinaryTreeNode current=ROOT; 32 | 33 | while(current!=null) 34 | { 35 | System.out.print(current.data +" "); 36 | if(current.left!=null) 37 | { 38 | Q.add(current.left); 39 | } 40 | if(current.right!=null) 41 | { 42 | Q.add(current.right); 43 | } 44 | 45 | current=Q.poll(); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /arrays/1_d_arrays/occurances/occuranceOfParticularNum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | /* 7 | 8 | Given an sorted array of size N with duplicate eliments, 9 | find the count of the given number k in the array arr */ 10 | 11 | // input : 12 | // N = 7 k = 2 13 | // arr = 1 1 2 2 2 3 14 | // 15 | // 16 | 17 | /*Build logic 1 1 2 2 2 2 3 */ 18 | 19 | void findCountOf(int arr[], int n , int k){ 20 | int *countArr = (int *) malloc (n * sizeof(int)); 21 | map storeCounts; 22 | map :: iterator it; 23 | countArr[n] = {-1}; 24 | for (int i = 0; i < n; i++) { 25 | storeCounts[arr[i]]++; 26 | } 27 | for(it = storeCounts.begin() ; it!= storeCounts.end() ; it++){ 28 | cout<<"{"<first<<","<second<<"}"<second<>testcases; 39 | 40 | while(testcases--){ 41 | int size,toFindCountOf; 42 | cout<<"Enter the size"<>size; 44 | cout<<"Enter the number to find the count of"<>toFindCountOf; 46 | 47 | int *arr = (int *) malloc ( size * sizeof(int)); 48 | 49 | cout<<"Enter the elements in the array"<>arr[i]; 52 | } 53 | 54 | findCountOf(arr,size,toFindCountOf); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /arrays/3_d_arrays/dynamic3d.c: -------------------------------------------------------------------------------- 1 | /* 2 | * DYNAMIC 3D ARRAYS IN HEAP 3 | */ 4 | #include 5 | #include 6 | int main() 7 | { 8 | int height; 9 | int rows; 10 | int cols; 11 | printf("Enter the height,rows and cols of the array\n"); 12 | scanf("%d %d %d",&height,&rows,&cols); 13 | 14 | int ***arr = (int***)malloc(sizeof(int **)*height); 15 | for(register int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /* 7 | 8 | The question states 9 | 10 | Input: 11 | 12 | 3 -> odd so array will not be bothered 13 | 6 14 | 36 15 | 61 16 | 121 17 | 38 18 | 56 19 | 36 20 | 3 21 | 6 22 | -1 23 | 24 | Output: 25 | 26 | 3 27 | 6 28 | 61 29 | 121 30 | 38 31 | 3 32 | 6 33 | 34 | 35 | 36 | 37 | 38 | */ 39 | int processArray(int *arr,int len){ 40 | stack st; 41 | int j = 0; 42 | for(int i = 0 ; i < len ; i++){ 43 | if(arr[i] % 2 != 0){ 44 | st.push(arr[i]); 45 | } 46 | else if(arr[i] % 2 == 0){ 47 | st.push(arr[i]); 48 | while(arr[i] % 2 == 0){ 49 | i++; 50 | } 51 | st.push(arr[i]); 52 | } 53 | } 54 | while(!st.empty()){ 55 | arr[j++] = st.top(); 56 | st.pop(); 57 | } 58 | len = j; 59 | 60 | 61 | return len; 62 | } 63 | 64 | int main(){ 65 | int x; 66 | int len = 1; 67 | int *arr = new int [10000]; 68 | cin>>x; 69 | arr[0] = x; 70 | 71 | while(x != -1){ 72 | cin>>x; 73 | arr[len++] = x; 74 | } 75 | 76 | int res = processArray(arr,len); 77 | cout<<"The length of the modified array is " < 0 ; i--){ 80 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxHammingDistance(int *arr,int n){ 7 | // arr[] to brr[] two times so that 8 | // we can traverse through all rotations. 9 | int brr[2 *n + 1]; 10 | for (int i = 0; i < n; i++) 11 | brr[i] = arr[i]; 12 | for (int i = 0; i < n; i++) 13 | brr[n+i] = arr[i]; 14 | 15 | // We know hamming distance with 0 rotation 16 | // would be 0. 17 | int maxHam = 0; 18 | 19 | // We try other rotations one by one and compute 20 | // Hamming distance of every rotation 21 | for (int i = 1; i < n; i++) 22 | { 23 | cout<<"This is the iteration no "<>size; 46 | arr = new int[size]; 47 | cout<<"Enter the elements of the array"<>arr[i]; 50 | } 51 | int h_distance = maxHammingDistance(arr,size); 52 | cout<< h_distance< map = new HashMap(); 22 | map.put("key", "value"); 23 | map.put("one","two"); 24 | map.put("three", "four"); 25 | map.put("five", "six"); 26 | 27 | if(map.containsKey("key")){ 28 | System.out.println(map.get("key")); 29 | } 30 | System.out.println(map.containsValue("six")); 31 | map.remove("one"); 32 | System.out.println(map.toString()); 33 | 34 | map.compute("key", (key,val)-> val.concat(" Updated")); 35 | // traverse the map 36 | for(Map.Entry entry : map.entrySet()){ 37 | System.out.println(entry.getKey() +" "+entry.getValue()); 38 | } 39 | // get only keys 40 | System.out.println(map.keySet()); 41 | 42 | // get only values 43 | System.out.println(map.values()); 44 | 45 | // clearing a map 46 | map.clear(); 47 | System.out.println(map); 48 | } 49 | } -------------------------------------------------------------------------------- /arrays/1_d_arrays/array_rotations/rotateArrayByK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | 8 | /* This is the basic algorithm with : 9 | 10 | Time Complexity O(n * k) where k is the no of elements to rotate it by 11 | Space Complexity = 0(n); 12 | 13 | */ 14 | void rotateArrayByK(int *arr , int size, int k){ 15 | 16 | int j = 1; 17 | 18 | while(k--){ 19 | // take the first element of the array [ before or after rotation ] 20 | int temp = arr[0]; 21 | 22 | // shift the array by 1 element array[0th index ] = its next index and so on. 23 | for(int i = 0 ; i < size - 1 ; i++){ 24 | 25 | // Shifting the elements to the left by 1 element 26 | arr[i] = arr[i+1]; 27 | } 28 | // attaching the first to the end by 1 rotation 29 | // replace the last element with the first for anticlockwise rotation 30 | arr[size-1] = temp; 31 | } 32 | } 33 | 34 | void printArr(int *arr,int size){ 35 | for(int i = 0 ; i < size ; i++){ 36 | cout<>size; 45 | cout<<"Enter the no of elements to rotate by"<>k; 47 | 48 | int *arr = new int(size); 49 | 50 | cout<<"Enter the elements "<>arr[i]; 54 | } 55 | 56 | cout<<"performing the rotation"< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | /* not working for large testcases */ 7 | 8 | 9 | int search(long int arr[], long int l, long int h, long int key) 10 | { 11 | if(l > h){ 12 | return -1; 13 | } 14 | 15 | long int mid = (l+h)/2; 16 | 17 | if(arr[mid] == key){ 18 | return mid; 19 | } 20 | 21 | if(key >= arr[l] && key <= arr[mid]){ 22 | 23 | return search(arr,l,mid-1,key); 24 | 25 | } 26 | else{ 27 | return search(arr,mid+1,h,key); 28 | } 29 | 30 | 31 | if(key > arr[mid] && key < arr[h] ){ 32 | return search(arr,mid+1,h,key); 33 | } 34 | else{ 35 | return search(arr,l,mid-1,key); 36 | } 37 | } 38 | 39 | int main(){ 40 | 41 | long int testcases,size,element,foundIndex; 42 | long int *arr; 43 | cout<<"Enter the testcases"<>testcases; 45 | while(testcases--){ 46 | cout<<"Enter the size"<>size; 48 | arr = new long int[size]; 49 | cout<<"Enter the array"<>arr[i]; 52 | } 53 | cout<<"Enter the element to be searched"<>element; 55 | foundIndex = search(arr,0,size-1,element); 56 | if(foundIndex != -1){ 57 | cout< 2 | using namespace std; 3 | void build(int a[], int s, int e, int tree[], int index) { 4 | if (s == e) { 5 | tree[index] = a[s]; 6 | return; 7 | } 8 | int mid = (s + e) / 2; 9 | build(a, s, mid, tree, 2 * index); 10 | build(a, mid + 1, e, tree, 2 * index + 1); 11 | tree[index] = tree[2 * index] + tree[2 * index + 1]; 12 | return; 13 | } 14 | int query(int tree[], int s, int e, int qs, int qe, int index) { 15 | if ((s >= qs) and (qe >= e)) { 16 | return tree[index]; 17 | } 18 | if ((qe < s) or (qs > e)) { 19 | return 0; 20 | } 21 | int mid = (s + e) / 2; 22 | int left = query(tree, s, mid, qs, qe, 2 * index); 23 | int right = query(tree, mid + 1, e, qs, qe, (2 * index) + 1); 24 | return left + right; 25 | } 26 | 27 | void update(int tree[], int s, int e, int index, int key, int val) { 28 | if ((key > e) or (key < s)) return; 29 | if ((s == e) and (s == key)) { 30 | tree[index] = tree[index] + val; 31 | return; 32 | } 33 | int mid = (s + e) / 2; 34 | update(tree, s, mid, 2 * index, key, val); 35 | update(tree, mid + 1, e, 2 * index + 1, key, val); 36 | tree[index] = min(tree[2 * index], tree[2 * index + 1]); 37 | return; 38 | } 39 | 40 | int32_t main() 41 | { 42 | // Input number of queries 43 | int n; 44 | cin >> n; 45 | int a[n]; 46 | int tree[4 * n + 1]; 47 | for(int i=0;i> a[i]; 48 | build(a, 0, n - 1, tree, 1); 49 | int m; 50 | cin >> m; 51 | while (m--) { 52 | int x, y; 53 | cin >> x >> y; 54 | cout << query(tree, 1, n , x, y, 1) << "\n"; 55 | } 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /stacks/misc/minimumElementUsingStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /* PROGRAMME TO FIND THE MINIMUM ELEMENT USING A SINGLE STACK :') */ 3 | using namespace std; 4 | int * STACK; 5 | int top = 0; 6 | int element; 7 | int choice; 8 | int size; 9 | 10 | 11 | void push(int x) 12 | { 13 | STACK[top++]=x; 14 | } 15 | int pop() 16 | { 17 | return STACK[top--]; 18 | } 19 | int main() 20 | { 21 | cout<<"Enter the size of the array"<>size; 23 | cout<<"\nEnter the choice\n1.push()\n2.display minimum element"<>choice; 25 | STACK = new int[size]; 26 | while(choice != -1) 27 | { 28 | switch(choice) 29 | { 30 | 31 | case 1: 32 | cout<<"Enter the element"<>element; 34 | // push(element); 35 | if(top == 0) 36 | { 37 | 38 | push(element); 39 | //cout<<"top is "<>choice; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /lists/inbuilt/arraylist/list.py: -------------------------------------------------------------------------------- 1 | #Making List l 2 | l = [11, 12, 13, 14] 3 | 4 | #Using append function on list 5 | l.append(50) 6 | l.append(60) 7 | print("list after adding 50 & 60:- ", l) 8 | 9 | #Using remove function on list 10 | l.remove(11) 11 | l.remove(13) 12 | print("list after removing 11 & 13:- ", l) 13 | 14 | #Using the sort function with their parameters changed 15 | #Implementing sorting in a list 16 | l.sort(reverse=False) 17 | print("list after sortinng in ascending order:- ",l) 18 | l.sort(reverse=True) 19 | print("list after sorting in descending order:- ",l) 20 | 21 | #Implementing searching in a list 22 | if 13 in l: 23 | print("yes 13 is in the list") 24 | else: 25 | print("no 13 is not in the list") 26 | print("no of elements list have:- ",len(l)) 27 | 28 | #Implementing traversing in a list 29 | s = 0 30 | oddsum = 0 31 | evensum = 0 32 | primesum = 0 33 | for i in l: 34 | s = s + i 35 | if i % 2 == 0: 36 | evensum = evensum + i 37 | else: 38 | oddsum = oddsum + i 39 | count = 0 40 | j = 1 41 | while( j < len(l)): 42 | if l[j] % j == 0: 43 | count = count + 1 44 | j = j+1 45 | if count == 2: 46 | primesum = primesum + l[i] 47 | print("sum of elements in the list:- ",s) 48 | print("sum of odd elements in the list:- ",oddsum) 49 | print("sum of even elements in the list:- ",evensum) 50 | print("sum of prime elements in the list:- ",primesum) 51 | 52 | #Using clear function to delete all the data in list 53 | #Implementing delete functionality in a list by using predefined functions 54 | l.clear() 55 | print("list after using clear function:- ",l) 56 | del l 57 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/dynamicarray.c: -------------------------------------------------------------------------------- 1 | //dynamic array 2 | #include 3 | #include 4 | int main() 5 | { 6 | int arr_size=2; 7 | int *arr = (int *)malloc(sizeof(int)*arr_size); //intially array size 1 8 | 9 | //entering elements 10 | int n; //for entering number 11 | int i=0; //for insertion and element count 12 | while(1) 13 | { 14 | printf("ENTER ELEMENT or quit by -1: "); 15 | scanf("%d",&n); 16 | if(n==-1) 17 | { 18 | break; 19 | } 20 | if(i S = new Stack(); 32 | boolean done=false; 33 | BinaryTreeNode current=ROOT; 34 | while(!done) 35 | { 36 | if(current!=null) 37 | { 38 | S.push(current); 39 | current=current.left; 40 | } 41 | else //if null value found 42 | { 43 | if(S.isEmpty()) 44 | done=true; 45 | else 46 | { 47 | current = S.pop(); 48 | System.out.print(current.data+" "); 49 | current=current.right; 50 | } 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /trees/binary_tree/printOddEvenNodes_Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* 6 | 7 | 1 => level 1 8 | / \ 9 | 2 3 10 | / \ / \ 11 | 4 5 6 7 => level 3 12 | 13 | 14 | 15 | 16 | */ 17 | struct Node{ 18 | int data; 19 | struct Node *left; 20 | struct Node *right; 21 | }; 22 | struct Node *root = NULL; 23 | 24 | struct Node *newNode(int data) 25 | { 26 | struct Node *temp = (struct Node *) malloc ( sizeof(struct Node)); 27 | temp->data = data; 28 | temp->left = NULL; 29 | temp->right = NULL; 30 | 31 | return temp; 32 | } 33 | 34 | int height(struct Node *root) 35 | { 36 | if(root == NULL) 37 | { 38 | return 0; 39 | } 40 | 41 | int lheight = height(root->left); 42 | int rheight = height(root->right); 43 | 44 | if(lheight > rheight) 45 | { 46 | return lheight + 1; 47 | } 48 | return rheight + 1; 49 | } 50 | void printOddEven(struct Node *root,int height) 51 | { 52 | if(root == NULL) 53 | { 54 | return ; 55 | } 56 | if(height % 2 != 0) 57 | { 58 | printf("%d => ",root->data); 59 | } 60 | 61 | printOddEven(root->left,height-1); 62 | printOddEven(root->right,height-1); 63 | } 64 | 65 | int main() 66 | { 67 | struct Node *root = newNode(1); 68 | root->left = newNode(2); 69 | root->left->left = newNode(4); 70 | root->left->right = newNode(5); 71 | root->right = newNode(3); 72 | root->right->left = newNode(6); 73 | root->right->right = newNode(7); 74 | 75 | printOddEven(root,height(root)); 76 | } 77 | -------------------------------------------------------------------------------- /trees/binary_tree/findHeightOfTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node{ 6 | int data; 7 | struct Node *left; 8 | struct Node *right; 9 | }; 10 | 11 | struct Node * root = NULL; 12 | 13 | struct Node* newNode(int data) 14 | { 15 | struct Node* temp = (struct Node *) malloc (sizeof(struct Node)); 16 | temp->data = data; 17 | temp->left = NULL; 18 | temp->right = NULL; 19 | return temp; 20 | } 21 | 22 | 23 | int height(struct Node * root) 24 | { 25 | if(root == NULL) 26 | { 27 | return 0; 28 | } 29 | 30 | int lheight = height(root->left); 31 | int rheight = height(root->right); 32 | 33 | //printf("Lheight is %d\n",lheight); 34 | //printf("Rheight is %d\n",rheight); 35 | 36 | if(lheight > rheight) 37 | { 38 | return lheight+1; 39 | } 40 | return rheight+1; 41 | } 42 | 43 | 44 | 45 | int main() 46 | { 47 | struct Node * root = newNode(1); 48 | root->left = newNode(2); 49 | root->left->left = newNode(10); 50 | root->left->right = newNode(12); 51 | root->right = newNode(3); 52 | root->right->left = newNode(15); 53 | root->right->right = newNode(18); 54 | 55 | 56 | int treeHeight = height(root); 57 | 58 | printf("The height of the tree --> %d =>",treeHeight); 59 | } 60 | 61 | 62 | /* 63 | 64 | 1 ==> 0th Level 65 | / \ 66 | 2 3 ==> 1st level 67 | / \ / \ 68 | 10 12 15 18 ==> 2nd Level 69 | 70 | 71 | */ 72 | -------------------------------------------------------------------------------- /trees/binary_tree/ConstructMirrorTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct Node{ 7 | int data; 8 | struct Node *left; 9 | struct Node *right; 10 | 11 | Node(int data){ 12 | this->data = data; 13 | this->left = NULL; 14 | this->right = NULL; 15 | } 16 | }; 17 | 18 | 19 | /* inorder printing */ 20 | 21 | void inorder(struct Node * root) 22 | { 23 | if(root == NULL){ 24 | return ; 25 | } 26 | 27 | inorder(root->left); 28 | printf("%d => ",root->data); 29 | inorder(root->right); 30 | } 31 | /* Simple way to construct mirror tree is to traverse both sides and then swap the data */ 32 | void constructMirror(struct Node *root){ 33 | 34 | if(root == NULL){ 35 | return ; 36 | } 37 | 38 | constructMirror(root->left); // traversing the left Nodes 39 | constructMirror(root->right); // traversing the right Nodes 40 | 41 | /* Swapping the datas */ 42 | struct Node *temp = root->left; 43 | root->left = root->right; 44 | root->right = temp; 45 | 46 | } 47 | int main(){ 48 | struct Node *root = new Node(1); 49 | root->left = new Node(2); 50 | root->right = new Node(3); 51 | root->left->left = new Node(4); 52 | root->left->right = new Node(5); 53 | root->right->left = new Node(6); 54 | root->right->right = new Node(7); 55 | 56 | printf("The inorder tree before mirror is \n"); 57 | inorder(root); 58 | constructMirror(root); 59 | printf("\nThe inorder tree after the mirror is \n"); 60 | inorder(root); 61 | 62 | } 63 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/occurances/findMissingNumWithDuplicatesGiven.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | /* Question 9 | 10 | This is a really good question 11 | always the input will be 1 -> n 12 | 13 | INPUT : 3 1 3 2 5 14 | OUTPUT : 3 -> duplicate 15 | 4 -> missing number 16 | 17 | 18 | Method 1: 19 | 20 | using map store the counts of values. 21 | if value count >= 2 22 | that is the duplicate number. 23 | and if the count of that number is 0 24 | then the missing number is that only. 25 | */ 26 | void findMissingNum(long long int *arr,long long int size){ 27 | 28 | map storeCount; 29 | map :: iterator it; 30 | int duplicateNum = 0,missingNum = 0; 31 | for(int i = 0 ; i < size ; i++){ 32 | storeCount[arr[i]]++; 33 | storeCount[i+1]++; 34 | } 35 | 36 | for(it = storeCount.begin() ; it != storeCount.end() ; it++){ 37 | 38 | cout<<"{"<first<<" , "<second<<"}"<second > 2){ 40 | duplicateNum = it->first; 41 | } 42 | else if(it->second == 1){ 43 | missingNum = it->first; 44 | } 45 | } 46 | 47 | cout<<"The dup number is "<< duplicateNum<>size; 56 | long long int *arr = new long long int[size]; 57 | for(long long int i = 0 ; i < size ; i++){ 58 | cin>>arr[i]; 59 | } 60 | 61 | findMissingNum(arr,size); 62 | } -------------------------------------------------------------------------------- /hashtable/inbuilt/Treemap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Treemap{ 3 | public static void main(String[] args){ 4 | /** 5 | * TreeMap sorted map 6 | * 7 | * Methods 8 | * - put(key,value) 9 | * - putIfAbsent(key,value) 10 | * - get(key) 11 | * - getOrDefault(key,default) 12 | * 13 | * - containsKey(key) 14 | * - remove(key) 15 | * - isEmpty() 16 | * - clear() 17 | * 18 | * - descendingKeySet() 19 | * - keySet() 20 | * - firstEntry() 21 | * - firstKey() 22 | * - pollFirstEntry() 23 | * - pollLastEntry() 24 | **/ 25 | TreeMap map = new TreeMap(); 26 | map.put(10, "ten"); 27 | map.put(3, "three"); 28 | map.put(5, "five"); 29 | map.put(50, "fifty"); 30 | 31 | System.out.println(map); 32 | System.out.println(map.get(5)); 33 | System.out.println(map.containsKey(10)); 34 | System.out.println(map.containsValue("three")); 35 | System.out.println(map.getOrDefault(30, "hello")); 36 | System.out.println(map.isEmpty()); 37 | 38 | map.putIfAbsent(30, "thirty"); 39 | System.out.println(map); 40 | 41 | map.remove(5); 42 | System.out.println(map.descendingKeySet()); 43 | map.pollFirstEntry(); 44 | System.out.println(map.descendingMap()); 45 | map.pollLastEntry(); 46 | System.out.println(map.keySet()); 47 | System.out.println(map.firstEntry()); 48 | System.out.println(map.firstKey()); 49 | 50 | map.clear(); 51 | System.out.println(map); 52 | } 53 | } -------------------------------------------------------------------------------- /strings/suffixArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | typedef long long int ll; 3 | #define vi vector 4 | #define pi pair 5 | #define pb push_back 6 | #define F first 7 | #define S second 8 | #define B begin() 9 | #define E end() 10 | #define mp make_pair 11 | using namespace std; 12 | 13 | 14 | suffixArray(string str, int n){ 15 | str+='$'; 16 | n+=1; 17 | vector >index; 18 | for(int i =0; i < n; i++){ 19 | index.pb(mp(str[i],i)); 20 | } 21 | sort(index.B,index.E); 22 | vector p(n),c(n); 23 | int idx = 0; 24 | for(int i = 0; i < n; i++) p[i] = index[i].S; 25 | c[p[0]] = 0; 26 | for(int i = 1; i < n; i++){ 27 | if(index[i].F == index[i-1].F){ 28 | c[p[i]] = c[p[i-1]]; 29 | } 30 | else{ 31 | c[p[i]] = c[p[i-1]]+1; 32 | } 33 | } 34 | int k = 1, len = 1, diff = 0; 35 | while(len < n && diff< n){ 36 | vector,int> > aux(n); 37 | for(int i = 0; i < n; i++){ 38 | aux[i] = {{c[i],c[(i+len)%n]},i}; 39 | } 40 | sort(aux.B,aux.E); 41 | for(int i = 0; i < n; i++) p[i] = aux[i].S; 42 | c[p[0]] = 0; 43 | for(int i = 1; i < n; i++){ 44 | if(aux[i].F == aux[i-1].F){ 45 | c[p[i]] = c[p[i-1]]; 46 | } 47 | else{ 48 | c[p[i]] = c[p[i-1]]+1; 49 | } 50 | } 51 | len*=2; 52 | } 53 | for(int i = 0; i < n; i++){ 54 | cout<>str; 66 | int n = str.length(); 67 | suffixArray(str,n); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /trees/binary_tree/traversalUsingBTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node{ 6 | 7 | int data; 8 | struct Node * left; 9 | struct Node * right; 10 | }; 11 | struct Node* root = NULL; 12 | struct Node* newNode(int data) 13 | { 14 | struct Node * temp = (struct Node*) malloc (sizeof(struct Node)); 15 | temp->data = data; // data is added 16 | temp->left = NULL; // left root added 17 | temp->right = NULL; // right added 18 | 19 | return temp; 20 | } 21 | 22 | void inorderTraversal(struct Node *root) 23 | { 24 | if(root == NULL) 25 | { 26 | return ; 27 | } 28 | inorderTraversal(root->left); 29 | printf("%d-> ",root->data); 30 | inorderTraversal(root->right); 31 | } 32 | 33 | void preOrderTraversal(struct Node *root) 34 | { 35 | if(root == NULL) 36 | { 37 | return ; 38 | } 39 | 40 | 41 | printf("%d-> ",root->data); 42 | preOrderTraversal(root->left); 43 | preOrderTraversal(root->right); 44 | } 45 | 46 | void postOrderTraversal(struct Node *root) 47 | { 48 | if(root == NULL) 49 | { 50 | return ; 51 | } 52 | 53 | postOrderTraversal(root->left); 54 | postOrderTraversal(root->right); 55 | printf("%d-> ",root->data); 56 | } 57 | 58 | 59 | int main() 60 | { 61 | struct Node* root = newNode(1); 62 | root->left = newNode(2); 63 | root->right = newNode(3); 64 | root->left->left = newNode(4); 65 | root->left->right = newNode(5); 66 | root->right->left = newNode(6); 67 | root->right->right = newNode(7); 68 | 69 | printf("\nThe Inorder Traversal of the tree is \n"); 70 | inorderTraversal(root); 71 | printf("\nThe Preorder Traversal of the tree is \n"); 72 | preOrderTraversal(root); 73 | printf("\nThe PostOrder Traversal of the tree is \n"); 74 | postOrderTraversal(root); 75 | 76 | } 77 | -------------------------------------------------------------------------------- /trees/binary_tree/printLevelorder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *left,*right; 8 | }; 9 | 10 | 11 | void printGivenLevel(struct Node* root, int level); 12 | int height (struct Node * node); 13 | 14 | struct Node * newNode(int data); 15 | 16 | void printLevelOrder(struct Node * root) 17 | { 18 | int h = height(root); 19 | int i; 20 | 21 | for(i = 1; i<= h ; i++) 22 | { 23 | printGivenLevel(root,i); 24 | } 25 | } 26 | 27 | void printGivenLevel(struct Node * root,int level) 28 | { 29 | if(root == NULL) 30 | { 31 | return; 32 | } 33 | if(level == 1) 34 | { 35 | printf("%d",root->data); 36 | 37 | } 38 | else if(level > 1) 39 | { 40 | printGivenLevel(root->left , level -1); 41 | printGivenLevel(root->right , level -1); 42 | } 43 | } 44 | 45 | int height(struct Node * node) 46 | { 47 | if(node == NULL) 48 | { 49 | return 0; 50 | } 51 | else 52 | { 53 | int lheight = height(node->left); 54 | int rheight = height(node->right); 55 | 56 | 57 | 58 | if(lheight > rheight) 59 | { 60 | return lheight+1; 61 | } 62 | else 63 | { 64 | return rheight+1; 65 | } 66 | } 67 | } 68 | struct Node* newNode(int data) 69 | { 70 | struct Node* node = (struct Node*) 71 | malloc(sizeof(struct Node)); 72 | node->data = data; 73 | node->left = NULL; 74 | node->right = NULL; 75 | 76 | return(node); 77 | } 78 | int main() 79 | { 80 | struct Node *root = newNode(1); 81 | root->left = newNode(2); 82 | root->right = newNode(3); 83 | root->left->left = newNode(4); 84 | root->left->right = newNode(5); 85 | 86 | printf("Level Order traversal of binary tree is \n"); 87 | printLevelOrder(root); 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/order_statistics/fndMeanMedianOfArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Program for Mean and median of an unsorted array 3 | Given n size unsorted array, find its mean and median. 4 | 5 | Mean of an array = (sum of all elements) / 6 | (number of elements) 7 | 8 | Median of a sorted array of size n is defined 9 | as below : 10 | It is middle element when n is odd and average 11 | of middle two elements when n is even. 12 | 13 | Since the array is not sorted here, we sort 14 | the array first, then apply above formula. 15 | Examples: 16 | 17 | Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7} 18 | Output : Mean = 4.5 19 | Median = 4.5 20 | Sum of the elements is 1 + 3 + 4 + 2 + 6 + 21 | 5 + 8 + 7 = 36 22 | Mean = 36/8 = 4.5 23 | Since number of elements are even, median 24 | is average of 4th and 5th largest elements. 25 | which means (4 + 5)/2 = 4.5 26 | 27 | Input : a[] = {4, 4, 4, 4, 4} 28 | Output : Mean = 4 29 | Median = 4 30 | */ 31 | 32 | #include 33 | #include 34 | #include 35 | using namespace std; 36 | 37 | int findMean(int *arr,int size){ 38 | float sum = 0; 39 | for(int i = 0 ; i < size ; i++){ 40 | sum += arr[i]; 41 | } 42 | 43 | return (float)sum/size; 44 | 45 | } 46 | int findMedian(int *arr,int size){ 47 | sort(arr,arr+size); 48 | int median; 49 | 50 | if(size % 2 == 0){ 51 | median = (arr[(size/2)-1]+arr[size/2])/2; 52 | }else{ 53 | median = arr[(size/2)]; 54 | } 55 | return float(median); 56 | } 57 | int main(){ 58 | int size; 59 | cin>>size; 60 | int * arr = new int[size]; 61 | 62 | for(int i = 0 ; i < size ; i++){ 63 | cin>>arr[i]; 64 | } 65 | 66 | cout<<"The mean is "<<(float)findMean(arr,size)< 2 | #include 3 | int top = 0; 4 | char *STACK; 5 | char str[10000]; 6 | char *res; 7 | 8 | /* for pushing the operators into stack */ 9 | void push(char value) 10 | { 11 | STACK[top++] = value; 12 | } 13 | /* for popping the operators into stack */ 14 | int pop() 15 | { 16 | top--; 17 | return STACK[top]; 18 | } 19 | /* for displaying the stack */ 20 | void displayStack() 21 | { 22 | for(int i = 0 ; i < top ; i++) 23 | { 24 | printf("%c",STACK[i]); 25 | } 26 | } 27 | 28 | /* manually gives away the precedence */ 29 | int precedence(char op) 30 | { 31 | if (op == '+' || op == '-') 32 | { 33 | return 1; 34 | } 35 | else if(op == '*' || op == '/') 36 | { 37 | return 2; 38 | } 39 | else 40 | { 41 | return -1; 42 | } 43 | } 44 | /* the conversion takes place here */ 45 | void infixTopostfix(char str[],int count) 46 | { 47 | int i,k=0; 48 | char x; 49 | STACK = (char *) malloc((10*count) * sizeof(char)); 50 | res = (char *) malloc((10*count) * sizeof(char)); 51 | i = 0; 52 | push('('); 53 | while(str[i]!='\0') 54 | { 55 | if(str[i]>='a' && str[i]<='z') 56 | { 57 | res[k++] = str[i]; 58 | } 59 | else if(str[i] == '+' || str[i] =='-' || str[i]=='*' || str[i]=='/') 60 | { 61 | x = pop(); 62 | while(precedence(x) >= precedence(STACK[top])) 63 | { 64 | res[k++] = x; 65 | x = pop(); 66 | } 67 | push(str[i]); 68 | } 69 | 70 | i++; 71 | } 72 | //printf("%d\n",top); 73 | puts(res); 74 | displayStack(); 75 | } 76 | 77 | /* main function for function calling */ 78 | int main() 79 | { 80 | int i = 0 ,count = 0; 81 | gets(str); 82 | while(str[i]!='\0') 83 | { 84 | count++; 85 | i++; 86 | } 87 | infixTopostfix(str,count); 88 | count = 0; 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/occurances/findPairsWithSumK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | /* base logic of find sum with pairs k 9 | 10 | nput : arr[] = {1, 5, 7, -1}, 11 | sum = 6 12 | Output : 2 13 | Pairs with sum 6 a 14 | 15 | Input : arr[] = {1, 5, 7, -1, 5}, 16 | sum = 6 17 | Output : 3 18 | Pairs with sum 6 are (1, 5), (7, -1) & 19 | (1, 5) 20 | 21 | Input : arr[] = {1, 1, 1, 1}, 22 | sum = 2 23 | Output : 6 24 | There are 3! pairs with sum 2. 25 | 26 | Input : arr[] = {10, 12, 10, 15, -1, 7, 6, 27 | 5, 4, 2, 1, 1, 1}, 28 | sum = 11 29 | Output : 9 30 | */ 31 | 32 | 33 | // this codes complexity = O(n^2); 34 | int binarySearch(int arr[],int start,int end,int key){ 35 | int mid = (start + end)/2; 36 | //cout<end){ 39 | return 0; 40 | } 41 | if(arr[mid] == key){ 42 | return mid; 43 | } 44 | else if(arr[mid] > key){ 45 | return binarySearch(arr,start,mid-1,key); 46 | } 47 | else{ 48 | return binarySearch(arr,mid+1,end,key); 49 | } 50 | } 51 | 52 | int findPairsWithk(int arr[], int size , int sum){ 53 | 54 | int index = 0; 55 | int counter = 0; 56 | sort(arr,arr+size); 57 | 58 | while(size--){ 59 | int findSumOf = sum-arr[index]; 60 | int secondPair = binarySearch(arr,0,size,findSumOf); 61 | 62 | if(arr[index]+arr[secondPair] == sum){ 63 | cout<<"{"< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct Node { 8 | int data; 9 | struct Node *left; 10 | struct Node *right; 11 | }; 12 | 13 | /* *curr 14 | 1 15 | / \ 16 | 2 3 17 | / \ / \ 18 | 4 5 6 7 19 | 20 | Right Node of 2 => 3; 21 | Right Node of 4 => 5 6 7; 22 | 23 | COMPLETED 24 | 25 | */ 26 | 27 | struct Node *newNode(int data){ 28 | 29 | struct Node *tempNode = (struct Node *) malloc ( sizeof(struct Node) ); 30 | tempNode -> data = data; 31 | tempNode -> left = NULL; 32 | tempNode ->right = NULL; 33 | 34 | return tempNode; 35 | } 36 | 37 | void findRightNodes(struct Node *root , int key){ 38 | 39 | queue q ; 40 | struct Node *curr = root; 41 | if(root == NULL){ 42 | return; 43 | } 44 | 45 | 46 | q.push(curr); 47 | 48 | 49 | while(!q.empty()) 50 | { 51 | // curr = q.pop(); 52 | //cout<data<left != NULL){ 54 | q.push(curr->left); 55 | } 56 | if(curr->right != NULL){ 57 | q.push(curr->right); 58 | } 59 | 60 | if(curr->data == key){ 61 | q.pop(); 62 | cout<< q.front()->data; 63 | break; 64 | } 65 | q.pop(); 66 | curr = q.front(); 67 | } 68 | 69 | } 70 | 71 | 72 | 73 | 74 | int main(){ 75 | 76 | struct Node *root = newNode(1); 77 | root->left = newNode(2); 78 | root->right = newNode(3); 79 | root->left->left = newNode(4); 80 | root->left->right = newNode(5); 81 | root->right->left = newNode(6); 82 | root->right->right = newNode(7); 83 | 84 | findRightNodes(root,6); 85 | } 86 | -------------------------------------------------------------------------------- /trees/binary_tree/constructTreeInorder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node{ 5 | int data; 6 | struct Node* left; 7 | struct Node* right; 8 | }; 9 | 10 | int search(int arr[],int start,int end,int value); 11 | 12 | struct Node * newNode(int data); 13 | 14 | struct Node * buildTree(int in[],int pre[],int inStrt,int inEnd) 15 | { 16 | static int preIndex = 0; 17 | 18 | if(inStrt > inEnd) 19 | { 20 | return NULL; 21 | } 22 | 23 | struct Node *tNode = newNode(pre[preIndex++]); 24 | 25 | if(inStrt == inEnd) 26 | { 27 | return tNode; 28 | } 29 | 30 | int inIndex = search(in,inStrt,inEnd,tNode->data); 31 | 32 | tNode->left = buildTree(in,pre,inStrt,inIndex-1); 33 | tNode->right = buildTree(in , pre , inIndex+1, inEnd); 34 | return tNode; 35 | } 36 | 37 | int search(int arr[],int strt,int end,int value) 38 | { 39 | int i ; 40 | for(i = strt ; i <= end ; i++) 41 | { 42 | if(arr[i] == value) 43 | { 44 | return i; 45 | } 46 | } 47 | } 48 | 49 | struct Node *newNode(int data) 50 | { 51 | struct Node *node = (struct Node *) malloc ( sizeof(struct Node)); 52 | node->data = data; 53 | node->left = NULL; 54 | node -> right = NULL; 55 | 56 | return(node); 57 | } 58 | 59 | void printInorder(struct Node* node) 60 | { 61 | if (node == NULL) 62 | return; 63 | 64 | /* first recur on left child */ 65 | printInorder(node->left); 66 | 67 | /* then print the data of node */ 68 | printf("%d ", node->data); 69 | 70 | /* now recur on right child */ 71 | printInorder(node->right); 72 | } 73 | 74 | int main() 75 | { 76 | int in[] = { 1,2,3,4,5 }; 77 | int pre[] = { 4,2,1,3,5 }; 78 | int len = sizeof(in) / sizeof(in[0]); 79 | struct node* root = buildTree(in, pre, 0, len - 1); 80 | 81 | /* Let us test the built tree by printing Insorder traversal */ 82 | printf("Inorder traversal of the constructed tree is \n"); 83 | printInorder(root); 84 | } 85 | -------------------------------------------------------------------------------- /stacks/misc/postfixEvaluation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Output: 3 | 4 | Enter a Postfix Equation (space separated) = 5 6 9 * + 5 | Symbol | Action | Stack 6 | ----------------------------------- 7 | 5 | push(5) | 5 8 | 6 | push(6) | 5,6 9 | 9 | push(9) | 5,6,9 10 | | pop(9) | 5,6 11 | | pop(6) | 5 12 | * | push(6*9) | 5,54 13 | | pop(54) | 5 14 | | pop(5) | 15 | + | push(5+54) | 59 16 | 17 | Result = 59 18 | """ 19 | 20 | import operator as op 21 | 22 | def Solve(postfix): 23 | Stack = [] 24 | Div = lambda x, y: int(x/y) # integer division operation 25 | Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation 26 | 27 | # print table header 28 | print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ") 29 | print('-'*(30+len(postfix))) 30 | 31 | for x in postfix: 32 | if x.isdigit() : # if x in digit 33 | Stack.append(x) # append x to stack 34 | print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 35 | else: 36 | B = Stack.pop() # pop stack 37 | print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 38 | 39 | A = Stack.pop() # pop stack 40 | print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 41 | 42 | Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack 43 | print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 44 | 45 | return int(Stack[0]) 46 | 47 | Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(' ') 48 | print("\n\tResult = ", Solve(Postfix)) 49 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/arrangement_rearrangement/rearrangePositiveNegative.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rearrange positive and negative numbers in O(n) time and O(1) extra space 3 | An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array. 4 | 5 | For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the output should be [9, -7, 8, -3, 5, -1, 2, 4, 6] 6 | 7 | Note: The partition process changes relative order of elements. I.e. the order of the appearance of elements is not maintained with this approach. See this for maintaining order of appearance of elements in this problem. 8 | 9 | 10 | */ 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | 16 | void arrangePosNegAlt(int *arr,int size){ 17 | 18 | int count = 0,idx = 0,storeElements = 0,counter = 0; 19 | for(int i = 0 ; i < size ; i++){ 20 | if(arr[i] < 0){ 21 | // counting the negative values so that we can arrange to that limit only 22 | count++; 23 | } 24 | } // O(n) 25 | 26 | //if exactly half of the elements are negative 27 | if(count == (size/2)){ 28 | // perform the basic alternative operations 29 | // if arr[i] is positive it will occupy the even spaces 30 | // if arr[i] is odd it will occupy the odd spaces 31 | while( counter < size){ 32 | //search for first negative number 33 | } 34 | } 35 | } 36 | 37 | 38 | int main(){ 39 | int size; 40 | cin>>size; 41 | int *arr = new int[size]; 42 | 43 | for(int i = 0 ; i < size ; i++){ 44 | cin>>arr[i]; 45 | } 46 | 47 | arrangePosNegAlt(arr,size); 48 | for(int i = 0 ; i < size ; i++){ 49 | cout< S = new Stack(); 31 | S.push(ROOT); 32 | BinaryTreeNode prev=null; 33 | while(!S.isEmpty()) 34 | { 35 | BinaryTreeNode current = S.peek(); 36 | if(prev==null || prev.left==current || prev.right==current) 37 | { 38 | //traverse left then right 39 | if(current.left!=null) 40 | { 41 | S.push(current.left); 42 | } 43 | else if(current.right!=null) 44 | { 45 | S.push(current.right); 46 | } 47 | } 48 | else if(current.left==prev) 49 | { 50 | if(current.right!=null) 51 | { 52 | S.push(current.right); 53 | } 54 | } 55 | else 56 | { 57 | System.out.print(current.data+" "); 58 | S.pop(); 59 | } 60 | prev=current; 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /trees/binary_tree/printLevelOrder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | /* 5 | Using recursion it holds all the node values such that they print when the level returns to 1. 6 | 7 | 1 ==> 1 ===> PRINT 1 8 | / \ 9 | 2 3 ==> 2 ==> PRINT 2 3 10 | / \ / \ 11 | 4 5 6 7 ==> 3 ==> PRINT 4 5 6 7 12 | 13 | */ 14 | 15 | 16 | 17 | struct Node{ 18 | int data; 19 | struct Node *left; 20 | struct Node *right; 21 | }; 22 | 23 | struct Node* root = NULL; 24 | 25 | struct Node *newNode(int data){ 26 | struct Node* temp = (struct Node*) malloc ( sizeof(struct Node)); 27 | temp->data = data; 28 | temp->left = NULL; 29 | temp->right = NULL; 30 | 31 | 32 | return temp; 33 | } 34 | 35 | int height(struct Node* root){ 36 | if(root == NULL){ 37 | return 0; 38 | } 39 | 40 | int lheight = height(root->left); 41 | int rheight = height(root->right); 42 | 43 | if(lheight > rheight){ 44 | return lheight+1; 45 | } 46 | return rheight + 1; 47 | 48 | } 49 | 50 | void levelOrder(struct Node * root,int level) 51 | { 52 | if(root == NULL) 53 | { 54 | return ; 55 | } 56 | 57 | if(level == 1) 58 | { 59 | printf("%d -> ",root->data); 60 | } 61 | if(level > 1) 62 | { 63 | levelOrder(root->left,level-1); 64 | levelOrder(root->right,level-1); 65 | } 66 | 67 | } 68 | 69 | 70 | void printLevelOrder(struct Node* root){ 71 | int treeHeight = height(root); 72 | int i; 73 | 74 | for(i = 1 ; i <= treeHeight ; i++) 75 | { 76 | levelOrder(root,i); 77 | printf("\n"); 78 | } 79 | } 80 | 81 | 82 | 83 | int main() 84 | { 85 | struct Node* root = newNode(1); 86 | root->left = newNode(2); 87 | root->right = newNode(3); 88 | root->left->left = newNode(4); 89 | root->left->right = newNode(5); 90 | root->right->left = newNode(6); 91 | root->right->right = newNode(7); 92 | 93 | printLevelOrder(root); 94 | } 95 | -------------------------------------------------------------------------------- /graphs/graphRepresentation.java: -------------------------------------------------------------------------------- 1 | package GRAPH.Java; 2 | import java.util.*; 3 | import jdk.internal.org.jline.utils.InputStreamReader; 4 | import java.io.*; 5 | 6 | // Adjancy List Representation of Graph 7 | 8 | class Graph-Representation{ 9 | 10 | static class Edge{ 11 | int src; // source 12 | int nbr; // neighbour 13 | int w; // weight 14 | 15 | Edge(int src,int nbr, int w){ 16 | this.src = src; 17 | this.nbr = nbr; 18 | this.w = w; 19 | } 20 | 21 | public static void main(String[] args){ 22 | 23 | BufferedOutputStream br = new BufferedReader(new InputStreamReader(System.in)); 24 | 25 | // number of vertex 26 | 27 | int size = 6; 28 | 29 | // graph represent as array of arraylist of edges 30 | 31 | ArrayList[] graph = new ArrayList[size]; 32 | 33 | // create list for each vertex 34 | for(int i=0;i(); 37 | } 38 | 39 | // here in first array 0 is connected with 3 with weight 10 40 | // likewise 0 connected with 1 with weight 50...... 41 | 42 | graph[0].add(new Edge(0, 3, 10)); 43 | graph[0].add(new Edge(0, 1, 50)); 44 | 45 | graph[1].add(new Edge(1, 0, 50)); 46 | graph[1].add(new Edge(1, 2, 54)); 47 | 48 | graph[2].add(new Edge(2, 0, 23)); 49 | graph[2].add(new Edge(2, 2, 34)); 50 | graph[2].add(new Edge(2, 4, 52)); 51 | 52 | graph[3].add(new Edge(3, 5, 10)); 53 | graph[3].add(new Edge(3, 4, 40)); 54 | 55 | graph[4].add(new Edge(4, 3, 67)); 56 | graph[4].add(new Edge(4, 1, 89)); 57 | 58 | graph[5].add(new Edge(5, 2, 30)); 59 | graph[5].add(new Edge(5, 1, 20)); 60 | 61 | 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /stacks/linked_stack/LinkedStack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LinkedStack 3 | { 4 | private int length; //indicates the size of the linked list 5 | private StackNode top; //acting like a head of linked list 6 | 7 | public LinkedStack() 8 | { 9 | length=0; 10 | top=null; 11 | } 12 | 13 | //adds a specified data to the top of this stack 14 | public void push(int data) 15 | { 16 | StackNode temp = new StackNode(data); 17 | temp.setNext(top); 18 | top=temp; 19 | length++; 20 | } 21 | 22 | //removes the data at the top of this stack and returns a reference to it.throws an empty stack exception if the stack is empty 23 | public int pop() throws EmptyStackException 24 | { 25 | if(isEmpty()) 26 | { 27 | throw new EmptyStackException(); 28 | } 29 | int result = top.getData(); 30 | top = top.getNext(); 31 | length--; 32 | return result; 33 | } 34 | 35 | //returns a reference to the data at the top of this stack. 36 | //the data is not removed from the stack throws an EmptyStackException if the stack is empty 37 | public int peek() throws EmptyStackException 38 | { 39 | if(isEmpty()) 40 | { 41 | throw new EmptyStackException(); 42 | } 43 | return top.getData(); 44 | } 45 | 46 | //returns true if this stack is empty and false otherwise 47 | public boolean isEmpty() 48 | { 49 | return length==0; 50 | } 51 | 52 | //returns the number of eleements in the stack 53 | public int size() 54 | { 55 | return length; 56 | } 57 | 58 | //returns the string representation of the stack 59 | public String toString() 60 | { 61 | String result=""; 62 | StackNode current=top; 63 | while(current!=null) 64 | { 65 | result=result+current.toString()+"\n"; 66 | current=current.getNext(); 67 | } 68 | return result; 69 | } 70 | } -------------------------------------------------------------------------------- /trees/binary_tree/PrintCousins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct Node{ 8 | int data; 9 | 10 | struct Node *left; 11 | struct Node *right; 12 | }; 13 | 14 | struct Node *newNode(int data){ 15 | struct Node *temp = (struct Node *) malloc (sizeof(struct Node)); 16 | 17 | temp -> data = data; 18 | temp -> left = NULL; 19 | temp -> right = NULL; 20 | return temp; 21 | } 22 | 23 | /* 24 | 25 | 1 26 | / \ 27 | 2 3 28 | / \ / 29 | 4 5 6 30 | / 31 | 7 32 | 33 | 1 2 3 4 5 6 34 | if key == 6 35 | 1 2 3 is ignored as its their root or parents and semi parent; 36 | 4 5 is the cousin as 6 isnt present in its parent node. 37 | ignore 6 as its the key 38 | 39 | 40 | */ 41 | 42 | void findCousins(struct Node *root,int key){ 43 | 44 | struct Node *first = root; 45 | struct Node *second = root; 46 | 47 | if(root == NULL){ 48 | return ; 49 | } 50 | 51 | if(root->data == key || (root->left->data == key || root->right->data == key)){ 52 | cout<<"-1"<right->left->data == key){ 58 | printf("%d",root->left->left->data); 59 | printf("%d",root->left->right->data); 60 | } 61 | } 62 | 63 | findCousins(root->left,key); 64 | findCousins(root->right,key); 65 | } 66 | 67 | int main() 68 | { 69 | struct 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->left->right = newNode(7); 76 | 77 | 78 | findCousins(root,4); 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /stacks/misc/prefixEvaluation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Output: 3 | 4 | Enter a Prefix Equation (space separated) = + 8 ^ 6 2 5 | Symbol | Action | Stack 6 | ----------------------------------- 7 | 2 | push(2) | 2 8 | 6 | push(6) | 2,6 9 | | pop(6) | 2 10 | | pop(2) | 11 | ^ | push(2^6) | 64 12 | 8 | push(8) | 64,8 13 | | pop(8) | 64 14 | | pop(64) | 15 | + | push(64+8) | 72 16 | 17 | Result = 72 18 | """ 19 | 20 | import operator as op 21 | 22 | def Solve(postfix): 23 | Stack = [] 24 | Div = lambda x, y: int(x/y) # integer division operation 25 | Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation 26 | 27 | # print table header 28 | print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ") 29 | print('-'*(30+len(postfix))) 30 | 31 | for x in postfix: 32 | if x.isdigit() : # if x in digit 33 | Stack.append(x) # append x to stack 34 | print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 35 | else: 36 | B = Stack.pop() # pop stack 37 | print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 38 | 39 | A = Stack.pop() # pop stack 40 | print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 41 | 42 | Stack.append( str(Opr[x](int(B), int(A))) ) # evaluate the 2 values poped from stack & push result to stack 43 | print(x.rjust(8), ('push('+B+x+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format 44 | 45 | return int(Stack[0]) 46 | 47 | def Convert(prefix): 48 | prefix.reverse() # Reverse the Prefix Equation 49 | return Solve(prefix) # evaluate the reversed Prefix Equation (as a Postfix Equation) 50 | 51 | Prefix = input("\n\nEnter a Prefix Equation (space separated) = ").strip().split(' ') 52 | print("\n\tResult = ", Convert(Prefix)) 53 | -------------------------------------------------------------------------------- /lists/single/insertANodeInTheMiddle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *link; 8 | }; 9 | 10 | struct node* root; 11 | 12 | void insertAtTail(int value) 13 | { 14 | 15 | struct node * tempNode; 16 | tempNode = (struct node*)malloc(sizeof(struct node)); 17 | tempNode->data = value; 18 | tempNode->link = NULL; 19 | 20 | if(root == NULL) 21 | { 22 | root = tempNode; 23 | } 24 | else 25 | { 26 | struct node *p; 27 | 28 | p = root; 29 | 30 | while(p->link != NULL) 31 | { 32 | p = p->link; 33 | } 34 | 35 | p->link = tempNode; // holds the address of temp 36 | tempNode->link = NULL; // holds NULL 37 | } 38 | 39 | } 40 | int length() 41 | { 42 | int count = 0; 43 | struct node* tempNode; 44 | tempNode = root; 45 | 46 | while(tempNode != NULL) 47 | { 48 | count++; 49 | tempNode = tempNode->link; 50 | } 51 | return count; 52 | } 53 | void addAfter(int value,int position) 54 | { 55 | int i = 1; 56 | if(position > length()) 57 | { 58 | printf("Invalid Location, the list has %d nodes",length()); 59 | } 60 | else 61 | { 62 | struct node * tempNode; 63 | tempNode = (struct node*)malloc(sizeof(struct node)); 64 | struct node * p; 65 | tempNode->data = value;//creating the node 66 | tempNode->link = NULL;//creating the node 67 | p = root; 68 | while(i < position) 69 | { 70 | p = p->link; // traversing every nodes untill the desired position 71 | i++; 72 | } 73 | tempNode->link = p->link; // right connect 74 | p->link = tempNode; //left connection 75 | } 76 | } 77 | 78 | void display() 79 | { 80 | struct node *temp; 81 | temp = root; 82 | 83 | while(temp != NULL) 84 | { 85 | printf("%d ",temp->data); 86 | temp = temp->link; 87 | } 88 | 89 | } 90 | int main() 91 | { 92 | insertAtTail(1); 93 | insertAtTail(2); 94 | insertAtTail(3); 95 | insertAtTail(4); 96 | insertAtTail(5); 97 | //printf("The length is = %d\n",length()); 98 | addAfter(9,3); 99 | display(); 100 | } 101 | -------------------------------------------------------------------------------- /stacks/array_stack/ArrayStack.java: -------------------------------------------------------------------------------- 1 | //ARRAY STACK 2 | public class ArrayStack 3 | { 4 | int[] stack; 5 | int top; 6 | public ArrayStack() 7 | { 8 | this(5); 9 | } 10 | 11 | /** 12 | * Constructor for initializing the size 13 | * */ 14 | public ArrayStack(int size) 15 | { 16 | stack = new int[size]; 17 | top=-1; 18 | } 19 | 20 | /** 21 | * push(int) 22 | * it will push element to the top of the stack 23 | * @return void 24 | * */ 25 | public void push(int value) 26 | { 27 | if(top+1==stack.length) 28 | { 29 | System.out.println("STACK OVERFLOW"); 30 | System.exit(0); 31 | } 32 | stack[++top]=value; 33 | } 34 | 35 | /** 36 | * pop() 37 | * it will take out one element of the stack 38 | * @return int 39 | * */ 40 | public int pop() 41 | { 42 | if(isEmpty()) 43 | { 44 | System.out.println("STACK UNDERFLOW"); 45 | System.exit(0); 46 | } 47 | int temp = stack[top]; 48 | // stack[top]=0; //initializing it to zero 49 | top--; 50 | return temp; 51 | } 52 | 53 | /** 54 | * top() 55 | * it will convey the top element of the stack 56 | * @return int 57 | * */ 58 | public int top() 59 | { 60 | int temp = stack[top]; 61 | return temp; 62 | } 63 | 64 | /** 65 | * isEmpty() 66 | * it will convey whether the stack is empty or not 67 | * @return boolean 68 | * */ 69 | public boolean isEmpty() 70 | { 71 | return top==-1; 72 | } 73 | 74 | /** 75 | * size() 76 | * it will convey the size of the stack 77 | * @return int 78 | **/ 79 | public int size() 80 | { 81 | return top+1; 82 | } 83 | 84 | /** 85 | * print() 86 | * it will print the stack 87 | * @return void 88 | **/ 89 | public void print() 90 | { 91 | for(int i=top;i>=0;i--) 92 | { 93 | System.out.println("| "+stack[i]+" |"); 94 | } 95 | System.out.println("-----"); 96 | } 97 | } -------------------------------------------------------------------------------- /stacks/misc/Infix_to_Prefix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char arr[10000]; 5 | char stack[10000]; 6 | char ans[10000]; 7 | char new[10000]; 8 | int len = 0; 9 | 10 | void push(char ch){ 11 | stack[len] = ch; 12 | len++; 13 | } 14 | 15 | void pop(){ 16 | if(len) 17 | len--; 18 | else 19 | return; 20 | } 21 | 22 | char peek(){ 23 | if(len) 24 | return stack[len-1]; 25 | else 26 | return '\0'; 27 | } 28 | 29 | void print_st(){ 30 | int flag = 0; 31 | for(int i=len-1;i>=0;i--){ 32 | flag = 1; 33 | printf("%c ",stack[i]); 34 | } 35 | if(!flag) 36 | printf("stack is empty\n"); 37 | } 38 | 39 | int check_prec(char ch){ 40 | if((ch=='/' || ch=='*') && (peek()=='+' || peek()=='-' || peek()=='(')){ 41 | return 1; 42 | } 43 | else 44 | return 0; 45 | } 46 | 47 | void reverse(){ 48 | //reverse new 49 | int length = strlen(new); 50 | for(int i=length-1;i>=0;i--){ 51 | if(new[i]=='(') 52 | arr[length-1-i] = ')'; 53 | else if(new[i]==')') 54 | arr[length-1-i] = '('; 55 | else 56 | arr[length-1-i] = new[i]; 57 | } 58 | } 59 | 60 | int main(){ 61 | printf("Infix->Prefix\n"); 62 | printf("enter the expression "); 63 | scanf("%s",new); 64 | printf("Prefix form->\n"); 65 | reverse(); 66 | int track = 0; 67 | for(int i=0;i=0;i--) 103 | printf("%c",ans[i]); 104 | printf("\n"); 105 | } -------------------------------------------------------------------------------- /strings/Strings.java: -------------------------------------------------------------------------------- 1 | public class Strings 2 | { 3 | public static void main(String[] args) 4 | { 5 | /*USAGE OF STRING CLASS IN JAVA*/ 6 | String trial = "Hello World this is github"; 7 | 8 | System.out.println("string:\t" + trial); 9 | System.out.println(); 10 | 11 | System.out.println("METHODS IN STRING CLASS"); 12 | 13 | //charAt() 14 | System.out.println("charAt(3):\t\t\t" + trial.charAt(3)); 15 | 16 | //indexOf() 17 | System.out.println("indexOf('o'):\t\t\t" + trial.indexOf('o')); 18 | System.out.println("indexOf('o',3):\t\t\t" + trial.indexOf('o',3)); 19 | System.out.println("indexOf(\"this\"):\t\t" + trial.indexOf("this")); 20 | System.out.println("indexOf(\"this\",3):\t\t" + trial.indexOf("this",3)); 21 | 22 | //lastIndexOf() 23 | System.out.println("lastIndexOf('o'):\t\t" + trial.lastIndexOf('o')); 24 | System.out.println("lastIndexOf('o',3):\t\t" + trial.lastIndexOf('o',3)); 25 | System.out.println("lastIndexOf(\"this\"):\t\t" + trial.lastIndexOf("this")); 26 | System.out.println("lastIndexOf(\"this\",4):\t\t" + trial.lastIndexOf("this",4)); 27 | 28 | //length() 29 | System.out.println("length():\t\t\t" + trial.length()); 30 | 31 | //substring() 32 | System.out.println("substring(1):\t\t\t" + trial.substring(1)); 33 | System.out.println("substring(3,5):\t\t\t" + trial.substring(3,5)); 34 | 35 | //replace() 36 | System.out.println("replace('a','b'):\t\t" + trial.replace('a','b')); 37 | System.out.println("replace(\"Hello\",\"world\"):\t" + trial.replace("Hello","world")); 38 | 39 | //concat() 40 | System.out.println("concat(\" Hello World\"):\t\t" + trial.concat(" Hello World")); 41 | 42 | //equals() 43 | System.out.println("equals(\"Hello World this is github\"):\t" + trial.equals("hello wotld a bac a")); 44 | 45 | //toUpperCase() 46 | System.out.println("toUpperCase():\t\t\t" + trial.toUpperCase()); 47 | 48 | //toLowerCase() 49 | System.out.println("toLowerCase():\t\t\t" + trial.toLowerCase()); 50 | } 51 | } -------------------------------------------------------------------------------- /arrays/2_d_arrays/spiralOrderMatric.java: -------------------------------------------------------------------------------- 1 | package MISC; 2 | 3 | import java.util.*; 4 | abstract class spiralOrder 5 | { 6 | /** 7 | * for running this program go to JAVA directory as this program is in package 8 | * so follow 9 | * javac MISC/spiralOrder.java 10 | * java MISC/spiralOrder 11 | * 12 | * SAMPLE TEST CASE 13 | * 3 3 14 | * 1 2 3 15 | * 4 5 6 16 | * 7 8 9 17 | * 18 | * OUTPUT 19 | * 1 20 | * 2 21 | * 3 22 | * 6 23 | * 9 24 | * 8 25 | * 7 26 | * 4 27 | * 5 28 | **/ 29 | public static void main(String[] args) 30 | { 31 | Scanner in = new Scanner(System.in); 32 | int n = in.nextInt(); 33 | int m = in.nextInt(); 34 | int[][] arr = new int[n][m]; 35 | for(int i=0;i r 56 | for(int i=sc;i=sc;i--) 74 | { 75 | System.out.println(arr[er-1][i]); 76 | } 77 | er--; 78 | } 79 | 80 | // ^ 81 | // | 82 | if(sc=sr;i--) 85 | { 86 | System.out.println(arr[i][sc]); 87 | } 88 | sc++; 89 | } 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /queues/circular_queue/CircularQueueUsingArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define size 5 3 | 4 | void insertq(int[], int); 5 | void deleteq(int[]); 6 | void display(int[]); 7 | 8 | int front = - 1; 9 | int rear = - 1; 10 | 11 | int main() 12 | { 13 | int n, ch; 14 | int queue[size]; 15 | do 16 | { 17 | printf("\n\n Circular Queue:\n1. Insert \n2. Delete\n3. Display\n0. Exit"); 18 | printf("\nEnter Choice 0-3? : "); 19 | scanf("%d", &ch); 20 | switch (ch) 21 | { 22 | case 1: 23 | printf("\nEnter number: "); 24 | scanf("%d", &n); 25 | insertq(queue, n); 26 | break; 27 | case 2: 28 | deleteq(queue); 29 | break; 30 | case 3: 31 | display(queue); 32 | break; 33 | } 34 | }while (ch != 0); 35 | } 36 | 37 | 38 | void insertq(int queue[], int item) 39 | { 40 | if ((front == 0 && rear == size - 1) || (front == rear + 1)) 41 | { 42 | printf("queue is full"); 43 | return; 44 | } 45 | else if (rear == - 1) //Queue is Empty 46 | { 47 | rear++; 48 | front++; 49 | } 50 | else if (rear == size - 1 && front > 0) 51 | { 52 | rear = 0; 53 | } 54 | else 55 | { 56 | rear++; 57 | } 58 | queue[rear] = item; 59 | } 60 | 61 | void display(int queue[]) 62 | { 63 | int i; 64 | printf("\n"); 65 | if (front > rear) 66 | { 67 | for (i = front; i < size; i++) 68 | { 69 | printf("%d ", queue[i]); 70 | } 71 | for (i = 0; i <= rear; i++) 72 | printf("%d ", queue[i]); 73 | } 74 | else 75 | { 76 | for (i = front; i <= rear; i++) 77 | printf("%d ", queue[i]); 78 | } 79 | } 80 | 81 | void deleteq(int queue[]) 82 | { 83 | if (front == - 1) //Queue is empty 84 | { 85 | printf("Queue is empty "); 86 | } 87 | else if (front == rear) //Only 1 element present 88 | { 89 | printf("\n %d deleted", queue[front]); 90 | front = - 1; 91 | rear = - 1; 92 | } 93 | else 94 | { 95 | printf("\n %d deleted", queue[front]); 96 | front++; 97 | } 98 | } -------------------------------------------------------------------------------- /arrays/4_d_arrays/4darrays.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 4D ARRAYS 3 | */ 4 | #include 5 | int main() 6 | { 7 | /* 8 | * FOR 4D ARRAYS IAMGINE A 3D CUBE SOLVED IN TIME TAKEN AS FOURTH DIMENSIONAL 9 | */ 10 | int length; //LENGTH OF THE CUBE 11 | int breadth; //BREADTH OF THE CUBE 12 | int height; //HEIGHT OF THE CUBE 13 | int tym; //HOW MANY CUBE IS ACCESSED 14 | printf("Enter the time YOU WANT TO access the cube\n"); 15 | scanf("%d",&tym); 16 | 17 | printf("Enter the length,breadth and height of the cube\n"); 18 | scanf("%d %d %d",&length,&breadth,&height); 19 | int arr[tym][height][length][breadth]; //declared 4d array 20 | printf("Enter the elements of the 4d array\n"); 21 | 22 | for(register int i=0;i 2 | #include 3 | 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *link; 9 | }; 10 | struct node * root; 11 | 12 | // to insert at end 13 | void insertAtTail(int value) 14 | { 15 | struct node * temp; 16 | temp = (struct node *)malloc(sizeof(struct node)); 17 | temp->data = value; 18 | temp->link = NULL; 19 | 20 | if(root == NULL) 21 | { 22 | root = temp; 23 | } 24 | else 25 | { 26 | struct node *p; 27 | p = root; 28 | 29 | while(p->link != NULL) 30 | { 31 | p = p->link; 32 | } 33 | p->link = temp; 34 | temp->link = NULL; 35 | } 36 | } 37 | 38 | // to find length 39 | int length() 40 | { 41 | int count = 0; 42 | struct node* tempNode; 43 | tempNode = root; 44 | 45 | while(tempNode != NULL) 46 | { 47 | count++; 48 | tempNode = tempNode->link; 49 | } 50 | return count; 51 | } 52 | // to delete 53 | 54 | void deleteNode(int position) 55 | { 56 | if(position > length()) 57 | { 58 | printf("Sorry the position to delete dosent exist , currently there are %d nodes in the linked list\n",length()); 59 | } 60 | else if(position == 1) 61 | { 62 | // the user wants to delete the first node 63 | struct node * temp; 64 | temp = root; 65 | root = temp->link; // root points the second node 66 | temp->link = NULL; //detaching the first node 67 | free(temp); // freeing the memory 68 | } 69 | else 70 | { 71 | struct node* p; 72 | struct node* q; 73 | p = root; // initially it contains root 74 | int i = 1; 75 | 76 | while(i < position-1) 77 | { 78 | p = p -> link; 79 | i++; 80 | } 81 | q = p->link; // next address we are storing; 82 | p->link = q->link; 83 | q->link = NULL; 84 | free(q); 85 | } 86 | } 87 | //to display 88 | void display() 89 | { 90 | struct node* temp; 91 | temp = root; 92 | 93 | while(temp != NULL) 94 | { 95 | printf("%d ",temp->data); 96 | temp = temp->link; 97 | } 98 | printf("\n"); 99 | 100 | } 101 | 102 | int main() 103 | { 104 | insertAtTail(1); 105 | insertAtTail(2); 106 | insertAtTail(3); 107 | insertAtTail(4); 108 | insertAtTail(5); 109 | display(); 110 | deleteNode(3); 111 | display(); 112 | } 113 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/array_rotations/findPairWithGivenSumInRotatedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /* 10 | BruteForce with least complexity : 11 | 12 | MergeSort => O(nlog(n)); 13 | BinarySearch => O(log(n)); 14 | 15 | T(n) = T(nlog(n))+T(log(n)); 16 | 17 | MAX COMPLEXITY O( n * log(n)); 18 | 19 | 20 | 21 | */ 22 | int binarySearch(int * arr , int start , int end , int key){ 23 | 24 | if(start > end){ 25 | return 0 ; 26 | } 27 | int mid = (start + end)/2; 28 | 29 | if(arr[mid] == key){ 30 | return mid; 31 | } 32 | else if(key > arr[mid]){ 33 | binarySearch(arr,mid+1,end,key); 34 | } 35 | else{ 36 | binarySearch(arr,start,mid-1,key); 37 | } 38 | 39 | 40 | } 41 | 42 | void findSumIn_Rotated_Sorted_Array(int *arr,int size , int sum){ 43 | map storePairs; 44 | map :: iterator it; 45 | bool flag = false; 46 | /* CODE WITH THE MAXIMUM COMPLEXITY */ 47 | // Sort the array , best would have been mergeSort 48 | sort(arr,arr+size); 49 | int i = 0; 50 | while(i < size){ 51 | int temp = arr[i]; 52 | int findNextSum = (sum - temp); 53 | int index = binarySearch(arr,0,size-1,findNextSum); 54 | 55 | 56 | if(index == 0){ 57 | } 58 | else{ 59 | storePairs.insert(pair(temp,arr[index])); 60 | flag = true; 61 | } 62 | i++; 63 | } 64 | 65 | if(flag == true){ 66 | cout<<"true"<first<<" , "<second<<"}"<>size; 84 | arr = new int[size]; 85 | cout<<"Enter the elements of the array"<>arr[i]; 88 | } 89 | cout<<"Give the sum whose pair is to be found"<>sum; 91 | 92 | findSumIn_Rotated_Sorted_Array(arr,size,sum); 93 | delete[] arr; 94 | 95 | 96 | } -------------------------------------------------------------------------------- /lists/single/reverseList.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *link; 9 | }; 10 | struct node * root; 11 | void insertTail(int value) 12 | { 13 | struct node* temp; 14 | temp = (struct node*)malloc(sizeof(struct node)); 15 | temp->data = value; 16 | temp->link = NULL; 17 | 18 | if(root == NULL) 19 | { 20 | root = temp; 21 | } 22 | else 23 | { 24 | struct node*p; 25 | p = root; 26 | 27 | while(p->link != NULL) 28 | { 29 | p = p->link; 30 | } 31 | p->link = temp; // the tempnode becomes the newNode; 32 | temp->link = NULL; // the link of the tempNode becomes NULL; 33 | } 34 | } 35 | int length() 36 | { 37 | int count = 0; 38 | struct node *temp ; 39 | temp = root; 40 | 41 | while(temp != NULL) 42 | { 43 | count++; 44 | temp = temp->link; 45 | } 46 | return count; 47 | } 48 | void reverseList() 49 | { 50 | int i = 0; // the first node 51 | int j = length()-1; // the last node 52 | struct node *p,*q; 53 | p=q=root; // both pointing to root, do not disturb the head. 54 | 55 | while(i link; // q points to the last node , then goes back to root address then again points to the second last node and then the thirdlast and so on 63 | } 64 | // same as array reverse 65 | int temp = p->data; 66 | p->data = q->data; 67 | q->data = temp; 68 | // incrementing i and decrementing j for swapping 69 | i++; 70 | j--; 71 | p = p->link; // p points to the next node 72 | q = root; // q goes back to the starting position as singly_linkedlist cant go backward 73 | } 74 | } 75 | 76 | void display() 77 | { 78 | struct node*temp; 79 | temp = root; 80 | 81 | while(temp != NULL) 82 | { 83 | printf("The node is %d\n",temp->data); 84 | temp = temp->link; 85 | } 86 | } 87 | int main() 88 | { 89 | insertTail(1); 90 | insertTail(2); 91 | insertTail(3); 92 | insertTail(4); 93 | insertTail(5); 94 | 95 | display(); 96 | 97 | printf("the nodes after reversing are\n"); 98 | reverseList(); 99 | display(); 100 | } 101 | -------------------------------------------------------------------------------- /arrays/1_d_arrays/array_rotations/findMaxValueWithOnlyRotationsAllowed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /* 8 | A = 1 20 2 10 9 | 10 | after 2 rotations 11 | 12 | 2 10 1 20 13 | 14 | the sum becomes 72 15 | 16 | which is max; 17 | 18 | 19 | COMPLEXITIES: 20 | 21 | TimeComplexity is most probably 2O(n*k), where k = no of rotations 22 | SpaceComplexity is O(m+n); 23 | 24 | 25 | 26 | */ 27 | 28 | /* Brute force method */ 29 | void printSumArr(int * , int); 30 | int Calculate_Rotation_Sum(int * arr, int size){ 31 | int eachRotationSum = 0; 32 | for(int i = 0 ; i < size ; i++ ){ 33 | eachRotationSum += arr[i]*i; 34 | } 35 | 36 | return eachRotationSum; 37 | } 38 | 39 | void RotateArray(int * arr ,int size){ 40 | int temp = arr[0]; 41 | 42 | for(int i = 0 ; i < size - 1 ; i++){ 43 | arr[i] = arr[i+1]; 44 | } 45 | 46 | arr[size-1] = temp; 47 | } 48 | 49 | int findMaxWithOnly_Rotations(int *arr,int size){ 50 | 51 | int firstSum = 0,j=0,rotations = 0,foundMax = 0; 52 | int *rotationSum = new int[size]; 53 | /* find all rotations and sum them */ 54 | 55 | for(int i = 0 ; i < size ; i++){ 56 | firstSum += arr[i]*i; 57 | } //O(n) 58 | rotationSum[j] = firstSum; 59 | j = 1; 60 | 61 | while(rotations < size){ 62 | RotateArray(arr,size); 63 | rotationSum[j++] = Calculate_Rotation_Sum(arr,size); 64 | rotations++; 65 | } 66 | 67 | printSumArr(rotationSum , size); 68 | for(int i = 0 ; i < j ; i++){ 69 | foundMax = max(rotationSum[i],foundMax); 70 | } 71 | 72 | return foundMax; 73 | } 74 | 75 | void printSumArr(int * arr , int size){ 76 | 77 | cout<<"The array rotations are"<>size; 88 | arr = new int[size]; 89 | 90 | cout<<"Enter the array"<>arr[i]; 93 | } 94 | 95 | int Max_Sum = findMaxWithOnly_Rotations(arr,size); 96 | cout<<"The max sum is "< 2 | #include 3 | using namespace std; 4 | 5 | 6 | /* 7 | 8 | Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. It is given that ll array elements are distinct. 9 | 10 | Examples: 11 | 12 | Input: arr[] = {7, 10, 4, 3, 20, 15} 13 | k = 3 14 | Output: 7 15 | 16 | Input: arr[] = {7, 10, 4, 3, 20, 15} 17 | k = 4 18 | Output: 10 19 | 20 | 21 | 22 | */ 23 | 24 | void merge(int *Arr, int start, int mid, int end) { 25 | // create a temp array 26 | int temp[end - start + 1]; 27 | 28 | // crawlers for both intervals and for temp 29 | int i = start, j = mid+1, k = 0; 30 | 31 | // traverse both arrays and in each iteration add smaller of both elements in temp 32 | while(i <= mid && j <= end) { 33 | if(Arr[i] <= Arr[j]) { 34 | temp[k] = Arr[i]; 35 | k += 1; i += 1; 36 | } 37 | else { 38 | temp[k] = Arr[j]; 39 | k += 1; j += 1; 40 | } 41 | } 42 | 43 | // add elements left in the first interval 44 | while(i <= mid) { 45 | temp[k] = Arr[i]; 46 | k += 1; i += 1; 47 | } 48 | 49 | // add elements left in the second interval 50 | while(j <= end) { 51 | temp[k] = Arr[j]; 52 | k += 1; j += 1; 53 | } 54 | 55 | // copy temp to original interval 56 | for(i = start; i <= end; i += 1) { 57 | Arr[i] = temp[i - start]; 58 | } 59 | } 60 | 61 | // Arr is an array of integer type 62 | // start and end are the starting and ending index of current interval of Arr 63 | 64 | void mergeSort(int *Arr, int start, int end) { 65 | 66 | if(start < end) { 67 | int mid = (start + end) / 2; 68 | mergeSort(Arr, start, mid); 69 | mergeSort(Arr, mid+1, end); 70 | merge(Arr, start, mid, end); 71 | } 72 | } 73 | 74 | 75 | int Klargest(int *arr,int size , int k){ 76 | 77 | return arr[size-k]; 78 | } 79 | 80 | int Ksmallest(int *arr,int k){ 81 | 82 | 83 | return arr[k-1]; 84 | 85 | } 86 | int main(){ 87 | long long int size,k; 88 | cin>>size; 89 | int * arr = new int[size]; 90 | 91 | for(int i = 0 ; i < size ; i++){ 92 | cin>>arr[i]; 93 | } 94 | cin>>k; 95 | 96 | mergeSort(arr,0,size-1); 97 | int largest = Klargest(arr,size,k); 98 | int smallest = Ksmallest(arr,k); 99 | 100 | cout<<"The kth largest element is "< abc^+ 16 | """ 17 | 18 | def infix_2_postfix(infix): 19 | Stack = [] 20 | Postfix = [] 21 | priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator 22 | print_width = len(Infix) if(len(Infix)>7) else 7 23 | 24 | # Print table header for output 25 | print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ") 26 | print('-'*(print_width*3+7)) 27 | 28 | for x in infix: 29 | if x.isalpha() or x.isdigit() : Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix 30 | elif x == '(' : Stack.append(x) # if x is "(" push to Stack 31 | elif x == ')' : # if x is ")" pop stack until "(" is encountered 32 | while Stack[-1] != '(' : 33 | Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix 34 | Stack.pop() 35 | else: 36 | if len(Stack) == 0 : Stack.append(x) #If stack is empty, push x to stack 37 | else: 38 | while len(Stack) > 0 and priority[x] <= priority[Stack[-1]] : # while priority of x is not greater than priority of element in the stack 39 | Postfix.append( Stack.pop() ) # pop stack & add to Postfix 40 | Stack.append(x) # push x to stack 41 | 42 | print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format 43 | 44 | while len(Stack) > 0 : # while stack is not empty 45 | Postfix.append( Stack.pop() ) # pop stack & add to Postfix 46 | print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format 47 | 48 | return "".join(Postfix) # return Postfix as str 49 | 50 | Infix = input("\nEnter an Infix Equation (space separated) = ") #Input an Infix equation 51 | Infix = "".join(Infix.split()) #Remove spaces from the input 52 | print("\n\t", Infix, "->", infix_2_postfix(Infix)) 53 | -------------------------------------------------------------------------------- /trees/binary_tree/constructTreeInPost.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* 6 | 1 => ROOT 7 | / \ 8 | 2 3 => level 1 9 | / \ / 10 | 4 5 6 => level 2 11 | 12 | inorder = (left->root->right) => [4,2,5,1,6,3]; 13 | postorder = (left->right->root) => [4,5,2,6,3,1]; 14 | preorder = (root->left->right) => [1,2,4,5,3,6]; 15 | 16 | pseudocode; 17 | */ 18 | 19 | struct Node{ 20 | int data; 21 | struct Node *left; 22 | struct Node *right; 23 | }; 24 | 25 | struct Node *newNode(int data){ 26 | struct Node *tempNode = (struct Node *) malloc ( sizeof(struct Node) ); 27 | tempNode -> data = data; 28 | tempNode -> left = NULL; 29 | tempNode -> right = NULL; 30 | return tempNode; 31 | } 32 | 33 | int find_Inorder_Index(int inorder[],int data , int size) 34 | { 35 | printf("The data is %d\n",data); 36 | int i; 37 | for(i = size ; i >= 0 ; i--) 38 | { 39 | if(inorder[i] == data) 40 | { 41 | break; 42 | } 43 | } 44 | return i; 45 | } 46 | 47 | struct Node *buildNodes(int in[],int post[],int start,int end,int *end_root) 48 | { 49 | 50 | if(start > end){ 51 | return NULL; 52 | } 53 | 54 | 55 | struct Node *root = newNode(post[*end_root]); 56 | (*end_root)--; 57 | if(start == end){ 58 | return root; 59 | } 60 | // this will search the data in the inorder array and return the index 61 | int searchIndex = find_Inorder_Index(in,root->data,end); 62 | 63 | // this whole thing will construct the right side of the tree 64 | root->right = buildNodes(in,post,searchIndex+1,end,end_root); 65 | 66 | // this whole thing will construct the left side of the tree 67 | root->left = buildNodes(in,post,start,searchIndex-1,end_root); 68 | 69 | return (root); 70 | 71 | } 72 | 73 | struct Node *constructTree(int in[],int post[],int N) 74 | { 75 | int end_root = N-1; 76 | // sending the address of the end root 77 | struct Node *root = buildNodes(in,post,0,N-1,&end_root); 78 | return (root); 79 | } 80 | 81 | void printPreorder(struct Node *root){ 82 | 83 | if(root == NULL){ 84 | return ; 85 | } 86 | 87 | printf("%d=>",root->data); 88 | printPreorder(root->left); 89 | printPreorder(root->right); 90 | } 91 | 92 | int main(){ 93 | 94 | int in[6] = {4,2,5,1,6,3}; 95 | int post[6] = {4,5,2,6,3,1}; 96 | int N = 6; 97 | struct Node *root; 98 | 99 | root = constructTree(in,post,N); 100 | printPreorder(root); 101 | } 102 | -------------------------------------------------------------------------------- /queues/linked_queue/queueUsingLinkedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct node{ 4 | int data; 5 | struct node* next; 6 | }; 7 | 8 | struct node* front; 9 | struct node* rear; 10 | 11 | struct node* getnewnode(int data){ 12 | struct node* temp = (struct node*)malloc(sizeof(struct node)); 13 | temp->data = data; 14 | temp->next = NULL; 15 | } 16 | 17 | void enqueue(int data){ 18 | if(front == NULL){ 19 | front = getnewnode(data); 20 | rear = front; 21 | return; 22 | } 23 | rear->next = getnewnode(data); 24 | rear = rear->next; 25 | } 26 | 27 | void dequeue(){ 28 | if(front == rear){ 29 | struct node* temp = front; 30 | free(temp); 31 | front = rear = NULL; 32 | return; 33 | } 34 | struct node* temp = front; 35 | front = front->next; 36 | free(temp); 37 | } 38 | 39 | void print_ll(){ 40 | struct node* temp = front; 41 | while(temp != NULL){ 42 | printf("%d ",temp->data); 43 | temp = temp->next; 44 | } 45 | } 46 | 47 | void search(int val){ 48 | struct node* temp = front; 49 | int i=1; 50 | while(temp != NULL){ 51 | if(temp->data == val){ 52 | printf("%d is found at position %d\n",val,i); 53 | return; 54 | } 55 | i++; 56 | temp = temp->next; 57 | } 58 | printf("%d is not present in the list\n",val); 59 | } 60 | 61 | int main(){ 62 | front = NULL;rear = NULL; 63 | printf("operations in the queue are-> 0-enqueue, 1-dequeue, 2-search, 3-display, 4-display front, 5-display rear, 6-check if empty "); 64 | while(1){ 65 | printf("\nenter your choice ");int q;scanf("%d",&q); 66 | switch(q){ 67 | case(0): 68 | printf("enter number to be inserted "); 69 | int num; 70 | scanf("%d",&num); 71 | enqueue(num); 72 | print_ll(); 73 | break; 74 | case(1): 75 | if(front == NULL) 76 | printf("queue is empty\n"); 77 | else{ 78 | dequeue(); 79 | print_ll(); 80 | } 81 | break; 82 | case(2): 83 | if(front == NULL) 84 | printf("queue is empty\n"); 85 | else{ 86 | printf("\nenter the number to be searched "); 87 | int val;scanf("%d",&val); 88 | search(val); 89 | } 90 | break; 91 | case(3): 92 | if(front == NULL) 93 | printf("queue is empty\n"); 94 | else 95 | print_ll(); 96 | break; 97 | case(4): 98 | printf("%d",front->data); 99 | break; 100 | case(5): 101 | printf("%d",rear->data); 102 | break; 103 | case(6): 104 | if(front == NULL) 105 | printf("queue is empty\n"); 106 | else 107 | printf("queue is not empty\n"); 108 | break; 109 | default: 110 | printf("invalid"); 111 | } 112 | printf("\ndo you want to continue(y/n)? "); 113 | char ch;scanf(" %c",&ch); 114 | if(ch=='y') 115 | continue; 116 | else 117 | break; 118 | } 119 | } -------------------------------------------------------------------------------- /trees/binary_tree/inordertraversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct Node 4 | { 5 | int data; 6 | struct Node *left; 7 | struct Node *right; 8 | }; 9 | 10 | struct Node *root = NULL; 11 | 12 | void insert(int data) 13 | { 14 | struct Node *tempNode = (struct Node *)malloc(sizeof(struct Node)); 15 | struct Node *current; 16 | struct Node *parent; 17 | 18 | tempNode->data = data; 19 | tempNode->left = NULL; 20 | tempNode->right = NULL; 21 | 22 | //if tree is empty 23 | 24 | if (root == NULL) 25 | { 26 | root = tempNode; 27 | } 28 | else 29 | { 30 | current = root; 31 | parent = NULL; 32 | 33 | while (1) 34 | { 35 | parent = current; 36 | if (data < parent->data) 37 | { 38 | current = current->left; 39 | 40 | if (current == NULL) 41 | { 42 | parent->left = tempNode; 43 | return; 44 | } 45 | } 46 | else 47 | { 48 | current = current->right; 49 | 50 | if (current == NULL) 51 | { 52 | parent->right = tempNode; 53 | return; 54 | } 55 | } 56 | } 57 | } 58 | } 59 | 60 | struct Node *search(int data) 61 | { 62 | struct Node *current = root; 63 | 64 | printf("visiting elements"); 65 | 66 | while (current->data != data) 67 | { 68 | if (current != NULL) 69 | { 70 | printf("%d", current->data); 71 | 72 | if (current->data > data) 73 | { 74 | current = current->left; 75 | } 76 | else 77 | { 78 | current = current->right; 79 | } 80 | } 81 | if (current == NULL) 82 | { 83 | return NULL; 84 | } 85 | } 86 | 87 | return current; 88 | } 89 | 90 | void printInorder(struct Node *root) 91 | { 92 | 93 | if (root == NULL) 94 | { 95 | return; 96 | } 97 | 98 | printInorder(root->left); 99 | printf("%d ", root->data); 100 | printInorder(root->right); 101 | } 102 | int main() 103 | { 104 | int i; 105 | int array[7] = {27, 14, 35, 10, 19, 31, 42}; 106 | 107 | for (i = 0; i < 7; i++) 108 | insert(array[i]); 109 | 110 | i = 31; 111 | struct Node *temp = search(i); 112 | 113 | if (temp != NULL) 114 | { 115 | printf("[%d] Element found.", temp->data); 116 | printf("\n"); 117 | } 118 | else 119 | { 120 | printf("[ x ] Element not found (%d).\n", i); 121 | } 122 | 123 | i = 15; 124 | temp = search(i); 125 | 126 | if (temp != NULL) 127 | { 128 | printf("[%d] Element found.", temp->data); 129 | printf("\n"); 130 | } 131 | else 132 | { 133 | printf("[ x ] Element not found (%d).\n", i); 134 | } 135 | 136 | printf("\nInorder traversal: "); 137 | printInorder(root); 138 | return 0; 139 | } 140 | -------------------------------------------------------------------------------- /stacks/misc/balancedParanthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | bool isempty(); 6 | 7 | /*=======> IMPLEMENTATION OF STACK <=======*/ 8 | static int top = -1; //storing top of a stack 9 | char *stack; //dynamic stack 10 | 11 | 12 | /*===============> ISEMPTY <===============*/ 13 | //returns boolean whether the stack is empty or not 14 | bool isempty() 15 | { 16 | return top==-1; 17 | } 18 | 19 | /*================> PUSH <=================*/ 20 | void push(char value) 21 | { 22 | stack[++top] = value; 23 | } 24 | 25 | /*================> POP <==================*/ 26 | void pop() 27 | { 28 | if(isempty()) 29 | { 30 | cout << "UNDERFLOW" << endl; 31 | exit(0); 32 | } 33 | stack[top]=0; 34 | top--; 35 | } 36 | 37 | /*================> PEEK <=================*/ 38 | //return the top element of the stack 39 | char peek() 40 | { 41 | return stack[top]; 42 | } 43 | 44 | /*==============> print the stack <=========*/ 45 | void display() 46 | { 47 | for(int i = 0 ; i <= top ; i++) 48 | { 49 | cout <<"| " < SIZE <==============*/ 58 | int size() 59 | { 60 | return top+1; 61 | } 62 | /* ******************************************* */ 63 | //returns the bracket inversion 64 | char invertBracket(char expr) 65 | { 66 | switch(expr) 67 | { 68 | case ']': 69 | return '['; 70 | case '}': 71 | return '{'; 72 | case ')': 73 | return '('; 74 | default: 75 | return ' '; 76 | } 77 | } 78 | bool balancedParanthesis(string expression) 79 | { 80 | stack = new char[expression.size()]; //allocating dynamic stack 81 | 82 | int i = 0; 83 | while(expression[i] != '\0') 84 | { 85 | if(expression[i] == '[' || expression[i]=='{' || expression[i]== '(') 86 | { 87 | push(expression[i]); 88 | } 89 | else if(expression[i]==']' || expression[i]=='}' || expression[i]==')') 90 | { 91 | if(isempty()) 92 | { 93 | return false; 94 | } 95 | //check top 96 | if(invertBracket(expression[i])==peek()) //if bracket is same as the top element of the stack 97 | { 98 | pop(); 99 | } 100 | } 101 | i++; 102 | } 103 | if(isempty()) 104 | { 105 | delete [] stack; 106 | return true; 107 | } 108 | else 109 | { 110 | delete [] stack; 111 | return false; 112 | } 113 | } 114 | 115 | int main() 116 | { 117 | int ans; 118 | string str; 119 | getline(cin,str); 120 | if(balancedParanthesis(str)) 121 | { 122 | cout << "BRACKETS ARE BALANCED" << endl; 123 | } 124 | else 125 | { 126 | cout << "BRACKETS NOT BALANCED" << endl; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTION 2 | 3 | Thanks for coming here !!! 4 | 5 | Please help us by making a **star** on this repository. 6 | 7 | ## :rocket: Coding Conventions 8 | 9 | 1. Directory names should be in lowercase with underscore `_` if the name contains any space. 10 | 2. Code file name should be in camel casing for example `singleLinkedList.c` 11 | 3. No need to add .gitignore files it will be maintained in the root only 12 | 4. Make sure filename is unique in specific directory 13 | 5. Copying of code some other platforms such as GFG is not allowed. 14 | 15 | ### :file_folder: Directory Conventions 16 | 17 | * data_structure 18 | * data_structure_type 19 | * codeWithExtension (unique name with no duplicate data structure) 20 | 21 | ## HACKTOBER FEST Guidelines for October (Updated) 22 | 23 | For contributing in October read all these guidelines given below: 24 | 25 | * Firstly read the README where we have all the implemented Data Structures are listed that are added to this repository and please go through our project coding guidelines. 26 | 27 | * After deciding which Data Structure implementation and which language **create a pull request** with the code changes and the README index changes. Make sure you **send as PR in the Hacktober fest PR template only**. 28 | 29 | * After sending the PR, wait for the response from our side 30 | 31 | * PR Review Process 32 | * Firstly if the PR seems to be valid then it will be labelled as `HacktoberFest22` and with the `specific language label` and will be linked to the `Project` via maintainer 33 | * If the PR is wrongly sent then it will be marked as `invalid` 34 | * Secondly after adding the labels if everything seems fine either your PR will be approved or the PR will be marked for Request Changes 35 | * Before merging the changes the PR will be marked with **hacktoberfest-accepted** label 36 | * If the requested changes are not done in a week then the PRs will be marked as **hacktoberfest-expiry** and the other PRs which are not merged before 1 November will also be marked as **hacktoberfest-expiry**. 37 | 38 | * If you want to check your PRs status you can now check them at our `HacktoberFest22 project`. 39 | * If someone tries to spam this PR process then the user's PRs will be marked as `spam` and as a community we will make sure you don't participate in HacktoberFest anymore. 40 | 41 | ## OUTSIDE HACKTOBER FEST (Other than October) 42 | 43 | * Before contribution see through repository index and check which Algorithm is missing and in which language. 44 | * For doing the contribution **fork the repository** and **send us an pull request** but make sure you use the **Pull Request template** 45 | * We make sure that pull request is merged ASAP if valid. 46 | 47 | ## FAQs 48 | 49 | ### How can we add the language types that are not supported 50 | 51 | Don't worry just send us a valid PR and we will add the language support automatically. Feel free to choose any language. 52 | 53 | Thanks !!! 54 | 55 | Happy Contributing !!! 56 | -------------------------------------------------------------------------------- /stacks/misc/infixToPrefix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Output: 3 | 4 | Enter an Infix Equation (space separated) = a + b ^ c 5 | Symbol | Stack | Postfix 6 | ---------------------------- 7 | c | | c 8 | ^ | ^ | c 9 | b | ^ | cb 10 | + | + | cb^ 11 | a | + | cb^a 12 | | | cb^a+ 13 | 14 | a+b^c (Infix) -> +a^bc (Prefix) 15 | """ 16 | 17 | def infix_2_postfix(infix): 18 | Stack = [] 19 | Postfix = [] 20 | priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator 21 | print_width = len(Infix) if(len(Infix)>7) else 7 22 | 23 | # Print table header for output 24 | print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ") 25 | print('-'*(print_width*3+7)) 26 | 27 | for x in infix: 28 | if x.isalpha() or x.isdigit() : Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix 29 | elif x == '(' : Stack.append(x) # if x is "(" push to Stack 30 | elif x == ')' : # if x is ")" pop stack until "(" is encountered 31 | while Stack[-1] != '(' : 32 | Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix 33 | Stack.pop() 34 | else: 35 | if len(Stack) == 0 : Stack.append(x) #If stack is empty, push x to stack 36 | else: 37 | while len(Stack) > 0 and priority[x] <= priority[Stack[-1]] : # while priority of x is not greater than priority of element in the stack 38 | Postfix.append( Stack.pop() ) # pop stack & add to Postfix 39 | Stack.append(x) # push x to stack 40 | 41 | print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format 42 | 43 | while len(Stack) > 0 : # while stack is not empty 44 | Postfix.append( Stack.pop() ) # pop stack & add to Postfix 45 | print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format 46 | 47 | return "".join(Postfix) # return Postfix as str 48 | 49 | def infix_2_prefix(Infix): 50 | Infix = list(Infix[::-1]) # reverse the infix equation 51 | for i in range(len(Infix)): 52 | if Infix[i] == '(' : Infix[i] = ')' # change "(" to ")" 53 | elif Infix[i] == ')' : Infix[i] = '(' # change ")" to "(" 54 | return (infix_2_postfix("".join(Infix)))[::-1] # call infix_2_postfix on Infix, return reverse of Postfix 55 | 56 | Infix = input("\nEnter an Infix Equation (space separated) = ") #Input an Infix equation 57 | Infix = "".join(Infix.split()) #Remove spaces from the input 58 | print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)") 59 | -------------------------------------------------------------------------------- /lists/double/doubleLinkedList.cpp: -------------------------------------------------------------------------------- 1 | //1)insert at beg,end,middle 2 | //2)delete at beg,end,middle 3 | //3)reverse 4 | //4)print 5 | 6 | #include 7 | using namespace std; 8 | struct Node{ 9 | int data; 10 | Node* prev; 11 | Node* next; 12 | Node(int x) 13 | { 14 | data=x; 15 | prev=NULL; 16 | next=NULL; 17 | } 18 | }; 19 | void printList(Node* head) 20 | {Node* temp=head; 21 | while(temp) 22 | { 23 | cout<data<<"->"; 24 | temp=temp->next; 25 | } 26 | cout<next=head; 31 | head->prev=temp; 32 | head=temp; 33 | return temp; 34 | 35 | } 36 | Node* insertAtEnd(Node* head,int i) 37 | { 38 | Node*temp=new Node(i); 39 | Node* cur=head; 40 | while(cur->next) 41 | { 42 | cur=cur->next; 43 | } 44 | cur->next=temp; 45 | temp->prev=cur; 46 | return head; 47 | } 48 | Node* insertAtMiddle(Node* head,int d,int i) 49 | { Node*temp=new Node(i); 50 | Node* cur=head; 51 | while(cur->data!=d) 52 | { 53 | cur=cur->next; 54 | } 55 | temp->next=cur->next; 56 | temp->prev=cur; 57 | cur->next->prev=temp; 58 | cur->next=temp; 59 | return head; 60 | 61 | 62 | } 63 | Node* deleteAtBeg(Node* head) 64 | { 65 | if(head==NULL) 66 | { 67 | return head; 68 | } 69 | else{ 70 | Node* t=head; 71 | head=head->next; 72 | head->prev=NULL; 73 | delete t; 74 | return head; 75 | } 76 | } 77 | Node* deleteAtEnd(Node* head) 78 | { 79 | if(head==NULL) 80 | { 81 | return head; 82 | } 83 | else{ 84 | Node* t=head; 85 | while(t->next->next) 86 | { 87 | t=t->next; 88 | } 89 | Node* tt=t->next; 90 | t->next=NULL; 91 | tt->prev=NULL; 92 | delete tt->next; 93 | return head; 94 | } 95 | } 96 | Node* deleteAtMid(Node* head,int d) 97 | { 98 | if(head==NULL) 99 | { 100 | return head; 101 | } 102 | else{ 103 | Node* temp=head; 104 | while(temp->data!=d) 105 | { 106 | temp=temp->next; 107 | } 108 | if(temp==NULL) 109 | { 110 | return head; 111 | } 112 | else{ 113 | Node* tt=temp->next; 114 | temp->next=tt->next; 115 | tt->prev=NULL; 116 | tt->next->prev=temp; 117 | tt->next=NULL; 118 | delete tt; 119 | return head; 120 | } 121 | } 122 | } 123 | 124 | Node* reverse(Node* head) 125 | { Node* cur=head; 126 | Node* pre=NULL; 127 | Node* nex=NULL; 128 | while(cur) 129 | { nex=cur->next; 130 | cur->next=pre; 131 | cur->prev=nex; 132 | pre=cur; 133 | cur=nex; 134 | } 135 | return pre; 136 | } 137 | int main() 138 | { 139 | Node* head=new Node(1); 140 | head->next=new Node(2); 141 | head->next->prev=head; 142 | head->next->next=new Node(3); 143 | head->next->next->prev=head->next; 144 | head=insertAtBeg(head,4); 145 | head=insertAtEnd(head,5); 146 | head=insertAtMiddle(head,2,7); 147 | head=reverse(head); 148 | head=deleteAtBeg(head); 149 | 150 | printList(head); 151 | head=deleteAtMid(head,2); 152 | printList(head); 153 | head=deleteAtEnd(head); 154 | printList(head); 155 | return 0; 156 | } 157 | -------------------------------------------------------------------------------- /lists/double/treeUsingDoubly.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | /* 7 | Process execution 8 | +++++++++++++++++++ 9 | The idea can be described using below steps. 10 | 1) Write a general purpose function that concatenates two given circular doubly lists (This function is explained below). 11 | 2) Now traverse the given tree 12 | ….a) Recursively convert left subtree to a circular DLL. Let the converted list be leftList. 13 | ….a) Recursively convert right subtree to a circular DLL. Let the converted list be rightList. 14 | ….c) Make a circular linked list of root of the tree, make left and right of root to point to itself. 15 | ….d) Concatenate leftList with list of single root node. 16 | ….e) Concatenate the list produced in step above (d) with rightList. 17 | 18 | Note that the above code traverses tree in Postorder fashion. We can traverse in inorder fashion also. We can first concatenate left subtree and root, then recur for right subtree and concatenate the result with left-root concatenation. 19 | 20 | */ 21 | 22 | /* 23 | 24 | How to Concatenate two circular DLLs? 25 | 26 | Get the last node of the left list. Retrieving the last node is an O(1) operation, since the prev pointer of the head points to the last node of the list. 27 | Connect it with the first node of the right list 28 | Get the last node of the second list 29 | Connect it with the head of the list. 30 | */ 31 | 32 | struct NODE 33 | { 34 | struct NODE *left,*right; 35 | int data; 36 | }; 37 | 38 | // append rightlist at the end of leftList 39 | 40 | NODE *concatenate(NODE *leftlist , NODE *rightlist) 41 | { 42 | // if any of the list is empty return the other list 43 | if(leftlist == NULL) 44 | { 45 | return rightlist; 46 | } 47 | if(rightlist == NULL) 48 | { 49 | return leftlist; 50 | } 51 | 52 | // store the last node of left list; 53 | NODE *leftLast = leftlist->left; 54 | // store the last node of the right list; 55 | NODE *rightLast = rightlist->left; 56 | 57 | // connect the last node of the left list with the first node of the right list 58 | leftLast->right = rightlist; 59 | rightlist->left= leftLast; 60 | 61 | // left of the first node points to the last of the rightlist; 62 | leftlist->left=rightLast; 63 | // right nodes last refers to the first of the node list 64 | rightLast->right = leftlist; 65 | 66 | return leftlist; 67 | } 68 | 69 | NODE *binTreelist(NODE *root) 70 | { 71 | if(root == NULL) 72 | { 73 | return NULL; 74 | } 75 | NODE *left = binTreelist(root->left); 76 | NODE *right = binTreelist(root->right); 77 | root->left = root->right = root; 78 | return concatenate(concatenate(left,root),right); 79 | } 80 | 81 | 82 | void displayCirList(NODE *head) 83 | { 84 | cout<<"The circular list in the whole code is"<data<right; 91 | } 92 | while(head!=it); 93 | cout<<"\n"; 94 | } 95 | 96 | NODE *newNode(int data) 97 | { 98 | NODE *temp = new NODE(); 99 | temp->data = data; 100 | temp->left = temp->right = NULL; 101 | return temp; 102 | } 103 | 104 | int main() 105 | { 106 | NODE *root = newNode(4); 107 | root->left = newNode(2); 108 | root->right = newNode(5); 109 | root->left->left = newNode(1); 110 | root->left->right = newNode(3); 111 | root->right->left = newNode(6); 112 | 113 | 114 | NODE *head = binTreelist(root); 115 | displayCirList(head); 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at techous18@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /strings/StringSearch.cpp: -------------------------------------------------------------------------------- 1 | /* Program to search wether a substrings t exists in one string S */ 2 | 3 | #include 4 | typedef long long int ll; 5 | #define vi vector 6 | #define pi pair 7 | #define pb push_back 8 | #define F first 9 | #define S second 10 | #define B begin() 11 | #define E end() 12 | #define mp make_pair 13 | using namespace std; 14 | 15 | 16 | void count_sort(vector &p, vector &c){ 17 | int n =p.size(); 18 | vector cnt(n); 19 | for(auto x: c){ 20 | cnt[x]++; 21 | } 22 | vector p_new(n); 23 | vector pos(n); 24 | pos[0]=0; 25 | for(int i = 1; i < n; i++){ 26 | pos[i] = pos[i-1] + cnt[i-1]; 27 | } 28 | for(auto x : p){ 29 | int i = c[x]; 30 | p_new[pos[i]] = x; 31 | pos[i]++; 32 | } 33 | p = p_new; 34 | 35 | } 36 | 37 | 38 | vector suffixArray(string str, int n){ 39 | str+='$'; 40 | n+=1; 41 | vector >index; 42 | for(int i =0; i < n; i++){ 43 | index.pb(mp(str[i],i)); 44 | } 45 | sort(index.B,index.E); 46 | vector p(n),c(n); 47 | for(int i = 0; i < n; i++) p[i] = index[i].S; 48 | int idx = 0; 49 | c[p[0]] = 0; 50 | for(int i = 1; i < n; i++){ 51 | if(index[i].F == index[i-1].F){ 52 | c[p[i]] = c[p[i-1]]; 53 | } 54 | else{ 55 | c[p[i]] = c[p[i-1]]+1; 56 | } 57 | } 58 | int k = 1, len = 1; 59 | while(len < n){ 60 | for(int i = 0; i < n; i++){ 61 | p[i] = (p[i]- len +n) %n; 62 | } 63 | 64 | count_sort(p,c); 65 | 66 | 67 | vector c_new(n); 68 | c_new[p[0]] = 0; 69 | 70 | for(int i = 1; i < n; i++){ 71 | pair prev = mp(c[p[i-1]], c[(p[i-1]+len)%n]); 72 | pair now = mp(c[p[i]], c[ ( p[i] + len ) % n ]); 73 | if(now == prev){ 74 | c_new[p[i]] = c_new[p[i-1]]; 75 | } 76 | else{ 77 | c_new[p[i]] = c_new[p[i-1]]+1; 78 | } 79 | } 80 | c = c_new; 81 | len*=2; 82 | } 83 | return p; 84 | } 85 | 86 | vector pr; 87 | string str,s; 88 | 89 | 90 | bool searchWord(int start, int end){ 91 | int mid = start + (end- start)/2; 92 | if(end >= start){ 93 | int nstart,nend; 94 | bool sw = true; 95 | for(int i = 0; i < s.size(); i++){ 96 | if(s[i] == str[pr[mid]+i]){ 97 | continue; 98 | } 99 | else{ 100 | if(s[i] > str[pr[mid]+i]){ 101 | nstart = mid+1; 102 | nend = end; 103 | } 104 | else{ 105 | nstart = start; 106 | nend = mid-1; 107 | } 108 | sw = false; 109 | break; 110 | } 111 | } 112 | if(sw){ 113 | return true; 114 | } 115 | else{ 116 | return searchWord(nstart,nend); 117 | } 118 | } 119 | else{ 120 | return false; 121 | } 122 | } 123 | 124 | 125 | int main () 126 | { 127 | ios_base::sync_with_stdio(false); 128 | cin.tie(NULL); 129 | cin>>str; 130 | int n = str.length(); 131 | pr= suffixArray(str,n); 132 | int cas; 133 | cin>>cas; 134 | while(cas--){ 135 | cin>>s; 136 | bool res = searchWord(0,str.size()); 137 | if(res){ 138 | cout<<"Yes\n"; 139 | } 140 | else{ 141 | cout<<"No\n"; 142 | } 143 | } 144 | return 0; 145 | } -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach4.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach4 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | private int size; //size of the linked list 55 | private int[] hash; //hashtable for the linked list 56 | 57 | //constructor for linked list 58 | public LinkedList() 59 | { 60 | head=null; 61 | size=0; 62 | hash = new int[10]; 63 | } 64 | 65 | /** 66 | * insert_at_head() 67 | * it will insert node at the head of the linked list 68 | * @param data 69 | **/ 70 | public void insert_at_head(int data) 71 | { 72 | Node newNode = new Node(data); 73 | if(head==null) 74 | { 75 | head=newNode; 76 | hash[size]=newNode.getData(); 77 | } 78 | else 79 | { 80 | newNode.setNext(head); 81 | head=newNode; 82 | hash[size]=newNode.getData(); 83 | } 84 | size++; 85 | } 86 | 87 | /** 88 | * print_list() 89 | * it will print the linked list 90 | **/ 91 | public void printList() 92 | { 93 | if(head==null) 94 | { 95 | System.out.println("NULL"); 96 | } 97 | else 98 | { 99 | Node current=head; 100 | while(current!=null) 101 | { 102 | System.out.print(current.getData() +" -> "); 103 | current=current.getNext(); 104 | } 105 | System.out.println("NULL"); 106 | } 107 | } 108 | 109 | /*====================================================================*/ 110 | /** 111 | * APPROACH 4 112 | * Using hashtables while adding elements in linked list 113 | * Then we get the size 114 | * find index of hashtable by subtracting the nthnode from size 115 | * print node at index from hashtable 116 | **/ 117 | public void printNthNodeFromLast(int num) 118 | { 119 | if(num>size) 120 | { 121 | System.out.println("INDEX OUT OF BOUNDS"); 122 | return; 123 | } 124 | System.out.println(hash[num-1]); 125 | } 126 | /*====================================================================*/ 127 | } 128 | 129 | public static void main(String[] args) 130 | { 131 | LinkedList ll = new LinkedList(); 132 | ll.insert_at_head(3); 133 | ll.insert_at_head(1); 134 | ll.insert_at_head(4); 135 | ll.insert_at_head(2); 136 | ll.insert_at_head(5); 137 | 138 | ll.printList(); 139 | 140 | Scanner in = new Scanner(System.in); 141 | System.out.println("Enter the nth node from last"); 142 | int n = in.nextInt(); 143 | 144 | ll.printNthNodeFromLast(n); 145 | in.close(); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach3 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | 55 | //constructor for linked list 56 | public LinkedList() 57 | { 58 | head=null; 59 | } 60 | 61 | /** 62 | * insert_at_head() 63 | * it will insert node at the head of the linked list 64 | * @param data 65 | **/ 66 | public void insert_at_head(int data) 67 | { 68 | Node newNode = new Node(data); 69 | if(head==null) 70 | { 71 | head=newNode; 72 | } 73 | else 74 | { 75 | newNode.setNext(head); 76 | head=newNode; 77 | } 78 | } 79 | 80 | /** 81 | * print_list() 82 | * it will print the linked list 83 | **/ 84 | public void printList() 85 | { 86 | if(head==null) 87 | { 88 | System.out.println("NULL"); 89 | } 90 | else 91 | { 92 | Node current=head; 93 | while(current!=null) 94 | { 95 | System.out.print(current.getData() +" -> "); 96 | current=current.getNext(); 97 | } 98 | System.out.println("NULL"); 99 | } 100 | } 101 | 102 | /*====================================================================*/ 103 | /** 104 | * APPROACH 3 105 | * Using hashtable 106 | * traverse the list and make hashtable 107 | * we will get the size of the list 108 | * we will calculate nth node from hashtable by substracting the nthnode from size 109 | **/ 110 | public void printNthNodeFromLast(int num) 111 | { 112 | int[] hash = new int[10]; //hashtable 113 | int size=0; 114 | Node current=head; 115 | 116 | while(current!=null) //traversing and making hashtable 117 | { 118 | hash[size]=current.getData(); 119 | current=current.getNext(); 120 | size++; 121 | } 122 | if(num>size) 123 | { 124 | System.out.println("INDEX OUT OF BOUNDS"); 125 | return; 126 | } 127 | System.out.println(hash[size-num]); 128 | } 129 | /*====================================================================*/ 130 | } 131 | 132 | public static void main(String[] args) 133 | { 134 | LinkedList ll = new LinkedList(); 135 | ll.insert_at_head(3); 136 | ll.insert_at_head(1); 137 | ll.insert_at_head(4); 138 | ll.insert_at_head(2); 139 | ll.insert_at_head(5); 140 | 141 | ll.printList(); 142 | 143 | Scanner in = new Scanner(System.in); 144 | System.out.println("Enter the nth node from last"); 145 | int n = in.nextInt(); 146 | 147 | ll.printNthNodeFromLast(n); 148 | in.close(); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach1 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | private int size; //size of the linked list 55 | 56 | //constructor for linked list 57 | public LinkedList() 58 | { 59 | head=null; 60 | size=0; 61 | } 62 | 63 | /** 64 | * insert_at_head() 65 | * it will insert node at the head of the linked list 66 | * @param data 67 | **/ 68 | public void insert_at_head(int data) 69 | { 70 | Node newNode = new Node(data); 71 | if(head==null) 72 | { 73 | head=newNode; 74 | } 75 | else 76 | { 77 | newNode.setNext(head); 78 | head=newNode; 79 | } 80 | size++; 81 | } 82 | 83 | /** 84 | * print_list() 85 | * it will print the linked list 86 | **/ 87 | public void printList() 88 | { 89 | if(head==null) 90 | { 91 | System.out.println("NULL"); 92 | } 93 | else 94 | { 95 | Node current=head; 96 | while(current!=null) 97 | { 98 | System.out.print(current.getData() +" -> "); 99 | current=current.getNext(); 100 | } 101 | System.out.println("NULL"); 102 | } 103 | } 104 | 105 | /*====================================================================*/ 106 | /** APPROACH 1 107 | * Compute the size while adding 108 | * find the starting node by substracting nthnode from size 109 | * find the starting node by traversing 110 | **/ 111 | public void printNthNodeFromLast(int num) 112 | { 113 | if(num>size) 114 | { 115 | System.out.println("INDEX OUT OF BOUNDS"); 116 | return; 117 | } 118 | int start = size-num; 119 | int i=0; 120 | Node current=head; 121 | while(current!=null) 122 | { 123 | if(start==i) 124 | { 125 | System.out.println(current.getData()); 126 | break; 127 | } 128 | current=current.getNext(); 129 | i++; 130 | } 131 | } 132 | /*====================================================================*/ 133 | } 134 | 135 | public static void main(String[] args) 136 | { 137 | LinkedList ll = new LinkedList(); 138 | ll.insert_at_head(3); 139 | ll.insert_at_head(1); 140 | ll.insert_at_head(4); 141 | ll.insert_at_head(2); 142 | ll.insert_at_head(5); 143 | 144 | ll.printList(); 145 | 146 | Scanner in = new Scanner(System.in); 147 | System.out.println("Enter the nth node from last"); 148 | int n = in.nextInt(); 149 | 150 | ll.printNthNodeFromLast(n); 151 | in.close(); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach6.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach6 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | private int size; //size of the linked list 55 | private int counter; 56 | 57 | //constructor for linked list 58 | public LinkedList() 59 | { 60 | head=null; 61 | size=0; 62 | counter=0; 63 | } 64 | 65 | /** 66 | * getHead() 67 | * @return the head node 68 | **/ 69 | public Node getHead() 70 | { 71 | return head; 72 | } 73 | 74 | /** 75 | * insert_at_head() 76 | * it will insert node at the head of the linked list 77 | * @param data 78 | **/ 79 | public void insert_at_head(int data) 80 | { 81 | Node newNode = new Node(data); 82 | if(head==null) 83 | { 84 | head=newNode; 85 | } 86 | else 87 | { 88 | newNode.setNext(head); 89 | head=newNode; 90 | } 91 | size++; 92 | } 93 | 94 | /** 95 | * print_list() 96 | * it will print the linked list 97 | **/ 98 | public void printList() 99 | { 100 | if(head==null) 101 | { 102 | System.out.println("NULL"); 103 | } 104 | else 105 | { 106 | Node current=head; 107 | while(current!=null) 108 | { 109 | System.out.print(current.getData() +" -> "); 110 | current=current.getNext(); 111 | } 112 | System.out.println("NULL"); 113 | } 114 | } 115 | 116 | /*====================================================================*/ 117 | /** 118 | * APPROACH 6 119 | * using recursion 120 | * in backtracking count the nodes 121 | * count equal to nthnode will be printed 122 | **/ 123 | public void printNthNodeFromLast(Node current,int num) 124 | { 125 | if(num>size) 126 | { 127 | System.out.println("OUT OF BOUND"); 128 | return; 129 | } 130 | if(current==null) 131 | { 132 | return; 133 | } 134 | printNthNodeFromLast(current.getNext(),num); 135 | counter++; 136 | if(counter==num) 137 | { 138 | System.out.println(current.getData()); 139 | return; 140 | } 141 | } 142 | /*====================================================================*/ 143 | } 144 | 145 | public static void main(String[] args) 146 | { 147 | LinkedList ll = new LinkedList(); 148 | ll.insert_at_head(3); 149 | ll.insert_at_head(1); 150 | ll.insert_at_head(4); 151 | ll.insert_at_head(2); 152 | ll.insert_at_head(5); 153 | ll.printList(); 154 | 155 | Scanner in = new Scanner(System.in); 156 | System.out.println("Enter the nth node from last"); 157 | int n = in.nextInt(); 158 | 159 | ll.printNthNodeFromLast(ll.getHead(), n); 160 | in.close(); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach5.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach5 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | 55 | //constructor for linked list 56 | public LinkedList() 57 | { 58 | head=null; 59 | } 60 | 61 | /** 62 | * insert_at_head() 63 | * it will insert node at the head of the linked list 64 | * @param data 65 | **/ 66 | public void insert_at_head(int data) 67 | { 68 | Node newNode = new Node(data); 69 | if(head==null) 70 | { 71 | head=newNode; 72 | } 73 | else 74 | { 75 | newNode.setNext(head); 76 | head=newNode; 77 | } 78 | } 79 | 80 | /** 81 | * print_list() 82 | * it will print the linked list 83 | **/ 84 | public void printList() 85 | { 86 | if(head==null) 87 | { 88 | System.out.println("NULL"); 89 | } 90 | else 91 | { 92 | Node current=head; 93 | while(current!=null) 94 | { 95 | System.out.print(current.getData() +" -> "); 96 | current=current.getNext(); 97 | } 98 | System.out.println("NULL"); 99 | } 100 | } 101 | 102 | /*====================================================================*/ 103 | /** 104 | * APPROACH 5 105 | * Finding in one scan of linked list 106 | * take current pointer set to head 107 | * traverse upto the nth node 108 | * take current2 set it to null 109 | * traverse current again upto null 110 | * move current2 also 111 | * when current is fully traversed current2 node will be printed 112 | **/ 113 | public void printNthNodeFromLast(int num) 114 | { 115 | Node current=head; 116 | int i=0; 117 | while(current!=null) //first traversed half upto nth node 118 | { 119 | if(num-1==i) 120 | { 121 | break; 122 | } 123 | i++; 124 | current=current.getNext(); 125 | } 126 | Node last=null; 127 | while(current!=null) //traversed upto end 128 | { 129 | if(last==null) 130 | { 131 | last=head; 132 | } 133 | else 134 | { 135 | last=last.getNext(); 136 | } 137 | current=current.getNext(); 138 | } 139 | System.out.println(last.getData()); 140 | } 141 | /*====================================================================*/ 142 | } 143 | 144 | public static void main(String[] args) 145 | { 146 | LinkedList ll = new LinkedList(); 147 | ll.insert_at_head(3); 148 | ll.insert_at_head(1); 149 | ll.insert_at_head(4); 150 | ll.insert_at_head(2); 151 | ll.insert_at_head(5); 152 | 153 | ll.printList(); 154 | 155 | Scanner in = new Scanner(System.in); 156 | System.out.println("Enter the nth node from last"); 157 | int n = in.nextInt(); 158 | 159 | ll.printNthNodeFromLast(n); 160 | in.close(); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /lists/misc/nth_node_from_end/Approach2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | abstract class Approach2 3 | { 4 | /** 5 | * LINKED LIST CLASS 6 | **/ 7 | private static class LinkedList 8 | { 9 | /** 10 | * NODE CLASS 11 | * for linked list node 12 | **/ 13 | private class Node 14 | { 15 | private int data; 16 | private Node next; 17 | 18 | //constructor 19 | public Node(int data) 20 | { 21 | this.data=data; 22 | next=null; 23 | } 24 | 25 | /** 26 | * getData() 27 | * @return data in the node 28 | **/ 29 | public int getData() 30 | { 31 | return data; 32 | } 33 | 34 | /** 35 | * getNext() 36 | * @return the next node 37 | **/ 38 | public Node getNext() 39 | { 40 | return next; 41 | } 42 | 43 | /** 44 | * setNext() 45 | * @param next 46 | **/ 47 | public void setNext(Node next) 48 | { 49 | this.next=next; 50 | } 51 | } 52 | 53 | private Node head; //head of the linked list 54 | 55 | //constructor for linked list 56 | public LinkedList() 57 | { 58 | head=null; 59 | } 60 | 61 | /** 62 | * insert_at_head() 63 | * it will insert node at the head of the linked list 64 | * @param data 65 | **/ 66 | public void insert_at_head(int data) 67 | { 68 | Node newNode = new Node(data); 69 | if(head==null) 70 | { 71 | head=newNode; 72 | } 73 | else 74 | { 75 | newNode.setNext(head); 76 | head=newNode; 77 | } 78 | } 79 | 80 | /** 81 | * print_list() 82 | * it will print the linked list 83 | **/ 84 | public void printList() 85 | { 86 | if(head==null) 87 | { 88 | System.out.println("NULL"); 89 | } 90 | else 91 | { 92 | Node current=head; 93 | while(current!=null) 94 | { 95 | System.out.print(current.getData() +" -> "); 96 | current=current.getNext(); 97 | } 98 | System.out.println("NULL"); 99 | } 100 | } 101 | 102 | /*====================================================================*/ 103 | /** 104 | * APPROACH 2 105 | * Using two current pointers 106 | * Find the remaining nodes from right on every node 107 | * Find the count of remaining nodes 108 | * if count is equal to the nth node to be founded then print that node 109 | * if count is less than the nth node return 110 | * if count is grater than the nth node then move current forward 111 | **/ 112 | public void printNthNodeFromLast(int num) 113 | { 114 | Node current=head; 115 | while(current!=null) 116 | { 117 | int count=0; //count of remaining node 118 | Node current2=current; 119 | while(current2!=null) 120 | { 121 | count++; 122 | current2=current2.getNext(); 123 | } 124 | 125 | if(count==num) 126 | { 127 | System.out.println(current.getData()); 128 | return; 129 | } 130 | else if(countnum) 136 | { 137 | current=current.getNext(); 138 | } 139 | } 140 | } 141 | /*====================================================================*/ 142 | } 143 | 144 | public static void main(String[] args) 145 | { 146 | LinkedList ll = new LinkedList(); 147 | ll.insert_at_head(3); 148 | ll.insert_at_head(1); 149 | ll.insert_at_head(4); 150 | ll.insert_at_head(2); 151 | ll.insert_at_head(5); 152 | 153 | ll.printList(); 154 | 155 | Scanner in = new Scanner(System.in); 156 | System.out.println("Enter the nth node from last"); 157 | int n = in.nextInt(); 158 | 159 | ll.printNthNodeFromLast(n); 160 | in.close(); 161 | } 162 | } 163 | --------------------------------------------------------------------------------