├── .directory ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── _config.yml ├── _layouts └── default.html ├── bash ├── System.txt ├── autoIncrement.sh ├── changeContentInFile.sh ├── pathDisplay.sh ├── soundDisable.sh └── startandstop.sh ├── c ├── RainProbability.c ├── isFibonacci.c ├── nthroot.c ├── pointdistance.c ├── printfactors.c ├── slope.c ├── sumOfseries.c └── sumofprimedivisors.c ├── cpp └── Recursion │ └── FloodFillAlgo.cpp ├── java ├── CircularLinkedLists │ ├── BinaryTreeConversion.java │ ├── Deque.java │ ├── SortedInsert.java │ └── SplitToTwo.java ├── DoublyLinkedLists │ ├── DeleteNode.java │ ├── ReverseLL.java │ ├── createDLLfromTernaryTree.java │ ├── intro.java │ ├── mergesort.java │ ├── sortandinsert.cpp │ └── swapknode.java ├── LinkedLists │ ├── DeleteElementKey.java │ ├── DeleteElementPosition.java │ ├── DetectLoop.java │ ├── Implentation.java │ ├── MergeLists.java │ ├── MiddleElement.java │ ├── RemoveDuplicates.java │ ├── Reverse.java │ ├── SwapNodesWithoutSwappingData.java │ └── UnionAndIntersection.java ├── Matrix │ ├── Spiralmatrix.java │ ├── diffOfSumOfDiagonals.java │ ├── interchangeFirstAndLastRow.java │ ├── isSymmetric.java │ ├── rotateMatrix.java │ ├── sortmatrix.java │ └── zigzag.java ├── MiscellaneousProblems │ ├── maxequation.java │ ├── nDigitPalindrome.java │ └── powerGame.java ├── Recursion │ ├── countpaths.java │ ├── josephus.java │ ├── specialkeyboard.java │ └── wateroverflow.java ├── arrays │ ├── AlternatePrimes.java │ ├── HighestPossibleSum.java │ ├── arithmeticProgression.java │ ├── maxLengthOf0and1.java │ ├── seperate0and1s.java │ └── splitArrayWithEqualSums.java ├── search │ ├── BinarySearch.java │ ├── RotatedBinarySearch.java │ └── TernarySearch.java ├── sort │ ├── BubbleSort.java │ ├── InsertSort.class │ ├── InsertSort.java │ ├── MergeSort.java │ ├── QuickSort.java │ ├── README.md │ └── SelectionSort.java └── strings │ ├── Anagram.java │ ├── HighestPalindrome.java │ ├── NextHighestPermutation.java │ ├── PalindroneStrings.java │ ├── RegularExpression.java │ ├── RemoveDuplicates.java │ ├── RemoveWhiteSpaces.java │ ├── ReverseString.java │ ├── StringMultiplication.java │ ├── StringSegmentation.java │ ├── SubstringSmallestWindow.java │ └── countAnagrams.java ├── javascript ├── DataStructures │ ├── Arrays │ │ ├── LargestNumberFormedByAnArray.js │ │ ├── LargestSubArrayWith0and1s.js │ │ ├── MissingNumber.js │ │ ├── SortByFrequency.js │ │ ├── SubArraysWithGivenSum.js │ │ ├── buy-and-sell-stock.js │ │ ├── is-valid-sudoku.js │ │ ├── kadaneAlgorithm.js │ │ ├── plusOne.js │ │ ├── rotate-array.js │ │ ├── rotate-image.js │ │ └── subsets.js │ ├── Graphs │ │ ├── BFS.js │ │ ├── DFS.js │ │ └── index.js │ └── LinkedList │ │ ├── DetectLoop.js │ │ ├── ImplementQueue.js │ │ ├── ImplementStack.js │ │ ├── MergeLinkedList.js │ │ ├── MiddleElement.js │ │ ├── Palindrome.js │ │ ├── ReverseLinkedList.js │ │ └── RotateLinkedList.js ├── GreedyAlgorithms │ ├── GreedyKnapsack.js │ └── README.md ├── numbers │ └── hammingDistance.js ├── search │ ├── BinarySearch.js │ ├── BinarySearchTree.js │ └── README.md ├── sort │ ├── BubbleSort.js │ ├── InsertionSort.js │ ├── MergeSort.js │ ├── QuickSort.js │ ├── README.md │ └── SelectionSort.js └── strings │ ├── Palindrome.js │ └── attendance.js └── python ├── power.py ├── queues ├── FIFOpageReplacement.py ├── ImplementationUsingLists.py ├── InterleavingElements.py └── LinkedListImplementation.py └── stacks ├── GeneralImplementation.py ├── InfixToPostfix.py ├── PostfixEvaluation.py ├── StacksUsingArrays.py ├── StringReversalUsingStacks.py └── infixToPostfixProblem.py /.directory: -------------------------------------------------------------------------------- 1 | [Dolphin] 2 | Timestamp=2018,8,9,21,21,54 3 | Version=4 4 | 5 | [Settings] 6 | HiddenFilesShown=true 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .directory 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | ### Thanks, for considering to contribute to this repository! 4 | You can contribute to this repository by either solving an issue or suggesting improvements/changes in the code. 5 | 6 | When contributing to this repository, please first discuss the change you wish to make via issue or any other method with the owners of this repository before making a change. 7 | 8 | To start contributing, follow the steps below 9 | - Fork the repo 10 | - Clone the repo 11 | - Create a branch using `git checkout -b feature-branch` 12 | - Make the required changes 13 | - Create a pull request using below commands 14 | - `git add --all` 15 | - `git commit -m "your commit message"` 16 | - `git push origin feature-branch` 17 | - Go to [Repository](https://github.com/AdithyaBhat17/interview-cookbook) 18 | - Create Pull Request against `master` branch 19 | - Add a suitable title and description to the pull request and tag the issue number in Pull Request description, if the pull request is related to some issue logged here: [Issues](https://github.com/AdithyaBhat17/interview-cookbook/issues) 20 | - You're done. Wait for your code to get reviewed and merged. 21 | - Optional: Give us a :star: if you like our work. 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | Version 2, December 2004 3 | 4 | Copyright (C) 2018 Adithya NR 5 | 6 | Everyone is permitted to copy and distribute verbatim or modified 7 | copies of this license document, and changing it is allowed as long 8 | as the name is changed. 9 | 10 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | 13 | 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | title: Interview CookBook 2 | name: Adithya NR 3 | email: adithyabhat17.ab@gmail.com 4 | description: This website will house several code snippets and useful resources for Data Structures, Algorithms and Object-Oriented Concepts. 5 | 6 | theme: jekyll-theme-cayman 7 | 8 | display_footer: none 9 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {% seo %} 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 26 | 27 |
28 | {{ content }} 29 | 30 | 36 |
37 | 38 | {% if site.google_analytics %} 39 | 47 | {% endif %} 48 | 49 | 50 | -------------------------------------------------------------------------------- /bash/System.txt: -------------------------------------------------------------------------------- 1 | # Write steps to execute a script as soon as system starts. 2 | 3 | Follow these steps. 4 | 5 | 1. Go to /etc/init.d 6 | 2. Add a file( say example ) and place the script you want to execute in that. 7 | 3. chmod +x /etc/init.d/example. (permissions) 8 | 4. Add # chkconfig: 345 99 10 inside your script 9 | 5. Save it 10 | 6. Start the service with — service example start. 11 | 12 | This should work as system service/ startup service 13 | -------------------------------------------------------------------------------- /bash/autoIncrement.sh: -------------------------------------------------------------------------------- 1 | # Write a script to Auto Increment variable in bash 2 | 3 | 4 | # This program increments the variable in it as soon as the program is executed. 5 | 6 | n=3;#the variable that I want to be incremented 7 | next_n=$(($n+1)) 8 | sudo sed -i "/#the variable that I want to be incremented$/s/=.*#/=$next_n;#/" ${0} 9 | echo $n 10 | 11 | 12 | #There should be no space between the variable and the comment 13 | #This is how bash will identify which varible to update 14 | -------------------------------------------------------------------------------- /bash/changeContentInFile.sh: -------------------------------------------------------------------------------- 1 | # Edit a line with specific pattern in shell script. 2 | 3 | sed -i '/pattern/c\ new_line' filename 4 | 5 | #Suppose you need to change a field like Auth to NO in file example.txt, you can use this 6 | 7 | sed -i 'Auth/c\ Auth=NO' example.txt 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /bash/pathDisplay.sh: -------------------------------------------------------------------------------- 1 | # Write a code to display path of executable file in Linux? 2 | 3 | 4 | which your_executable 5 | 6 | #For example 'which ls' 7 | -------------------------------------------------------------------------------- /bash/soundDisable.sh: -------------------------------------------------------------------------------- 1 | #How to disable sound on Linux systems? 2 | 3 | sudo apt-get remove --purge alsa 4 | 5 | #alsa stands for Advanced Linux Sound Architecture 6 | -------------------------------------------------------------------------------- /bash/startandstop.sh: -------------------------------------------------------------------------------- 1 | #Write a script to shut down reboot from a terminal? 2 | 3 | #For shutdown 4 | sudo poweroff 5 | 6 | #For restart 7 | sudo reboot 8 | -------------------------------------------------------------------------------- /c/RainProbability.c: -------------------------------------------------------------------------------- 1 | // Find the probability of rain on (n+1)th day given an array which shows the data for rain of the previous n days. 2 | 3 | #include 4 | 5 | float rainProbability(int a[],int n){ 6 | float count = 0, m; 7 | for(int i=0;i 6 | #include 7 | #include // importing boolean 8 | 9 | bool isPerfectSquare(int x){ 10 | int s = sqrt(x); 11 | if(s*s == x) 12 | return true; 13 | return false; 14 | } 15 | 16 | bool isFibonacci(int n){ 17 | if(isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4) == true) 18 | return true; 19 | return false; 20 | } 21 | 22 | void main(){ 23 | int number; 24 | scanf("%d",&number); 25 | if(isFibonacci(number) == true) 26 | printf("the number %d is a Fibonacci number",number); 27 | else 28 | printf("the number %d is not a Fibonacci number",number); 29 | } 30 | -------------------------------------------------------------------------------- /c/nthroot.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | double root1(int,int); 5 | 6 | int main(){ 7 | int n; 8 | int x; 9 | double root; 10 | printf("Enter a number greater than 1: \n"); 11 | scanf("%d",&x); 12 | if(x>1){ 13 | printf("Enter the value for 'n'(the root to be calculated): \n"); 14 | scanf("%d",&n); 15 | root = root1(x,n); 16 | printf("%d st/th/rd Root of %d is %f\n\n", n,x,root); 17 | } 18 | else 19 | printf("try again *_*"); 20 | return 0; 21 | } 22 | 23 | double root1(int a, int b){ 24 | int j; 25 | double i,k=1; 26 | double increment = 0.01; 27 | for(i=1; i<=a; i+=increment){ 28 | for(j=0;j ax + by + cz + d = 0 4 | // point => (x1,y1,z1) 5 | // Distance = (|ax1 + by1 + cz1 + d|)/sqrt(a^2 + b^2 + c^2) 6 | 7 | #include 8 | #include 9 | #include // for abs. 10 | 11 | void shortestPath(int x1, int y1, int z1, int a, int b, int c, int d){ 12 | d = abs(a*x1 + b*y1 + c*z1 + d); 13 | int e = sqrt(a*a + b*b + c*c); 14 | printf("shortest path is %f",d/e); 15 | } 16 | 17 | void main(){ 18 | int x1,y1,z1,a,b,c,d; 19 | scanf("%d%d%d",&x1,&y1,&z1); //point. 20 | scanf("%d%d%d%d",&a,&b,&c,&d); //co-efficients of the plane. 21 | shortestPath(x1,y1,z1,a,b,c,d); 22 | } -------------------------------------------------------------------------------- /c/printfactors.c: -------------------------------------------------------------------------------- 1 | // Print factors of a given number N in pairs 2 | 3 | #include 4 | 5 | void printFactors(int N){ 6 | for(int i=1;i*i<=N;i++) 7 | if(N % i == 0) 8 | printf("%d * %d\n",i,(N/i)); 9 | } 10 | 11 | int main(){ 12 | int number = 24; 13 | printFactors(number); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /c/slope.c: -------------------------------------------------------------------------------- 1 | // Given a number n,find the slope of the given number. 2 | 3 | // Note : slope of a number is the number of minima and maxima digits. 4 | // A digit is called a minima if the digit is lesser than the digit before and after it. 5 | // Similarly a digit is called a maxima if the digit is greater than the digit before and after it. 6 | 7 | #include 8 | #include 9 | 10 | int slopeOfNumber(char* number ,int n){ 11 | int slope = 0; 12 | // loop from the second digit till the last second digit. 13 | for(int i=1;i number[i-1] && number[i] > number[i+1]) //finding the maxima 15 | slope++; 16 | else if(number[i] < number[i-1] && number[i] < number[i+1]) //finding minima 17 | slope++; 18 | return slope; 19 | } 20 | 21 | // Driver code 22 | int main(){ 23 | char* number = "1213321"; 24 | int n = strlen(number); 25 | printf("slope of %s is %d",number,slopeOfNumber(number , n)); 26 | return 0; 27 | } 28 | 29 | // slope of 1213321 is 2 30 | // slope of 273299302236131 is 6 31 | 32 | -------------------------------------------------------------------------------- /c/sumOfseries.c: -------------------------------------------------------------------------------- 1 | // Find the sum of series whose 'i'th term is i^k - (i-1)^k 2 | 3 | #include 4 | #define MOD 1000000007 5 | 6 | int sumOfseries(int n, int k){ 7 | long result = 1; 8 | for(int i=0;i 4 | #include 5 | 6 | bool isPrime(int n){ 7 | if(n <= 1) return false; 8 | if(n <= 3) return true; 9 | if(n % 2 == 0 || n % 3 == 0) 10 | return false; 11 | for(int i=5;i*i<=n;i+=6) 12 | if(n%i == 0 || n%(i+2) == 0) 13 | return false; 14 | return true; 15 | } 16 | 17 | int sumOfPrimeDivisors(int n){ 18 | int sum = 0; 19 | for(int i=1;i<=n;i++) 20 | if(n % i == 0){ 21 | if(isPrime(i)) 22 | sum += i; 23 | } 24 | return sum; 25 | } 26 | 27 | int main(){ 28 | int n; 29 | scanf("%d",&n); //enter N 30 | printf("%d",sumOfPrimeDivisors(n)); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /java/CircularLinkedLists/SortedInsert.java: -------------------------------------------------------------------------------- 1 | // Sorted insert for circular linked list 2 | 3 | // Algorithm: 4 | // Allocate memory for the newly inserted node and put data in the newly allocated node. 5 | // Let the pointer to the new node be new_node. After memory allocation, 6 | // following are the three cases that need to be handled. 7 | 8 | // 1) Linked List is empty: 9 | // a) since node is the only node in CLL, make a self loop. 10 | // node->next = node; 11 | // b) change the head pointer to point to new node. 12 | // head = node; 13 | // 2) New node is to be inserted just before the head node: 14 | // (a) Find out the last node using a loop. 15 | // while(current.next != head) 16 | // current = current.next; 17 | // (b) Change the next of last node. 18 | // current.next = node; 19 | // (c) Change next of new node to point to head. 20 | // node.next = head; 21 | // (d) change the head pointer to point to new node. 22 | // head = node; 23 | // 3) New node is to be inserted somewhere after the head: 24 | // (a) Locate the node after which new node is to be inserted. 25 | // while ( current.next!= head && 26 | // current.next.data < node.data) 27 | // { current = current.next; } 28 | // (b) Make next of node as next of the located pointer 29 | // node.next = current.next; 30 | // (c) Change the next of the located pointer 31 | // current.next = node; 32 | 33 | class Node{ 34 | int data; 35 | Node next; 36 | Node(int d){ 37 | data = d; 38 | next = null; 39 | } 40 | } 41 | 42 | class CircularLinkedList{ 43 | Node head; 44 | CircularLinkedList(){ 45 | head = null; 46 | } 47 | 48 | public void sortAndInsert(Node node){ 49 | Node current = head; 50 | if(current == null){ // step 1. 51 | node.next = node; 52 | head = node; 53 | } 54 | else if(node.data < current.data){ // step 2. 55 | /* If value is smaller than head's value then 56 | we need to change next of last node */ 57 | while(current.next != head) 58 | current = current.next; 59 | current.next = node; 60 | node.next = head; 61 | head = node; 62 | } 63 | else{ //step 3. 64 | while(current.next != head && node.data >= current.data) 65 | current = current.next; 66 | node.next = current.next; 67 | current.next = node; 68 | } 69 | } 70 | 71 | public void print(){ 72 | if(head != null){ 73 | Node node = head; 74 | do{ 75 | System.out.print(node.data + "->"); 76 | node = node.next; 77 | }while(node != head); 78 | } 79 | System.out.println("null"); 80 | } 81 | 82 | public static void main(String args[]){ 83 | CircularLinkedList c = new CircularLinkedList(); 84 | int array[] = new int[] {12,23,24,5,67,34}; 85 | Node temp = null; //empty CircularLinkedList 86 | for(int i=0;inext becomes head and for even nodes 33 | hare->next->next becomes head */ 34 | while(hare.next != head && hare.next.next != head){ 35 | hare = hare.next.next; 36 | tortoise = tortoise.next; 37 | } 38 | /* If there are even elements in list then move hare */ 39 | while(hare.next.next == head) 40 | hare = hare.next; 41 | 42 | /* Set the head pointer of first half */ 43 | headA = head; 44 | /* Set the head pointer of second half */ 45 | if (head.next != head) { 46 | headB = tortoise.next; 47 | } 48 | /* Make second half circular */ 49 | hare.next = tortoise.next; 50 | 51 | /* Make first half circular */ 52 | tortoise.next = head; 53 | } 54 | 55 | void print(Node node) { 56 | Node temp = node; 57 | if (node != null) { 58 | do { 59 | System.out.print(temp.data + " "); 60 | temp = temp.next; 61 | } while (temp != node); 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | CircularLinkedList c = new CircularLinkedList(); 67 | 68 | //Created linked list will be 12->56->2->11 69 | c.head = new Node(12); 70 | c.head.next = new Node(56); 71 | c.head.next.next = new Node(2); 72 | c.head.next.next.next = new Node(11); 73 | c.head.next.next.next.next = c.head; 74 | 75 | System.out.println("Original Circular Linked list "); 76 | c.print(head); 77 | 78 | // Split the list 79 | c.splitList(); 80 | System.out.println(""); 81 | System.out.println("First Circular List "); 82 | c.print(headA); 83 | System.out.println(""); 84 | System.out.println("Second Circular List "); 85 | c.print(headB); 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /java/DoublyLinkedLists/DeleteNode.java: -------------------------------------------------------------------------------- 1 | // Write a function to delete a given node in a doubly linked list. 2 | 3 | class LinkedList { 4 | static Node head = null; 5 | class Node { 6 | int data; 7 | Node next, prev; 8 | Node(int d) { 9 | data = d; 10 | next = prev = null; 11 | } 12 | } 13 | 14 | /*Function to delete a node in a Doubly Linked List. 15 | head_ref --> pointer to head node pointer. 16 | del --> pointer to node to be deleted. */ 17 | void deleteNode(Node head_ref, Node del) { 18 | /* base case */ 19 | if (head == null || del == null) { 20 | return; 21 | } 22 | /* If node to be deleted is head node */ 23 | if (head == del) { 24 | head = del.next; 25 | } 26 | /* Change next only if node to be deleted is NOT the last node */ 27 | if (del.next != null) { 28 | del.next.prev = del.prev; 29 | } 30 | /* Change prev only if node to be deleted is NOT the first node */ 31 | if (del.prev != null) { 32 | del.prev.next = del.next; 33 | } 34 | /* Finally, free the memory occupied by del*/ 35 | return; 36 | } 37 | 38 | /* Function to insert a node at the beginning of the Doubly Linked List */ 39 | void push(Node head_ref, int new_data) { 40 | /* allocate node */ 41 | Node new_node = new Node(new_data); 42 | /* since we are adding at the begining, 43 | prev is always NULL */ 44 | new_node.prev = null; 45 | /* link the old list off the new node */ 46 | new_node.next = (head); 47 | /* change prev of head node to new node */ 48 | if ((head) != null) { 49 | (head).prev = new_node; 50 | } 51 | /* move the head to point to the new node */ 52 | (head) = new_node; 53 | } 54 | 55 | void printList(Node node) { 56 | while (node != null) { 57 | System.out.print(node.data + " "); 58 | node = node.next; 59 | } 60 | } 61 | 62 | public static void main(String[] args) { 63 | LinkedList list = new LinkedList(); 64 | /* Let us create the doubly linked list 10<->8<->4<->2 */ 65 | list.push(head, 2); 66 | list.push(head, 4); 67 | list.push(head, 8); 68 | list.push(head, 10); 69 | System.out.println("Original Linked list "); 70 | list.printList(head); 71 | 72 | /* delete nodes from the doubly linked list */ 73 | list.deleteNode(head, head); /*delete first node*/ 74 | 75 | list.deleteNode(head, head.next); /*delete middle node*/ 76 | 77 | list.deleteNode(head, head.next); /*delete last node*/ 78 | System.out.println(""); 79 | 80 | /* Modified linked list will be NULL<-8->NULL */ 81 | System.out.println("Modified Linked List"); 82 | list.printList(head); 83 | } 84 | } -------------------------------------------------------------------------------- /java/DoublyLinkedLists/ReverseLL.java: -------------------------------------------------------------------------------- 1 | class LinkedList { 2 | static Node head; 3 | static class Node { 4 | int data; 5 | Node next, prev; 6 | Node(int d) { 7 | data = d; 8 | next = prev = null; 9 | } 10 | } 11 | /* Function to reverse a Doubly Linked List */ 12 | void reverse() { 13 | Node temp = null; 14 | Node current = head; 15 | /* swap next and prev for all nodes of 16 | doubly linked list */ 17 | while (current != null) { 18 | temp = current.prev; 19 | current.prev = current.next; 20 | current.next = temp; 21 | current = current.prev; 22 | } 23 | /* Before changing head, check for the cases like empty 24 | list and list with only one node */ 25 | if (temp != null) { 26 | head = temp.prev; 27 | } 28 | } 29 | /* Function to insert a node at the beginging of the Doubly Linked List */ 30 | void push(int new_data) { 31 | /* allocate node */ 32 | Node new_node = new Node(new_data); 33 | /* since we are adding at the begining, 34 | prev is always NULL */ 35 | new_node.prev = null; 36 | /* link the old list off the new node */ 37 | new_node.next = head; 38 | /* change prev of head node to new node */ 39 | if (head != null) { 40 | head.prev = new_node; 41 | } 42 | /* move the head to point to the new node */ 43 | head = new_node; 44 | } 45 | void printList(Node node) { 46 | while (node != null) { 47 | System.out.print(node.data + " "); 48 | node = node.next; 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | LinkedList list = new LinkedList(); 54 | list.push(2); 55 | list.push(4); 56 | list.push(8); 57 | list.push(10); 58 | 59 | System.out.println("Original linked list "); 60 | list.printList(head); 61 | list.reverse(); 62 | System.out.println(""); 63 | System.out.println("The reversed Linked List is "); 64 | list.printList(head); 65 | } 66 | } -------------------------------------------------------------------------------- /java/DoublyLinkedLists/mergesort.java: -------------------------------------------------------------------------------- 1 | // Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort. 2 | 3 | class LinkedList { 4 | static Node head; // head of list 5 | /* Node Class */ 6 | static class Node { 7 | int data; 8 | Node next, prev; 9 | // Constructor to create a new node 10 | Node(int d) { 11 | data = d; 12 | next = prev = null; 13 | } 14 | } 15 | void print(Node node) { 16 | Node temp = node; 17 | System.out.println("Forward Traversal using next pointer"); 18 | while (node != null) { 19 | System.out.print(node.data + " "); 20 | temp = node; 21 | node = node.next; 22 | } 23 | System.out.println("\nBackward Traversal using prev pointer"); 24 | while (temp != null) { 25 | System.out.print(temp.data + " "); 26 | temp = temp.prev; 27 | } 28 | } 29 | 30 | // Split a doubly linked list (DLL) into 2 DLLs of 31 | // half sizes 32 | Node split(Node head) { 33 | Node fast = head, slow = head; 34 | while (fast.next != null && fast.next.next != null) { 35 | fast = fast.next.next; 36 | slow = slow.next; 37 | } 38 | Node temp = slow.next; 39 | slow.next = null; 40 | return temp; 41 | } 42 | 43 | Node mergeSort(Node node) { 44 | if (node == null || node.next == null) { 45 | return node; 46 | } 47 | Node second = split(node); 48 | 49 | // Recur for left and right halves 50 | node = mergeSort(node); 51 | second = mergeSort(second); 52 | 53 | // Merge the two sorted halves 54 | return merge(node, second); 55 | } 56 | 57 | // Function to merge two linked lists 58 | Node merge(Node first, Node second) { 59 | // If first linked list is empty 60 | if (first == null) { 61 | return second; 62 | } 63 | // If second linked list is empty 64 | if (second == null) { 65 | return first; 66 | } 67 | // Pick the smaller value 68 | if (first.data < second.data) { 69 | first.next = merge(first.next, second); 70 | first.next.prev = first; 71 | first.prev = null; 72 | return first; 73 | } else { 74 | second.next = merge(first, second.next); 75 | second.next.prev = second; 76 | second.prev = null; 77 | return second; 78 | } 79 | } 80 | 81 | public static void main(String[] args) { 82 | 83 | LinkedList list = new LinkedList(); 84 | list.head = new Node(10); 85 | list.head.next = new Node(30); 86 | list.head.next.next = new Node(3); 87 | list.head.next.next.next = new Node(4); 88 | list.head.next.next.next.next = new Node(20); 89 | list.head.next.next.next.next.next = new Node(5); 90 | 91 | Node node = null; 92 | node = list.mergeSort(head); 93 | System.out.println("Linked list after sorting :"); 94 | list.print(node); 95 | 96 | } 97 | } -------------------------------------------------------------------------------- /java/DoublyLinkedLists/sortandinsert.cpp: -------------------------------------------------------------------------------- 1 | // TODO : Write a JAVA program for the same. 2 | 3 | // Insert value in sorted way in a sorted doubly linked list 4 | // Given a sorted doubly linked list and a value to insert, write a function to insert the value in sorted way. 5 | 6 | // Algorithm: 7 | // Let input doubly linked list is sorted in increasing order. 8 | // New node passed to the function contains data in the data part and previous and next link are set to NULL. 9 | 10 | // sortedInsert(head_ref, newNode) 11 | // if (head_ref == NULL) 12 | // head_ref = newNode 13 | 14 | // else if head_ref->data >= newNode->data 15 | // newNode->next = head_ref 16 | // newNode->next->prev = newNode 17 | // head_ref = newNode 18 | 19 | // else 20 | // Initialize current = head_ref 21 | // while (current->next != NULL and 22 | // current->next->data data) 23 | // current = current->next 24 | 25 | // newNode->next = current->next 26 | // if current->next != NULL 27 | // newNode->next->prev = newNode 28 | 29 | // current->next = newNode 30 | // newNode->prev = current 31 | 32 | #include 33 | using namespace std; 34 | // Node of a doubly linked list 35 | struct Node { 36 | int data; 37 | struct Node* prev, *next; 38 | }; 39 | 40 | struct Node* getNode(int data) { 41 | // allocate node 42 | struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); 43 | // put in the data 44 | newNode->data = data; 45 | newNode->prev = newNode->next = NULL; 46 | return newNode; 47 | } 48 | 49 | // function to insert a new node in sorted way in 50 | // a sorted doubly linked list 51 | void sortedInsert(struct Node** head_ref, struct Node* newNode) { 52 | struct Node* current; 53 | // if list is empty 54 | if (*head_ref == NULL) 55 | *head_ref = newNode; 56 | // if the node is to be inserted at the beginning of the doubly linked list 57 | else if ((*head_ref)->data >= newNode->data) { 58 | newNode->next = *head_ref; 59 | newNode->next->prev = newNode; 60 | *head_ref = newNode; 61 | } 62 | 63 | else { 64 | current = *head_ref; 65 | // locate the node after which the new node is to be inserted 66 | while (current->next != NULL && current->next->data < newNode->data) 67 | current = current->next; 68 | 69 | /* Make the appropriate links */ 70 | newNode->next = current->next; 71 | 72 | // if the new node is not inserted at the end of the list 73 | if (current->next != NULL) 74 | newNode->next->prev = newNode; 75 | 76 | current->next = newNode; 77 | newNode->prev = current; 78 | } 79 | } 80 | 81 | // function to print the doubly linked list 82 | void printList(struct Node* head) { 83 | while (head != NULL) { 84 | cout << head->data << " "; 85 | head = head->next; 86 | } 87 | } 88 | 89 | int main() { 90 | /* start with the empty doubly linked list */ 91 | struct Node* head = NULL; 92 | 93 | // insert the following nodes in sorted way 94 | struct Node* new_node = getNode(8); 95 | sortedInsert(&head, new_node); 96 | new_node = getNode(5); 97 | sortedInsert(&head, new_node); 98 | new_node = getNode(3); 99 | sortedInsert(&head, new_node); 100 | new_node = getNode(10); 101 | sortedInsert(&head, new_node); 102 | new_node = getNode(12); 103 | sortedInsert(&head, new_node); 104 | new_node = getNode(9); 105 | sortedInsert(&head, new_node); 106 | 107 | cout << "Created Doubly Linked List" << endl; 108 | printList(head); 109 | return 0; 110 | } -------------------------------------------------------------------------------- /java/LinkedLists/DeleteElementKey.java: -------------------------------------------------------------------------------- 1 | // Given a singly linked list and a position, delete a linked list node with the given key 2 | 3 | class LinkedList 4 | { 5 | Node head; // head of list 6 | 7 | /* Linked list Node*/ 8 | class Node 9 | { 10 | int data; 11 | Node next; 12 | 13 | // Constructor to create a new node 14 | // Next is by default initialized 15 | // as null 16 | Node(int d) { 17 | data = d; 18 | next=null; 19 | } 20 | } 21 | // Insert a new node at front 22 | public void insertNode(int item){ 23 | Node node = new Node(item); 24 | node.next = head; 25 | head = node; // move the head to point the next node 26 | } 27 | public void print(){ 28 | Node node = head; 29 | while(node!=null){ 30 | System.out.print(node.data + " -> "); 31 | node = node.next; 32 | } 33 | System.out.println("null"); 34 | } 35 | public void deleteNode(int key){ 36 | Node temp = head; 37 | Node prev = null; 38 | if(temp != null && temp.data == key){ 39 | head = temp.next; 40 | return; 41 | } 42 | //keep track of prev node inorder to delete temp.next 43 | while(temp != null && temp.data != key){ 44 | prev = temp; 45 | temp = temp.next; 46 | } 47 | if(temp == null) return; //key not present :( 48 | prev.next = temp.next; //unlink the node 49 | } 50 | public static void main(String args[]){ 51 | LinkedList llist = new LinkedList(); 52 | for(int i=5;i>0;--i){ 53 | llist.insertNode(i); 54 | } 55 | System.out.println("Linked list - "); 56 | llist.print(); 57 | llist.deleteNode(3); //Delete node at position 3 58 | System.out.println("After deletion - "); 59 | llist.print(); 60 | } 61 | } -------------------------------------------------------------------------------- /java/LinkedLists/DeleteElementPosition.java: -------------------------------------------------------------------------------- 1 | // Given a singly linked list and a position, delete a linked list node at the given position 2 | 3 | class LinkedList 4 | { 5 | Node head; // head of list 6 | 7 | /* Linked list Node*/ 8 | class Node 9 | { 10 | int data; 11 | Node next; 12 | 13 | // Constructor to create a new node 14 | // Next is by default initialized 15 | // as null 16 | Node(int d) { 17 | data = d; 18 | next=null; 19 | } 20 | } 21 | // Insert a new node at front 22 | public void insertNode(int item){ 23 | Node node = new Node(item); 24 | node.next = head; 25 | head = node; // move the head to point the next node 26 | } 27 | public void deleteNode(int position){ 28 | if(head == null) return; //empty linked list ? 29 | Node temp = head; 30 | if(position == 0){ 31 | head = temp.next; // change head 32 | return; 33 | } 34 | // Let's find the previous node next to the node to be deleted. 35 | for(int i=0;temp != null && i"); 48 | node = node.next; 49 | } 50 | System.out.println("null"); 51 | } 52 | public static void main(String args[]){ 53 | LinkedList llist = new LinkedList(); 54 | for(int i=5;i>0;--i){ 55 | llist.insertNode(i); 56 | } 57 | System.out.println("Linked list - "); 58 | llist.print(); 59 | llist.deleteNode(3); //Delete node at position 3 60 | System.out.println("After deletion - "); 61 | llist.print(); 62 | } 63 | } -------------------------------------------------------------------------------- /java/LinkedLists/DetectLoop.java: -------------------------------------------------------------------------------- 1 | // Given a singly linked list, detect whether the given LL has a loop. 2 | import java.util.*; 3 | 4 | class LinkedList 5 | { 6 | static Node head; // head of list 7 | 8 | /* Linked list Node*/ 9 | static class Node 10 | { 11 | int data; 12 | Node next; 13 | 14 | // Constructor to create a new node 15 | // Next is by default initialized 16 | // as null 17 | Node(int d) { 18 | data = d; 19 | next=null; 20 | } 21 | } 22 | public static void insertNode(int item){ 23 | Node node = new Node(item); 24 | node.next = head; 25 | head = node; 26 | } 27 | public static boolean detectLoop(Node x){ 28 | HashSet s = new HashSet(); 29 | while(x != null){ 30 | if(s.contains(x)) 31 | return true; // if node is already present,then a loop exists 32 | s.add(x); 33 | x = x.next; 34 | } 35 | return false; 36 | } 37 | public static void main(String args[]){ 38 | LinkedList llist = new LinkedList(); 39 | llist.insertNode(1); 40 | llist.insertNode(2); 41 | llist.insertNode(3); 42 | llist.insertNode(4); 43 | llist.insertNode(5); 44 | llist.head.next.next = llist.head; 45 | if(detectLoop(head)) 46 | System.out.println("Loop found"); 47 | else 48 | System.out.println("No loop :)"); 49 | } 50 | } -------------------------------------------------------------------------------- /java/LinkedLists/Implentation.java: -------------------------------------------------------------------------------- 1 | // 1. General Implementation of LinkedList - from geeksforgeeks.com 2 | 3 | class LinkedList 4 | { 5 | Node head; // head of list 6 | 7 | /* Linked list Node*/ 8 | class Node 9 | { 10 | int data; 11 | Node next; 12 | 13 | // Constructor to create a new node 14 | // Next is by default initialized 15 | // as null 16 | Node(int d) {data = d;} 17 | } 18 | /* method to create a simple linked list with 3 nodes*/ 19 | public static void main(String[] args) 20 | { 21 | /* Start with the empty list. */ 22 | LinkedList llist = new LinkedList(); 23 | 24 | llist.head = new Node(1); 25 | Node second = new Node(2); 26 | Node third = new Node(3); 27 | 28 | /* Three nodes have been allocated dynamically. 29 | We have references to these three blocks as first, 30 | second and third 31 | 32 | llist.head second third 33 | | | | 34 | | | | 35 | +----+------+ +----+------+ +----+------+ 36 | | 1 | null | | 2 | null | | 3 | null | 37 | +----+------+ +----+------+ +----+------+ */ 38 | 39 | llist.head.next = second; // Link first node with the second node 40 | 41 | /* Now next of first Node refers to second. So they 42 | both are linked. 43 | 44 | llist.head second third 45 | | | | 46 | | | | 47 | +----+------+ +----+------+ +----+------+ 48 | | 1 | o-------->| 2 | null | | 3 | null | 49 | +----+------+ +----+------+ +----+------+ */ 50 | 51 | second.next = third; // Link second node with the third node 52 | 53 | /* Now next of second Node refers to third. So all three 54 | nodes are linked. 55 | 56 | llist.head second third 57 | | | | 58 | | | | 59 | +----+------+ +----+------+ +----+------+ 60 | | 1 | o-------->| 2 | o-------->| 3 | null | 61 | +----+------+ +----+------+ +----+------+ */ 62 | } 63 | } 64 | 65 | //2. Traversal of LinkedList 66 | 67 | class LinkedList 68 | { 69 | Node head; // head of list 70 | 71 | /* Linked list Node. This inner class is made static so that 72 | main() can access it */ 73 | static class Node { 74 | int data; 75 | Node next; 76 | Node(int d) { data = d; next=null; } // Constructor 77 | } 78 | 79 | /* This function prints contents of linked list starting from head */ 80 | public void printList() 81 | { 82 | Node node = head; 83 | while (node != null) 84 | { 85 | System.out.print(node.data+" "); 86 | node = node.next; 87 | } 88 | } 89 | 90 | /* method to create a simple linked list with 3 nodes*/ 91 | public static void main(String[] args) 92 | { 93 | /* Start with the empty list. */ 94 | LinkedList llist = new LinkedList(); 95 | 96 | llist.head = new Node(1); 97 | Node second = new Node(2); 98 | Node third = new Node(3); 99 | 100 | llist.head.next = second; // Link first node with the second node 101 | second.next = third; // Link first node with the second node 102 | 103 | llist.printList(); 104 | } 105 | } 106 | 107 | 108 | -------------------------------------------------------------------------------- /java/LinkedLists/MergeLists.java: -------------------------------------------------------------------------------- 1 | // Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, 2 | // and merges the two together into one list which is in increasing order. 3 | // SortedMerge() should return the new list. The new list should be made by splicing 4 | // together the nodes of the first two lists. 5 | 6 | // For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, 7 | // then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20. 8 | 9 | // There are many cases to deal with: either ‘a’ or ‘b’ may be empty, 10 | // during processing either ‘a’ or ‘b’ may run out first, 11 | // and finally there’s the problem of starting the result list empty, 12 | // and building it up while going through ‘a’ and ‘b’. 13 | 14 | public class Node{ 15 | public int data; 16 | public Node next; 17 | public Node(int data){ 18 | this.data = data; 19 | this.next = null; 20 | } 21 | } 22 | 23 | public class LinkedList{ 24 | public Node head; 25 | public LinkedList(){ 26 | head = null; 27 | } 28 | public void insertNodeAtBegin(int data){ 29 | Node node = new Node(data); 30 | node.next = head; 31 | head = node; 32 | } 33 | public void insertNodeAtEnd(int data) { 34 | if (head == null) { 35 | insertNodeAtBegin(data); 36 | } else { 37 | Node n = new Node(data); 38 | Node currNode = head; 39 | while (currNode.next != null) { 40 | currNode = currNode.next; 41 | } 42 | currNode.next = n; 43 | } 44 | } 45 | } 46 | 47 | public class MergeLinkedLists{ 48 | private LinkedList a; 49 | private LinkedList b; 50 | 51 | public MergeLinkedLists(LinkedList a,LinkedList b){ 52 | this.a = a; 53 | this.b = b; 54 | } 55 | 56 | public LinkedList merge(){ 57 | LinkedList result = new LinkedList(); 58 | while(a.head != null && b.head != null){ 59 | if(a.head.data < b.head.data){ 60 | result.insertNodeAtEnd(a.head.data); 61 | a.head = a.head.next; 62 | }else{ 63 | result.insertNodeAtEnd(b.head.data); 64 | b.head = b.head.next; 65 | } 66 | } 67 | while(a.head != null){ // b empty? 68 | result.insertNodeAtEnd(a.head.data); 69 | a.head = a.head.next; 70 | } 71 | while (b.head != null) { 72 | result.insertNodeAtEnd(b.head.data); 73 | b.head = b.head.next; 74 | } 75 | return result; 76 | } 77 | public void print(Node head){ 78 | while(node != null){ 79 | System.out.print(node.data + " -> "); 80 | node = node.next; 81 | } 82 | System.out.println(" "); 83 | } 84 | 85 | public static void main(String args[]){ 86 | LinkedList listA = new LinkedList(); 87 | listA.insertNodeAtBegin(15); 88 | listA.insertNodeAtBegin(10); 89 | listA.insertNodeAtBegin(5); 90 | LinkedList listB = new LinkedList(); 91 | listB.insertNodeAtBegin(20); 92 | listB.insertNodeAtBegin(3); 93 | listB.insertNodeAtBegin(2); 94 | 95 | MergeLinkedLists mergeA = new MergeLinkedLists(listA,listB); 96 | mergeA.print(listA.head); 97 | mergeA.print(listB.head); 98 | 99 | LinkedList result = new LinkedList(); 100 | mergeA.print(result.head); 101 | } 102 | } -------------------------------------------------------------------------------- /java/LinkedLists/MiddleElement.java: -------------------------------------------------------------------------------- 1 | class LinkedList{ 2 | Node head; 3 | class Node{ 4 | int data; 5 | Node next; 6 | Node(int d){ 7 | data = d; 8 | } 9 | } 10 | public void printMiddleElement(){ // The same logic as followed in the ES6 javascript code (Checkout the js folder in the repo) 11 | Node slowPointer = head; 12 | Node fastPointer = head; 13 | if(head != null){ 14 | while(fastPointer != null && fastPointer.next != null){ 15 | fastPointer = fastPointer.next.next; 16 | slowPointer = slowPointer.next; 17 | } 18 | System.out.println("The middle element is " + slowPointer.data); 19 | } 20 | } 21 | 22 | public void insertNode(int item){ 23 | Node node = new Node(item); 24 | node.next = head; 25 | head = node.next; // move the head to point the next node 26 | } 27 | 28 | public void print(){ 29 | Node node = head; 30 | while(node != null){ 31 | System.out.print(node.data + "->"); 32 | node = node.next; 33 | } 34 | System.out.println("null"); 35 | } 36 | public static void main(String args[]){ 37 | LinkedList llist = new LinkedList(); 38 | for(int i=5;i>0;--i){ 39 | llist.insertNode(i); 40 | llist.print(); 41 | llist.printMiddleElement(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /java/LinkedLists/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | // Write a removeDuplicates() function which takes a list and deletes any duplicate nodes from the list. 2 | // The list is not sorted. 3 | 4 | // For example if the linked list is 12->11->12->21->41->43->21 then 5 | // removeDuplicates() should convert the list to 12->11->21->41->43. 6 | 7 | import java.util.HashSet; 8 | class LinkedList{ 9 | static class Node{ 10 | int data; 11 | Node next; 12 | Node(int data){ 13 | this.data = data; 14 | this.next = null; 15 | } 16 | } 17 | 18 | static void removeDuplicates(Node head){ 19 | HashSet s = new HashSet<>(); 20 | Node current = head; 21 | Node prev = null; 22 | while(current != null){ 23 | int currentValue = current.data; 24 | if(s.contains(currentValue)) 25 | prev.next = current.next; //skip that duplicate item. 26 | else{ 27 | s.add(currentValue); 28 | prev = current; 29 | } 30 | current = current.next; 31 | } 32 | } 33 | 34 | static void print(Node node){ 35 | while(node != null){ 36 | System.out.print(node.data + " "); 37 | node = node.next; 38 | } 39 | System.out.println(); 40 | } 41 | 42 | public static void main(String args[]){ 43 | Node start = new Node(12); 44 | start.next = new Node(11); 45 | start.next.next = new Node(12); 46 | start.next.next.next = new Node(21); 47 | start.next.next.next.next = new Node(41); 48 | start.next.next.next.next.next = new Node(43); 49 | start.next.next.next.next.next.next = new Node(11); 50 | 51 | System.out.println("original list - "); 52 | print(start); 53 | 54 | System.out.println("After removal of duplicates - "); 55 | removeDuplicates(start); 56 | print(start); 57 | } 58 | } -------------------------------------------------------------------------------- /java/LinkedLists/Reverse.java: -------------------------------------------------------------------------------- 1 | // Given pointer to the head node of a linked list, the task is to reverse the linked list. 2 | // We need to reverse the list by changing links between nodes. 3 | 4 | // Examples: 5 | 6 | // Input : Head of following linked list 7 | // 1->2->3->4->NULL 8 | // Output : Linked list should be changed to, 9 | // 4->3->2->1->NULL 10 | 11 | // Input : Head of following linked list 12 | // 1->2->3->4->5->NULL 13 | // Output : Linked list should be changed to, 14 | // 5->4->3->2->1->NULL 15 | 16 | // Input : NULL 17 | // Output : NULL 18 | 19 | // Input : 1->NULL 20 | // Output : 1->NULL 21 | 22 | // Algorithm - iterative 23 | // 1. Initialize three pointers prev as NULL, curr as head and next as NULL. 24 | // 2. Iterate trough the linked list. In loop, do following. 25 | // Before changing next of current, 26 | // store next node 27 | // next = curr->next 28 | // Now change next of current 29 | // This is where actual reversing happens 30 | // curr->next = prev 31 | 32 | // Move prev and curr one step forward 33 | // prev = curr 34 | // curr = next 35 | 36 | // Time Complexity: O(n) 37 | // Space Complexity: O(1) 38 | 39 | class LinkedList{ 40 | static Node head; 41 | static class Node{ 42 | int data; 43 | Node next; 44 | Node(int d){ 45 | data = d; 46 | next = null; 47 | } 48 | } 49 | public void print(Node node){ //pass the changed head as a parameter. 50 | while(node != null){ 51 | System.out.print(node.data + " "); 52 | node = node.next; 53 | } 54 | System.out.println("null"); 55 | } 56 | 57 | Node reverse(Node node){ 58 | Node prev = null; 59 | Node current = node; 60 | Node next = null; 61 | while(current != null){ 62 | next = current.next; 63 | current.next = prev; 64 | prev = current; 65 | current = next; 66 | } 67 | node = prev; 68 | return node; 69 | } 70 | 71 | public static void main(String args[]){ 72 | LinkedList llist = new LinkedList(); 73 | llist.head = new Node(1); 74 | llist.head.next = new Node(2); 75 | llist.head.next.next = new Node(3); 76 | llist.head.next.next.next = new Node(4); 77 | llist.head.next.next.next.next = new Node(5); 78 | System.out.println("Original list - "); 79 | llist.print(head); 80 | 81 | head = llist.reverse(head); 82 | System.out.println("Reversed list - "); 83 | llist.print(head); 84 | } 85 | } -------------------------------------------------------------------------------- /java/LinkedLists/SwapNodesWithoutSwappingData.java: -------------------------------------------------------------------------------- 1 | // Given a linked list and two keys in it, swap nodes for two given keys. 2 | // Nodes should be swapped by changing links. Swapping data of nodes may be expensive 3 | // in many situations when data contains many fields. 4 | 5 | // It may be assumed that all keys in linked list are distinct. 6 | 7 | // Examples: 8 | 9 | // Input: 10->15->12->13->20->14, x = 12, y = 20 10 | // Output: 10->15->20->13->12->14 11 | 12 | // Input: 10->15->12->13->20->14, x = 10, y = 20 13 | // Output: 20->15->12->13->10->14 14 | 15 | // Input: 10->15->12->13->20->14, x = 12, y = 13 16 | // Output: 10->15->13->12->20->14 17 | 18 | class Node 19 | { 20 | int data; 21 | Node next; 22 | Node(int d) 23 | { 24 | data = d; 25 | next = null; 26 | } 27 | } 28 | 29 | class LinkedList{ 30 | Node head; 31 | public void swapNodes(int x,int y){ 32 | if(x == y) return; 33 | //look for x 34 | Node prevX = null,currentX = head; 35 | while(currentX != null && currentX.data != x){ 36 | prevX = currentX; 37 | currentX = currentX.next; 38 | } 39 | //look for y 40 | Node prevY = null,currentY = head; 41 | while(currentY != null && currentY.data != y){ 42 | prevY = currentY; 43 | currentY = currentY.next; 44 | } 45 | if(currentX == null || currentY == null) return; 46 | // if x is not head,then make y the new head. 47 | if(prevX != null) 48 | prevX.next = currentY; 49 | else 50 | head = currentY; 51 | // if y is not head,then make x the new head. 52 | if(prevY != null) 53 | prevY.next = currentX; 54 | else 55 | head = currentX; 56 | // swap next pointers. 57 | Node temp = currentX.next; 58 | currentX.next = currentY.next; 59 | currentY.next = temp; 60 | } 61 | 62 | public void insertNode(int item){ 63 | Node node = new Node(item); 64 | node.next = head; 65 | head = node; // move the head to point the next node 66 | } 67 | 68 | public void print(){ 69 | Node node = head; 70 | while(node != null){ 71 | System.out.print(node.data + " "); 72 | node = node.next; 73 | } 74 | System.out.println(); 75 | } 76 | 77 | public static void main(String args[]){ 78 | LinkedList llist = new LinkedList(); 79 | llist.insertNode(14); 80 | llist.insertNode(20); 81 | llist.insertNode(13); 82 | llist.insertNode(12); 83 | llist.insertNode(15); 84 | llist.insertNode(10); 85 | System.out.println("Before swap - "); 86 | llist.print(); 87 | llist.swapNodes(12,20); 88 | System.out.println("After swap - "); 89 | llist.print(); 90 | } 91 | } -------------------------------------------------------------------------------- /java/LinkedLists/UnionAndIntersection.java: -------------------------------------------------------------------------------- 1 | // Given two Linked Lists, create union and intersection lists that contain union and intersection 2 | // of the elements present in the given lists. Order of elments in output lists doesn’t matter. 3 | 4 | // Example: 5 | 6 | // Input: 7 | // List1: 10->15->4->20 8 | // list2: 8->4->2->10 9 | // Output: 10 | // Intersection List: 4->10 11 | // Union List: 2->8->20->4->15->10 12 | 13 | class LinkedList{ 14 | Node head; 15 | class Node{ 16 | int data; 17 | Node next; 18 | Node(int data){ 19 | this.data = data; 20 | this.next = null; 21 | } 22 | } 23 | 24 | public void insertNode(int data){ 25 | Node node = new Node(data); 26 | node.next = head; 27 | head = node; 28 | } 29 | 30 | public void print(){ 31 | Node node = head; 32 | while(node != null){ 33 | System.out.print(node.data + "->"); 34 | node = node.next; 35 | } 36 | System.out.println(); 37 | } 38 | 39 | public void union(Node head1,Node head2){ 40 | Node a = head1, b = head2; 41 | // insert all elements of list 1 42 | while(a != null){ 43 | insertNode(a.data); 44 | a = a.next; 45 | } 46 | // insert all elements of list 2 that are not present in list 1 47 | while(b != null){ 48 | if(!isPresent(head,b.data)) 49 | insertNode(b.data); 50 | b = b.next; 51 | } 52 | } 53 | 54 | public void intersection(Node head1, Node head2){ 55 | Node result = null; 56 | Node a = head1; 57 | // check if any element of a is present in b.If present,add it to the result. 58 | while(a != null){ 59 | if(isPresent(head2,a.data)) 60 | insertNode(a.data); 61 | a = a.next; 62 | } 63 | } 64 | 65 | boolean isPresent(Node head,int data){ 66 | Node node = head; 67 | while(node != null){ 68 | if(node.data == data) 69 | return true; 70 | node = node.next; 71 | } 72 | return false; 73 | } 74 | 75 | public static void main(String args[]){ 76 | LinkedList listA = new LinkedList(); 77 | LinkedList listB = new LinkedList(); 78 | LinkedList union = new LinkedList(); 79 | LinkedList intersection = new LinkedList(); 80 | 81 | listA.insertNode(20); 82 | listA.insertNode(4); 83 | listA.insertNode(15); 84 | listA.insertNode(10); 85 | 86 | listB.insertNode(10); 87 | listB.insertNode(2); 88 | listB.insertNode(4); 89 | listB.insertNode(8); 90 | 91 | intersection.intersection(listA.head,listB.head); 92 | union.union(listA.head,listB.head); 93 | 94 | intersection.print(); 95 | union.print(); 96 | } 97 | } -------------------------------------------------------------------------------- /java/Matrix/Spiralmatrix.java: -------------------------------------------------------------------------------- 1 | // Asked by - Delta X 2 | // Given m x n matrix,print the elements by traversing through the array in spiral form(clockwise) 3 | 4 | // Example - 5 | // m=4,n=4 6 | // array = [1,2,3,4 7 | // 5,6,7,8 8 | // 9,10,11,12 9 | // 13,14,15,16] 10 | 11 | // Output - 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 12 | 13 | import java.util.Scanner; 14 | class Spiral{ 15 | public static void printMatrix(int m,int n,int array[][]){ 16 | int k=0,l=0,i; //k and l are starting row and column index respectively. 17 | while(k < m && l < n){ 18 | // traverse the first row. 19 | for(i=l;i=l;--i) 32 | System.out.print(array[m-1][i] + " "); 33 | m--; 34 | } 35 | //traverse the first column. 36 | if(l < n){ 37 | for(i=m-1;i>=k;--i) 38 | System.out.print(array[i][l] + " "); 39 | l++; 40 | } 41 | } 42 | } 43 | public static void main(String args[]){ 44 | int m,n; //total no. of rows and columns. 45 | Scanner sc = new Scanner(System.in); 46 | m = sc.nextInt(); 47 | n = sc.nextInt(); 48 | int array[][] = new int[m][n]; 49 | for(int i=0;i=col;i--){ 74 | curr = matrix[m-1][i]; 75 | matrix[m-1][i] = prev; 76 | prev = curr; 77 | } 78 | } 79 | m--; 80 | 81 | 82 | // Move elements of first column from the remaining columns 83 | if(col < n){ 84 | for(int i=m-1;i>=row;i--){ 85 | curr = matrix[i][col]; 86 | matrix[i][col] = prev; 87 | prev = curr; 88 | } 89 | } 90 | col++; 91 | } 92 | // Print rotated matrix 93 | for (int i = 0; i < R; i++){ 94 | for (int j = 0; j < C; j++) 95 | System.out.print( matrix[i][j] + " "); 96 | System.out.println(); 97 | } 98 | } 99 | 100 | public static void main(String[] args){ 101 | int array[][] = {{1, 2, 3, 4}, 102 | {5, 6, 7, 8}, 103 | {9, 10, 11, 12}, 104 | {13, 14, 15, 16} 105 | }; 106 | rotateMatrix(R, C, array); 107 | } 108 | } -------------------------------------------------------------------------------- /java/Matrix/sortmatrix.java: -------------------------------------------------------------------------------- 1 | // Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is 2 | // sorted in a way such that all elements in a row are sorted in increasing order and for row `i`, where 1 <= i <= n-1, 3 | // first element of row 'i' is greater than or equal to the last element of row 'i-1'. 4 | 5 | // Examples: 6 | 7 | // Input : mat[][] = { {5, 4, 7}, 8 | // {1, 3, 8}, 9 | // {2, 9, 6} } 10 | // Output : 1 2 3 11 | // 4 5 6 12 | // 7 8 9 13 | 14 | // Approach: Create a temp[] array of size n^2. 15 | // Starting with the first row one by one copy the elements of the given matrix into temp[]. 16 | // Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix. 17 | 18 | import java.io.*; 19 | import java.util.*; 20 | 21 | class Matrix{ 22 | // static int SIZE = 10; 23 | static void sortMatrix(int[][] matrix, int n){ 24 | // copy the elements of the matrix to the temp array 25 | int[] temp = new int[n*n]; 26 | int k = 0; 27 | for(int i=0;i0; j++){ 53 | // storing element. 54 | arr[i][j] = k+1; 55 | // decrement element at 56 | // kth index. 57 | numbers[k]--; 58 | // if array contains zero 59 | // then increment index to 60 | // make this next index 61 | if (numbers[k] == 0) 62 | k++; 63 | } 64 | } 65 | // for odd row. 66 | else{ 67 | // for each column. 68 | for (int j=columns-1; j>=0 && numbers[k]>0; j--){ 69 | // storing element. 70 | arr[i][j] = k+1; 71 | // decrement element 72 | // at kth index. 73 | numbers[k]--; 74 | // if array contains zero then 75 | // increment index to make this 76 | // next index. 77 | if (numbers[k]==0) 78 | k++; 79 | } 80 | } 81 | } 82 | 83 | // printing the stored elements. 84 | for (int i=0;i y, then F(x) < F(y) 14 | 15 | import java.io.*; 16 | class GFG { 17 | // Function to find maximum 18 | static boolean findGreater(int x, int y) { 19 | // Case 1 20 | if (x > y) 21 | return false; 22 | 23 | // Case 2 24 | else 25 | return true; 26 | } 27 | 28 | // Driver Code 29 | public static void main (String[] args){ 30 | int x = 4; 31 | int y = 9; 32 | if(findGreater(x, y)) 33 | System.out.println("1"); 34 | else 35 | System.out.println("2"); 36 | } 37 | } -------------------------------------------------------------------------------- /java/MiscellaneousProblems/nDigitPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Streamoid Technologies 3 | 4 | PROBLEM: 5 | You are given a integer n .Find how many ways you can make a palindrome number consisting of n digits and 6 | print it, also you are not supposed to use any array or character array which means you can only use recursion. 7 | 8 | Example : n = 2 then answer would be 11,22,33,.... 9 | */ 10 | 11 | import java.util.*; 12 | 13 | public class myMain { 14 | public static long mirror(long num1, long num2) { 15 | if(num2 < 10) return num1*10 + num2; //for the last digit 16 | return(mirror(num1*10 + num2 % 10, num2/10)); //reverses the given number in each iteration 17 | } 18 | public static long printPalindrome(int num) { 19 | long total = 0L; 20 | if(num%2 == 0) { //for number with even digits 21 | int base = num/2; 22 | Long startInt = Math.round(Math.pow(10, base-1)); //calculates starting and ending numbers for first half 23 | Long endInt = Math.round(Math.pow(10, base)) - 1; 24 | //System.out.println("start:" + startInt + ",end:" + endInt); 25 | for(long l1 = startInt; l1 <= endInt; l1++) { 26 | long l2 = mirror(0L,l1); 27 | System.out.println(l1 * startInt * 10 + l2); //concatinate first half and mirrored half 28 | total++; 29 | } 30 | } else { //for number with odd digits 31 | int base = num/2; 32 | Long startInt = Math.round(Math.pow(10, base-1)); //calculates starting and ending numbers for first half 33 | Long endInt = Math.round(Math.pow(10, base)) - 1; 34 | System.out.println("start:" + startInt + ",end:" + endInt); 35 | for(long l1 = startInt; l1 <= endInt; l1++) { 36 | long l2 = mirror(0L,l1); 37 | for(int mid = 0; mid < 10 ; mid++) { 38 | System.out.println((l1 * 10 + mid)*startInt*10 + l2); //concatinate first half, middle digit and mirrored half 39 | total++; 40 | } 41 | } 42 | } 43 | return total; 44 | } 45 | public static void main(String[] args) { 46 | // TODO Auto-generated method stub 47 | Scanner sc = new Scanner(System.in); 48 | int num = sc.nextInt(); 49 | if(num < 2) { 50 | System.out.println("Please specify at least 2"); 51 | System.exit(1); 52 | } 53 | //printPallindrome(num); 54 | long total = printPalindrome(num); 55 | System.out.println("Total Palindromes:" + total); 56 | 57 | } 58 | } -------------------------------------------------------------------------------- /java/MiscellaneousProblems/powerGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Delta X 3 | 4 | 2 players play a game. A number is given as input. If the number is a power of 2(i.e, 2^1, 2^2 .. 2^64), 5 | then divide the number by 2 and pass the number to the other player. Else, if the number is not a power 6 | of 2, then subtract the number with its nearest 2 power number and pass the number to the other player. 7 | PlayerA always starts the game. The player who gets to value 1(one) is the winner. Output the name of 8 | the winner, i.e, 'PlayerA' or 'PlayerB' 9 | 10 | Ex: 11 | n = 10 12 | Output: PlayerB 13 | 14 | n = 12 15 | Output = PlayerA 16 | */ 17 | 18 | import java.util.Scanner; 19 | import java.lang.Math; 20 | 21 | class PowerGame{ 22 | public static int isPower(int number){ 23 | int value = 1; 24 | for(int i=1;i<65;i++){ 25 | value *= 2; 26 | if(number == value) 27 | return -1; // return -1 is it is a power of 2. 28 | else if(value > number) 29 | return i-1; //return the nearest power. 30 | } 31 | return 0; 32 | } 33 | public static void main(String args[]){ 34 | Scanner sc = new Scanner(System.in); 35 | int n = sc.nextInt(); //enter the input number. 36 | int turn = 1; // keeps track of the player in current possession of the number.(A-1,B-2) 37 | int count = 0; 38 | 39 | while(n != 1){ 40 | count++; 41 | if(count % 2 == 0) 42 | turn = 2; //B's turn 43 | else 44 | turn = 1; //A's turn 45 | 46 | int value = isPower(n); 47 | if(value == -1) 48 | n = n/2; 49 | else 50 | n = n - (int)Math.pow(2, value); 51 | } 52 | if(turn == 1) 53 | System.out.println("Player A wins"); 54 | else 55 | System.out.println("Player B wins"); 56 | } 57 | } -------------------------------------------------------------------------------- /java/Recursion/countpaths.java: -------------------------------------------------------------------------------- 1 | // Count all possible paths from top left to bottom right of a mXn matrix 2 | 3 | // The problem is to count all the possible paths from top left to bottom right of a mXn matrix with the 4 | // constraints that from each cell you can either move only to right or down 5 | 6 | // Examples : 7 | 8 | // Input : m = 2, n = 2; 9 | // Output : 2 10 | // There are two paths 11 | // (0, 0) -> (0, 1) -> (1, 1) 12 | // (0, 0) -> (1, 0) -> (1, 1) 13 | 14 | // Input : m = 2, n = 3; 15 | // Output : 3 16 | // There are three paths 17 | // (0, 0) -> (0, 1) -> (0, 2) -> (1, 2) 18 | // (0, 0) -> (0, 1) -> (1, 1) -> (1, 2) 19 | // (0, 0) -> (1, 0) -> (1, 1) -> (1, 2) 20 | 21 | class Path{ 22 | static int numberOfPaths(int m, int n){ 23 | if(m == 1 || n == 1) 24 | return 1; 25 | // If diagonal movements are allowed then the last addition is required. 26 | return numberOfPaths(m-1, n) + numberOfPaths(m, n-1); 27 | } 28 | 29 | public static void main(String args[]){ 30 | System.out.println(numberOfPaths(2, 3)); 31 | } 32 | } -------------------------------------------------------------------------------- /java/Recursion/josephus.java: -------------------------------------------------------------------------------- 1 | // Asked by Walmart 2 | 3 | // Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is 4 | // killed in circle in a fixed direction. The task is to choose the safe place in the circle so that when you 5 | // perform these operations starting from 1st place in the circle, you are the last one remaining and survive. 6 | // You are required to complete the function josephus which returns an integer denoting such position . 7 | 8 | // The problem has following recursive structure. 9 | 10 | // josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1 11 | // josephus(1, k) = 1 12 | // After the first person (kth from begining) is killed, n-1 persons are left. So we call josephus(n - 1, k) to 13 | // get the position with n-1 persons. But the position returned by josephus(n - 1, k) will consider the position 14 | // starting from k%n + 1. So, we must make adjustments to the position returned by josephus(n - 1, k). 15 | 16 | import java.io.*; 17 | 18 | class Josefus{ 19 | static int josephus(int n, int k) { 20 | if (n == 1) 21 | return 1; 22 | else 23 | /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) 24 | considers the original position k%n + 1 as position 1 */ 25 | return (josephus(n - 1, k) + k-1) % n + 1; 26 | } 27 | public static void main(String[] args) { 28 | int n = 14; 29 | int k = 2; 30 | System.out.println("The chosen place is " + josephus(n, k)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Recursion/specialkeyboard.java: -------------------------------------------------------------------------------- 1 | // Asked by Google, Paytm, Amazon 2 | 3 | // Imagine you have a special keyboard with the following keys: 4 | // Key 1: Prints 'A' on screen 5 | // Key 2: (Ctrl-A): Select screen 6 | // Key 3: (Ctrl-C): Copy selection to buffer 7 | // Key 4: (Ctrl-V): Print buffer on screen appending it 8 | // after what has already been printed. 9 | 10 | // If you can only press the keyboard for N times (with the above four 11 | // keys), write a program to produce maximum numbers of A's. That is to 12 | // say, the input parameter is N (No. of keys that you can press), the 13 | // output is M (No. of As that you can produce). 14 | 15 | // Input: N = 3 16 | // Output: 3 17 | // We can at most get 3 A's on screen by pressing 18 | // following key sequence. 19 | // A, A, A 20 | 21 | // Input: N = 7 22 | // Output: 9 23 | // We can at most get 9 A's on screen by pressing 24 | // following key sequence. 25 | // A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V 26 | 27 | // Input: N = 11 28 | // Output: 27 29 | // We can at most get 27 A's on screen by pressing 30 | // following key sequence. 31 | // A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V, Ctrl A, 32 | // Ctrl C, Ctrl V, Ctrl V 33 | 34 | // Below are few important points to note. 35 | 36 | // a) For N < 7, the output is N itself. 37 | 38 | // b) Ctrl V can be used multiple times to print current buffer (See last two examples above). 39 | // The idea is to compute the optimal string length for N keystrokes by using a simple insight. 40 | //The sequence of N keystrokes which produces an optimal string length will end with a suffix of Ctrl-A, a Ctrl-C, 41 | //followed by only Ctrl-V's . (For N > 6) 42 | 43 | // The task is to find out the break-point after which we get the above suffix of keystrokes. 44 | // Definition of a breakpoint is that instance after which we need to only press Ctrl-A, Ctrl-C once and 45 | // the only Ctrl-V's afterwards to generate the optimal length. If we loop from N-3 to 1 and choose 46 | // each of these values for the break-point, and compute that optimal string they would produce. 47 | // Once the loop ends, we will have the maximum of the optimal lengths for various breakpoints, 48 | // thereby giving us the optimal length for N keystrokes. 49 | 50 | import java.io.*; 51 | class Keyboard{ 52 | // A recursive function that returns the optimal length string for N keystrokes 53 | static int findOptimal(int N) { 54 | // The optimal string length is N 55 | // when N is smaller than 7 56 | if (N < 7) 57 | return N; 58 | 59 | // Initialize result 60 | int max = 0; 61 | 62 | // TRY ALL POSSIBLE BREAK-POINTS For any keystroke N, we need to loop from N-3 keystrokes back to 63 | // 1 keystroke to find a breakpoint 'b' after which we will have Ctrl-A, Ctrl-C and then only Ctrl-V 64 | // all the way. 65 | int b; 66 | for (b=N-3;b>=1;b--){ 67 | // If the breakpoint is s at b'th keystroke then the optimal string would have length 68 | // (n-b-1)*screen[b-1]; 69 | int curr = (N - b - 1) * findOptimal(b); 70 | if (curr > max) 71 | max = curr; 72 | } 73 | return max; 74 | } 75 | public static void main(String[] args) { 76 | int N; 77 | // for the rest of the array we will rely on the previous entries to compute new ones 78 | for (N = 1; N <= 20; N++) 79 | System.out.println("Maximum Number of A's with " + N + " keystrokes is " + findOptimal(N)); 80 | } 81 | } -------------------------------------------------------------------------------- /java/Recursion/wateroverflow.java: -------------------------------------------------------------------------------- 1 | // Asked by Amazon 2 | 3 | // There is a stack of water glasses in a form of pascal triangle and a person wants to pour the water at 4 | // the topmost glass, but the capacity of each glass is 1 unit . Overflow takes place in such a way that after 5 | // 1 unit, 1/2 of remaining unit gets into bottom left glass and other half in bottom right glass. 6 | 7 | // Now the pours K units of water in the topmost glass and wants to know how much water is there in the jth glass 8 | // of the ith row. 9 | 10 | // Assume that there are enough glasses in the triangle till no glass overflows. 11 | 12 | // There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: 13 | // 1 14 | // 2 3 15 | // 4 5 6 16 | // 7 8 9 10 17 | // You can put water to only top glass. If you put more than 1 litre water to 1st glass, water overflows and fills 18 | // equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on. 19 | // If you have X litre of water and you put that water in top glass, how much water will be contained by jth glass 20 | // in ith row? 21 | 22 | // Example. If you will put 2 litre on top. 23 | // 1st - 1 litre 24 | // 2nd - 1/2 litre 25 | // 3rd - 1/2 litre 26 | 27 | import java.lang.*; 28 | 29 | class Water{ 30 | // Returns the amount of water in jth glass of ith row 31 | static float findWater(int i, int j, float X){ 32 | // A row number i has maximum i columns. So input column number must be less than i 33 | if (j > i) { 34 | System.out.println("Incorrect Input"); 35 | System.exit(0); 36 | } 37 | 38 | // There will be i*(i+1)/2 glasses till ith row (including ith row) 39 | int ll = Math.round((i * (i + 1) )); 40 | float[] glass = new float[ll + 2]; 41 | 42 | // Put all water in first glass 43 | int index = 0; 44 | glass[index] = X; 45 | 46 | // Now let the water flow to the downward glasses till the row number is less than or/ equal 47 | // to i (given row) correction : X can be zero for side glasses as they have lower rate to fill 48 | for (int row = 1; row <= i ; ++row) { 49 | // Fill glasses in a given row. Number of columns in a row is equal to row number 50 | for (int col = 1;col <= row; ++col, ++index) { 51 | // Get the water from current glass 52 | X = glass[index]; 53 | // Keep the amount less than or equal to capacity in current glass 54 | glass[index] = (X >= 1.0f) ? 1.0f : X; 55 | 56 | // Get the remaining amount 57 | X = (X >= 1.0f) ? (X - 1) : 0.0f; 58 | 59 | // Distribute the remaining amount to the down two glasses 60 | glass[index + row] += X / 2; 61 | glass[index + row + 1] += X / 2; 62 | } 63 | } 64 | // The index of jth glass in ith row will be i*(i-1)/2 + j - 1 65 | return glass[(int)(i * (i - 1) / 2 + j - 1)]; 66 | } 67 | 68 | public static void main(String[] args) { 69 | int i = 2, j = 2; 70 | float X = 2.0f; // Total amount of water 71 | System.out.println("Amount of water in jth " + "glass of ith row is: " + findWater(i, j, X)); 72 | } 73 | } -------------------------------------------------------------------------------- /java/arrays/AlternatePrimes.java: -------------------------------------------------------------------------------- 1 | // Given a number N, the task is to find alternate prime numbers till N. 2 | 3 | class Prime{ 4 | static int prime(int num){ 5 | int i, flag = 0; 6 | for(i=2;i<=num/2;i++){ 7 | if(num % i == 0){ 8 | flag = 1; 9 | break; 10 | } 11 | } 12 | if(flag == 0) 13 | return 1; 14 | return 0; 15 | } 16 | 17 | static void printAlternatePrimes(int n){ 18 | int count = 0; 19 | for(int i=2;i freq = new HashMap(); 14 | for(int i=0;i maxFreq) 22 | maxFreq = freq.get(a0); 23 | } 24 | // minimum number of elements required to be changed is n - (max frequency of a0). 25 | return n - maxFreq; 26 | } 27 | public static void main(String args[]){ 28 | int n=4, d=2; 29 | int a[] = {1, 2, 4, 6}; 30 | System.out.println(minChanges(a, n, d)); 31 | } 32 | } -------------------------------------------------------------------------------- /java/arrays/maxLengthOf0and1.java: -------------------------------------------------------------------------------- 1 | // Maximum length of segments of 0's and 1's 2 | 3 | // Given a string comprising of ones and zeroes. The task is to find the max length of string such that the number of 1 4 | // in each segment is greater than 0 5 | // Note : Each segment taken should be distinct. Index starts from 0. 6 | 7 | // Examples: Input - str = "100110001010001" 8 | // Output - 9 9 | // i.e 10011, length = 5 10 | // 101, length = 3 11 | // 1, length = 1 12 | // Hence the answer is 5+3+1 = 9 13 | 14 | // Approach: 15 | 16 | // * If start == n, limiting condition arises, return 0. 17 | // * Run a loop from start till n, computing for each subarray till n. 18 | // * If character is 1 then increment the count of 1 else increment the count of 0. 19 | // * If count of 1 is greater than 0, recursively call the function for index (k+1) i.e. next index and add the 20 | // remaining length i.e. k-start+1. 21 | // * Else only recursively call the function for next index k+1. 22 | // * Return dp[start]. 23 | 24 | import java.util.*; 25 | import java.lang.Math; 26 | 27 | class GFG { 28 | // Recursive Function to find total length of the array where 1 is greater than 0 29 | public static int find(int start, String adj, int n, int dp[]){ 30 | // If reaches till end 31 | if (start == n) 32 | return 0; 33 | 34 | // If dp is saved 35 | if (dp[start] != -1) 36 | return dp[start]; 37 | 38 | dp[start] = 0; 39 | int one = 0, zero = 0, k; 40 | 41 | // Finding for each length 42 | for (k = start; k < n; k++) { 43 | if (adj.charAt(k) == '1') one++; 44 | else zero++; 45 | // If the character scanned is 1 if (adj.charAt(k) == '1') one++; else zero++; 46 | // If one is greater than zero, add total length scanned till now 47 | if (one > zero) 48 | dp[start] = Math.max(dp[start], find(k + 1, adj, n, dp) + k - start + 1); 49 | 50 | // Continue with next length 51 | else 52 | dp[start] = Math.max(dp[start], find(k + 1, adj, n, dp)); 53 | } 54 | 55 | return dp[start]; 56 | } 57 | 58 | public static void main (String[] args){ 59 | String adj = "100110001010001"; 60 | 61 | // Size of string 62 | int n = adj.length(); 63 | int dp[] = new int[n + 1]; 64 | Arrays.fill(dp, -1); 65 | 66 | System.out.println(find(0, adj, n, dp)); 67 | } 68 | } -------------------------------------------------------------------------------- /java/arrays/seperate0and1s.java: -------------------------------------------------------------------------------- 1 | // Segregate 0s and 1s in an array 2 | // You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. 3 | 4 | // Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 5 | // Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 6 | 7 | class GFG { 8 | // function to segregate 0s and 1s 9 | static void segregate0and1(int arr[], int n){ 10 | int count = 0; // counts the no of zeros in array 11 | for (int i = 0; i < n; i++) { 12 | if (arr[i] == 0) 13 | count++; 14 | } 15 | // loop fills the array with 0 until count 16 | for (int i = 0; i < count; i++) 17 | arr[i] = 0; 18 | // loop fills remaining arr space with 1 19 | for (int i = count; i < n; i++) 20 | arr[i] = 1; 21 | } 22 | 23 | static void print(int arr[], int n){ 24 | System.out.print("Array after segregation is "); 25 | for (int i = 0; i < n; i++) 26 | System.out.print(arr[i] + " "); 27 | } 28 | 29 | public static void main(String[] args){ 30 | int arr[] = new int[]{ 0, 1, 0, 1, 0, 0, 1, 1, 1, 0 }; 31 | int n = arr.length; 32 | segregate0and1(arr, n); 33 | print(arr, n); 34 | } 35 | } -------------------------------------------------------------------------------- /java/arrays/splitArrayWithEqualSums.java: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Facebook. 3 | 4 | Given an array of integers greater than zero, find if it is possible to split it in two subarrays 5 | (without reordering the elements), such that the sum of the two subarrays is the same. 6 | Print the two subarrays. 7 | 8 | Examples : 9 | 10 | Input : Arr[] = { 1 , 2 , 3 , 4 , 5 , 5 } 11 | Output : { 1 2 3 4 } 12 | { 5 , 5 } 13 | 14 | Input : Arr[] = { 1 , 2 ,3 , 4 } 15 | Output : Not Possible 16 | */ 17 | 18 | import java.util.Scanner; 19 | 20 | class Array{ 21 | public static int findSplitPoint(int array[],int n){ 22 | int leftSum = 0; 23 | for(int i=0;i high) { 11 | return - 1; 12 | } 13 | 14 | int middle = low + ((high-low)/2); 15 | if(arr[middle] == n) return middle; 16 | 17 | else if(n > arr[middle]) { 18 | return recursiveBinarySearch(arr, n, middle+1, high); 19 | 20 | } else return recursiveBinarySearch(arr, n, low, middle-1); 21 | } 22 | 23 | /* 24 | * Binary Search using iteration 25 | * Time complexity - Olog(n) 26 | * Memory Complexity - Constant, O(1) 27 | * */ 28 | private static int iterativeBinarySearch(int[]arr, int n, int low, int high) { 29 | while (low <= high) { 30 | int middle = low + ((high-low)/2); 31 | if(arr[middle] == n) return middle; 32 | 33 | if(n > arr[middle]) { 34 | low = middle+1; 35 | } else { 36 | high = middle-1; 37 | } 38 | } 39 | return -1; 40 | } 41 | 42 | 43 | public static void main(String[] args) { 44 | int[] arr = {1,11,23,34,45,56,67,78,89,90}; 45 | int n = 90; 46 | System.out.println(recursiveBinarySearch(arr, n, 0, arr.length-1)); 47 | System.out.println(iterativeBinarySearch(arr, n, 0, arr.length-1)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/search/RotatedBinarySearch.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | public class RotatedBinarySearch { 4 | /* 5 | * Binary Search using recursion 6 | * Time complexity - Olog(n) 7 | * Memory Complexity - O(logn) - as it will consume memory on the stack 8 | * */ 9 | public static int rotatedBinarySearch(int[] arr, int n, int low, int high) { 10 | if(low > high) return -1; 11 | 12 | int middle = low + ((high-low)/2); 13 | if(arr[middle] == n) return middle; 14 | 15 | /* 16 | * Step 1: check if the n value is less than the middle value 17 | * Step 2: Check if the first value is less than the middle value 18 | * Step 3: Check if the first value is less than the n value 19 | * */ 20 | if(n < arr[middle] && arr[low] < arr[middle] && n>= arr[low]) { 21 | return rotatedBinarySearch(arr, n, low, middle-1); 22 | 23 | /* 24 | * Step 1: check if the n value is greater than the middle value 25 | * Step 2: Check if the middle value is less than the highest value 26 | * Step 3: Check if the highest value is <= the n value 27 | * */ 28 | 29 | } else if(n > arr[middle] && arr[middle] < arr[high] && n <= arr[high]) { 30 | return rotatedBinarySearch(arr, n, middle+1, high); 31 | 32 | /* 33 | * Step 1: check if the first value is greater than the middle value 34 | * */ 35 | 36 | } else if(arr[low] > arr[middle]) { 37 | return rotatedBinarySearch(arr, n, low, middle-1); 38 | 39 | /* 40 | * Step 1: check if the last value is less than the middle value 41 | * */ 42 | } else if(arr[high] < arr[middle]) { 43 | return rotatedBinarySearch(arr, n, middle+1, high); 44 | } 45 | 46 | return -1; 47 | } 48 | 49 | 50 | public static void main(String[] args) { 51 | int[] arr = {5, 6, 7, 8, 9, 10, 1, 2, 3}; 52 | int n = 3; 53 | System.out.println(rotatedBinarySearch(arr, n, 0, arr.length-1)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /java/search/TernarySearch.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | public class TernarySearch { 4 | /* 5 | * Ternary Search using recursion 6 | * Time complexity - Olog(n) 7 | * Memory Complexity - O(logn) - as it will consume memory on the stack 8 | * 9 | * Ternary search is a fast search algorithm which works on the principle of divide & conquer. 10 | * It splits an array into three smaller arrays by finding the median value in the array. 11 | * The two different medians are found by adding the median value to the lowerIndex and by subtracting the upperIndex 12 | * by the median. If the value is greater than the median then the lower bound of the array is increased and if the value is less than the median then the upper bound of the array is decreased. 13 | * It can be used only for sorted arrays. 14 | * Ternary search reduces the array into half thus reducing the count of comparisons to be made 15 | * 16 | * */ 17 | public static int ternarySearch(int n, int[] arr, int lowerIndex, int upperIndex) { 18 | if(n < arr[lowerIndex] || n > arr[upperIndex]) return -1; 19 | 20 | int median = (upperIndex - lowerIndex) / 3; 21 | int med1 = lowerIndex + median; 22 | int med2 = upperIndex - median; 23 | 24 | if(arr[med1] == n) return med1; 25 | if(arr[med2] == n) return med2; 26 | 27 | if(arr[med1] < n) return ternarySearch(n, arr, med1+1, upperIndex); 28 | if(arr[med2] > n) return ternarySearch(n, arr, lowerIndex, med2-1); 29 | 30 | return -1; 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] arr = {1,11,23,34,45,56,67,78,89,90}; 35 | int n = 90; 36 | System.out.println(ternarySearch(n, arr, 0, arr.length-1)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BubbleSort { 6 | /* 7 | * 1. Bubble sort is the simplest sorting algorithm that compares two adjacent elements in an array and swaps the largest of the two values to the end. 8 | * 2. The worst case time complexity of bubble sort is O(n2): this is because for each iteration n-1 comparisons will be done. 9 | * 3. The best case time complexity will be O(n): this is when the list is already sorted 10 | * 4. The space time complexity will be O(1): since only one memory space is required for the temp variable. 11 | * 12 | * Key Points 13 | * -> Bubble sort is in place and stable sorting algorithm. 14 | * */ 15 | public static int[] bubbleSort(int[] arr) { 16 | if(arr.length == 1) return arr; 17 | 18 | for(int i=0; i arr[j+1]) { 22 | int temp = arr[j]; 23 | arr[j] = arr[j+1]; 24 | arr[j+1] = temp; 25 | } 26 | } 27 | } 28 | return arr; 29 | } 30 | 31 | 32 | public static void main(String[] args) { 33 | int[] arr = {55, 23, 26, 2, 25}; 34 | System.out.print(Arrays.toString(bubbleSort(arr))); 35 | } 36 | } 37 | /* 38 | The above function always runs O(n^2) time even if the array is sorted. 39 | It can be optimized by stopping the algorithm if inner loop didn’t cause any swap. 40 | // An optimized version of Bubble Sort 41 | static void bubbleSort(int arr[], int n) 42 | { 43 | int i, j, temp; 44 | boolean swapped; 45 | for (i = 0; i < n - 1; i++) 46 | { 47 | swapped = false; 48 | for (j = 0; j < n - i - 1; j++) 49 | { 50 | if (arr[j] > arr[j + 1]) 51 | { 52 | // swap arr[j] and arr[j+1] 53 | temp = arr[j]; 54 | arr[j] = arr[j + 1]; 55 | arr[j + 1] = temp; 56 | swapped = true; 57 | } 58 | } 59 | 60 | // IF no two elements were 61 | // swapped by inner loop, then break 62 | if (swapped == false) 63 | break; 64 | } 65 | }*/ 66 | -------------------------------------------------------------------------------- /java/sort/InsertSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdithyaBhat17/interview-cookbook/ed0214f4382cb5afbc4125d84155a0e1b5baebb6/java/sort/InsertSort.class -------------------------------------------------------------------------------- /java/sort/InsertSort.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class InsertSort { 6 | /* 7 | * Insertion sort compares the current element with the element on the left. 8 | * If it is found to be smaller it is swapped with the element on the left. 9 | * Worst Case Time Complexity : O(n^2) - When elements are sorted in reverse order. 10 | * Best Case Time Complexity : O(n) - When elements are already sorted. 11 | * Average Time Complexity : O(n^2) 12 | * Space Complexity : O(1) 13 | * This makes it inefficient to operate on larger datasets 14 | * 15 | * Key Points 16 | * -> Insertion Sort is in place sorting algorithm. 17 | * -> It is a stable sorting algorithm. 18 | * */ 19 | public static int[] insertionSort(int[] arr) { 20 | if(arr.length == 1) return arr; 21 | 22 | for(int i=1; i0; j--) { 25 | if(arr[j] < arr[j-1]) { 26 | int temp = arr[j]; 27 | arr[j] = arr[j-1]; 28 | arr[j-1] = temp; 29 | } 30 | } 31 | } 32 | 33 | return arr; 34 | } 35 | 36 | public static void main(String[] args) { 37 | int[] arr = {55, 23, 26, 2, 25}; 38 | System.out.print(Arrays.toString(insertionSort(arr))); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /java/sort/MergeSort.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MergeSort { 6 | /* 7 | * Merge sort uses divide & conquer method by splitting the array into smaller parts until there is only one element. 8 | * The elements are then compared and sorted and merged. 9 | * Split the arr into half by finding the median. 10 | * Call mergeSort on the first half and mergeSort on the second half. Then merge the two halves. 11 | * The time complexity of merge sort is always O(n log n): in all 3 cases (worst, average and best) as merge sort 12 | * always divides the array in two halves and take linear time to merge two halves. 13 | * 14 | * Key Points 15 | * -> Merge Sort unlike Quick Sort is not in place sorting algorithm. 16 | * -> Merge Sort is stable. 17 | * -> Merge Sort is better when data is huge and stored on external storage. 18 | * -> Merge Sort requires O(N) extra storage, N being the array size. 19 | * */ 20 | public static int[] mergeSort(int[] arr, int lowerIndex, int upperIndex) { 21 | if(arr.length == 1) return arr; 22 | if(lowerIndex >= upperIndex) return arr; 23 | 24 | int median = (lowerIndex + upperIndex)/2; 25 | mergeSort(arr, lowerIndex, median); 26 | mergeSort(arr, median+1, upperIndex); 27 | merge(arr, lowerIndex, median, upperIndex); 28 | 29 | return arr; 30 | } 31 | 32 | public static int[] merge(int[]arr, int lowerIndex, int median, int upperIndex) { 33 | int[] tempArr = new int[arr.length]; 34 | 35 | for(int i=0; i<= upperIndex; i++) { 36 | tempArr[i] = arr[i]; 37 | } 38 | 39 | int i = lowerIndex; 40 | int j = median+1; 41 | int k = lowerIndex; 42 | 43 | while (i <= median && j<= upperIndex) { 44 | if(tempArr[i] < tempArr[j]) { 45 | arr[k] = tempArr[i]; 46 | i++; 47 | 48 | } else { 49 | arr[k] = tempArr[j]; 50 | j++; 51 | } 52 | k++; 53 | } 54 | 55 | while (i<= median) { 56 | arr[k] = tempArr[i]; 57 | i++; 58 | k++; 59 | } 60 | 61 | return arr; 62 | } 63 | 64 | 65 | public static void main(String[] args) { 66 | int[] arr = {55, 23, 26, 2, 25}; 67 | System.out.print(Arrays.toString(mergeSort(arr, 0, arr.length-1))); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /java/sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class QuickSort { 6 | /* 7 | * Given an integer array, sort it in ascending order using quicksort. 8 | * 9 | * Runtime Complexity 10 | * ->Best Case :- When middle element is chosen as pivot. O(nLogn) 11 | * ->Average Case :- O(nLogn) 12 | * ->Worst Case: - When the pivot element is largest or smallest in the array. 13 | * If last element is chosen as the pivot element then when the array is sorted in ascending or descending order. 14 | * O(n^2). 15 | * 16 | * Memory Complexity - Logarithmic, O(logn). 17 | * Note: Recursive solution has O(logn) memory complexity as it will consume memory on the stack. 18 | * 19 | *Key Points 20 | * -> Quick Sort is faster than many sorting alogrithms like Merge and Heap Sorts. 21 | * -> Default implementation of Quick Sort is not stable. 22 | * -> Quick Sort is in place sorting algorithm therefore doesn't require extra storage. 23 | * -> AKA friendly sorting algorithm as it has a good locality of reference. 24 | * 25 | * Steps 26 | * Step 1: Select a pivot element from the array, usually the first element 27 | * Step 2: Compare the pivot element with the current element. If the current element is less than the pivot, 28 | * shift the current element to the left side and if it is greater than the pivot, shift it to the right 29 | * side of the pivot. 30 | * Step 3: Recursively sort the sublists on the right and left sides of the pivot 31 | * */ 32 | 33 | public static int[] quickSort(int[] arr, int low, int high) { 34 | if(high > low) { 35 | int partitionIndex = partition(arr, low, high); 36 | quickSort(arr, low, partitionIndex-1); 37 | quickSort(arr, partitionIndex+1, high); 38 | } 39 | return arr; 40 | } 41 | 42 | private static int partition(int[]arr, int low, int high) { 43 | int pivot = arr[low]; 44 | int i=low; 45 | int j = high; 46 | 47 | while (i < j) { 48 | while (i<= high && arr[i] <= pivot) { 49 | i++; 50 | } 51 | while (arr[j] > pivot) { 52 | j--; 53 | } 54 | 55 | if(i < j) { 56 | int temp = arr[i]; 57 | arr[i] = arr[j]; 58 | arr[j] = temp; 59 | } else break; 60 | } 61 | 62 | arr[low] = arr[j]; 63 | arr[j] = pivot; 64 | 65 | return j; 66 | } 67 | 68 | 69 | public static void main(String[] args) { 70 | int[] arr = {55, 23, 26, 2, 25}; 71 | System.out.print(Arrays.toString(quickSort(arr, 0, arr.length-1))); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /java/sort/README.md: -------------------------------------------------------------------------------- 1 | # Sort 2 | ## Bubble Sort 3 | Bubble Sort is a 4 | simple sorting algorithm that repeatedly steps through 5 | the list to be sorted, compares each pair of adjacent 6 | items and swaps them if they are in the wrong order. 7 | The pass through the list is repeated until no swaps 8 | are needed, which indicates that the list is sorted. 9 | 10 | ![Algorithm Visualization](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif) 11 | 12 | 13 | ## Insertion Sort 14 | 15 | Insertion sort compares the current element with the element on the left.If it is found to be smaller it is swapped with the element on the left. 16 | 17 | ![Algorithm Visualization](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) 18 | 19 | ## Merge Sort 20 | 21 | Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. 22 | 23 | ![Merge Sort](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif) 24 | 25 | A recursive merge sort algorithm used to sort an array of 7 26 | integer values. These are the steps a human would take to 27 | emulate merge sort (top-down). 28 | 29 | ![Merge Sort](https://upload.wikimedia.org/wikipedia/commons/e/e6/Merge_sort_algorithm_diagram.svg) 30 | 31 | ## Quick Sort 32 | Quick sort is a sorting technique that sequences a list by continuously dividing the list into two parts and moving the lower items to one side and the higher items to the other. It starts by picking one item in the entire list to serve as a pivot point. The pivot could be the first item or a randomly chosen one. All items that compare lower than the pivot are moved to the left of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left side and moves those items to left and right of the pivot and continues the pivot picking and dividing until there is only one item left in the group. It then proceeds to the right side and performs the same operation again. 33 | 34 | ![Quick Sort](https://upload.wikimedia.org/wikipedia/commons/9/9c/Quicksort-example.gif) 35 | 36 | ## Selection sort 37 | 38 | Selection sort is the simplest sorting algorithm. It finds the smallest element in the array and swaps it with the first position in the array. Then the second smallest and swaps it with the second position etc. 39 | 40 | ![Selection Sort](https://upload.wikimedia.org/wikipedia/commons/9/94/Selection-Sort-Animation.gif) 41 | 42 | 43 | 44 | | Algorithm | Time Complexity (best,average,worst) | Space Complexity | 45 | |---------|-------------- |-----------| 46 | |**Bubble Sort**|O(n), O(n2), O(n2)|O(1)| 47 | |**Insertion Sort**|O(n), O(n2), O(n2)|O(1)| 48 | |**Merge Sort**|O(n log(n))|O(n)| 49 | |**Quick Sort**|O(n log(n)), O(n log(n)), O(n2)|O(log(n))| 50 | |**Selection Sort**|O(n2), O(n2), O(n2)|O(1)| 51 | -------------------------------------------------------------------------------- /java/sort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SelectionSort { 6 | /* 7 | * 1. Selection sort is the simplest sorting algorithm. It finds the smallest element in the array and swaps it with the first position in the array. Then the second smallest and swaps it with the second position etc. 8 | * 2. Worst Case Time Complexity : O(n^2) 9 | * 3. Best Case Time Complexity : O(n^2) 10 | * 4. Average Time Complexity : O(n^2) 11 | * 5. Space Complexity : O(1) 12 | * This makes it inefficient to operate on larger datasets 13 | * 14 | * Key Points 15 | * -> Default implementation is not stable. 16 | * -> In place sorting algorithm. 17 | * */ 18 | public static int[] selectionSort(int[] arr) { 19 | if(arr.length == 1) return arr; 20 | 21 | for(int i=0; i< arr.length; i++) { 22 | int index = i; 23 | 24 | for(int j=i+1; j< arr.length; j++) { 25 | if(arr[j] < arr[index]) { 26 | index = j; 27 | } 28 | } 29 | int smallestNumber = arr[index]; 30 | arr[index] = arr[i]; 31 | arr[i] = smallestNumber; 32 | } 33 | 34 | return arr; 35 | } 36 | 37 | 38 | public static void main(String[] args) { 39 | int[] arr = {55, 23, 26, 2, 25}; 40 | System.out.print(Arrays.toString(selectionSort(arr))); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/strings/Anagram.java: -------------------------------------------------------------------------------- 1 | public class Anagram { 2 | /* 3 | * Input: "Keep", "Peek" 4 | * Output: false 5 | * */ 6 | public static boolean checkIfAnagram(String word1, String word2) { 7 | char[] cArr1 = word1.toCharArray(); 8 | char[] cArr2 = word2.toCharArray(); 9 | 10 | int n1 = cArr1.length; 11 | int n2 = cArr2.length; 12 | 13 | if(n1 != n2) return false; 14 | 15 | quickSort(cArr1, 0, n1-1); 16 | quickSort(cArr2, 0, n2-1); 17 | 18 | for(int i=0; i= k+2) { 33 | // You have spare changes. Change one or both (or neither!) to '9' 34 | } else (minChanges == k+1) { 35 | // You can make one extra change. If the digits are different, then change the smaller 36 | // to match the larger. 37 | } 38 | */ 39 | 40 | class Palindrome{ 41 | public static String maxPalindrome(String str, int k){ 42 | char[] c = str.toCharArray(); 43 | int minChange = 0; 44 | for(int i=0,j=c.length-1;i k) 49 | return "-1"; 50 | 51 | int changeBoth = k - minChange; 52 | int i = 0; 53 | int j =c.length - 1; 54 | for(;i<=j;i++,j--){ 55 | if(c[i] != c[j]){ 56 | char maxChar = (char) Math.max(c[i],c[j]); 57 | if(maxChar != '9' && changeBoth - 1 >= 0){ 58 | c[i] = '9'; 59 | c[j] = '9'; 60 | changeBoth--; 61 | } 62 | else{ 63 | c[i] = maxChar; 64 | c[j] = maxChar; 65 | minChange--; 66 | } 67 | } 68 | else{ 69 | char maxChar = (char) Math.max(c[i], c[j]); 70 | if (maxChar != '9' && changeBoth - 2 >= 0) { 71 | c[i] = '9'; 72 | c[j] = '9'; 73 | changeBoth -= 2; 74 | } 75 | } 76 | } 77 | if (changeBoth != 0 && i - 1 == j + 1) { 78 | c[i - 1] = '9'; 79 | } 80 | String result = new String(c); 81 | return result; 82 | } 83 | public static void main(String[] args) { 84 | Scanner in = new Scanner(System.in); 85 | int n = in.nextInt(); 86 | int k = in.nextInt(); 87 | String str = in.next(); 88 | System.out.println(maxPalindrome(str, k)); 89 | } 90 | } -------------------------------------------------------------------------------- /java/strings/NextHighestPermutation.java: -------------------------------------------------------------------------------- 1 | public class NextHighestPermutation { 2 | 3 | /* 4 | * Find next highest permutation of a given string. 5 | * Input: "abbc" 6 | * Output: "abcb" 7 | * Follow same logic as finding the next Highest integer from a given integer 8 | * */ 9 | public static String permutateString(String s) { 10 | char[] c = s.toCharArray(); 11 | 12 | int a = 0; 13 | int n = c.length; 14 | for(int i=n-1; i>0; i--) { 15 | if(c[i] > c[i-1]) { 16 | a = i; 17 | break; 18 | } 19 | } 20 | 21 | if(a == 0) return "No permutations"; 22 | 23 | int num = c[a-1]; 24 | int min = a; 25 | for(int i=a+1; i num && c[i] < c[min]) { 27 | min = i; 28 | } 29 | } 30 | 31 | char temp = c[min]; 32 | c[min] = c[a-1]; 33 | c[a-1] = temp; 34 | 35 | return new String(c); 36 | } 37 | 38 | 39 | 40 | public static void main(String[] args) { 41 | String input = "abbc"; 42 | System.out.println(permutateString(input)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java/strings/PalindroneStrings.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class PalindroneStrings { 5 | 6 | /* 7 | * Given a string find all substrings that are palindromes. 8 | * Input - "aabbbaa" 9 | * Output - aa, bb, bbb, abbba, aabbbaa, bb,aa 10 | * */ 11 | 12 | 13 | /* 14 | * A naive solution of this problem is to find all substrings of a given string and check whether each substring 15 | * is a palindrome or not. This solution has a complexity of O(n3). 16 | * 17 | * We can reduce the runtime of this algorithm to O(n2) by using the following approach. 18 | * For each letter in the input string, start expanding to left and right while checking for even and 19 | * odd length palindromes. Move to the next letter if we know a palindrome doesn't exist. 20 | * We expand one character to the left and right and compare them. If both of them are equal, 21 | * we print out the palindrome substring. 22 | * */ 23 | 24 | /* 25 | * Runtime Complexity - Polynomial, O(n2). 26 | * Memory Complexity - Constant, O(1). 27 | * 28 | * */ 29 | public static List findAllPalindromesInString(String input) { 30 | List words = new ArrayList<>(); 31 | for(int i=0; i findPalindromeInSubString(String input, int start, int end) { 39 | List words = new ArrayList<>(); 40 | for(;start >=0 && end 1 && pattern.charAt(1) == '*') { 26 | 27 | String remainingPattern = pattern.substring(2); 28 | String remainingText = text; 29 | 30 | for (int i = 0; i < text.length() + 1; ++i) { 31 | 32 | if (isRegexMatch(remainingText, remainingPattern)) { 33 | return true; 34 | } 35 | 36 | if (remainingText.isEmpty()) { 37 | return false; 38 | } 39 | 40 | if (pattern.charAt(0) != '.' && remainingText.charAt(0) != pattern.charAt(0)) { 41 | return false; 42 | } 43 | 44 | remainingText = remainingText.substring(1); 45 | } 46 | } 47 | 48 | if(text.isEmpty() || pattern.isEmpty()) { 49 | return false; 50 | } 51 | 52 | if(pattern.charAt(0) == '.' || pattern.charAt(0) == text.charAt(0)) { 53 | String remainingText = ""; 54 | if (text.length() >= 2) { 55 | remainingText = text.substring(1); 56 | } 57 | 58 | String remainingPattern = ""; 59 | if (pattern.length() >= 2) { 60 | remainingPattern = pattern.substring(1); 61 | } 62 | 63 | return isRegexMatch(remainingText, remainingPattern); 64 | } 65 | 66 | return false; 67 | } 68 | 69 | 70 | static boolean regexMatch(String text, String pattern) { 71 | return isRegexMatch(text, pattern); 72 | } 73 | 74 | 75 | public static void main(String[] args) { 76 | String input = "aabbbbbcdda"; 77 | String pattern = "a*bb*cdda"; // -> true 78 | // String pattern = "a*b*c*da"; // -> false 79 | System.out.println(regexMatch(input, pattern)); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /java/strings/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedHashSet; 2 | import java.util.Set; 3 | 4 | public class RemoveDuplicates { 5 | 6 | 7 | /* 8 | * Given a string that contains duplicate occurrences of characters, remove these duplicate occurrences 9 | * Eg. Input: "abbabcddbabcdeedebc" 10 | * Output: "abcde" 11 | * 12 | * Why to use LinkedHashSet instead of HashSet in this case? 13 | * A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of HashSet. 14 | * The only difference between HashSet and LinkedHashSet is that LinkedHashSet maintains the insertion order. 15 | * When we iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet. 16 | * The reason why LinkedHashSet maintains insertion order is because the underlying data structure is a doubly-linked list. 17 | * 18 | * */ 19 | public static String removeDuplicates(String s) { 20 | Set characterSet = new LinkedHashSet<>(); 21 | char[] charArr = s.toCharArray(); 22 | 23 | for(char c: charArr) { 24 | characterSet.add(c); 25 | } 26 | 27 | StringBuilder sb = new StringBuilder(); 28 | for (Character character : characterSet) { 29 | sb.append(character); 30 | } 31 | return sb.toString(); 32 | } 33 | 34 | 35 | // this solution uses extra memory 36 | // to keep all characters present in string. 37 | 38 | // Null terminating strings are not used in Java. 39 | // For this question, assume that you are passed a 40 | // null terminated string (array of characters). 41 | /* 42 | * Runtime Complexity - Linear O(n). 43 | * Memory Complexity - Linear, O(n). 44 | * */ 45 | public static void removeDuplicates1(char[] str){ 46 | Set hashSet = new LinkedHashSet<>(); 47 | 48 | int write_index = 0; 49 | int read_index = 0; 50 | 51 | while (str[read_index] != '\0') { 52 | 53 | if(!hashSet.contains(str[read_index])) { 54 | 55 | hashSet.add(str[read_index]); 56 | str[write_index] = str[read_index]; 57 | ++write_index; 58 | } 59 | 60 | ++read_index; 61 | } 62 | 63 | str[write_index] = '\0'; 64 | } 65 | 66 | 67 | 68 | // this solution does not require any extra memory 69 | // but runs in O(n^2) time 70 | 71 | // Null terminating strings are not used in Java. 72 | // For this question, assume that you are passed a 73 | // null terminated string (array of characters). 74 | public static void removeDuplicates2(char[] str){ 75 | if(str == null || str.length == 0) { 76 | return; 77 | } 78 | 79 | int write_index = 0; 80 | for(int i = 0; i < str.length; i++) { 81 | boolean found = false; 82 | 83 | for(int j = 0; j < write_index; j++) { 84 | if(str[i] == str[j]) { 85 | found = true; 86 | break; 87 | } 88 | } 89 | 90 | if(!found) { 91 | str[write_index] = str[i]; 92 | write_index++; 93 | } 94 | } 95 | 96 | str[write_index] = '\0'; 97 | } 98 | 99 | 100 | public static void main(String[] args) { 101 | String string = "abbabcddbabcdeedebc"; 102 | System.out.println(removeDuplicates(string)); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /java/strings/RemoveWhiteSpaces.java: -------------------------------------------------------------------------------- 1 | public class RemoveWhiteSpaces { 2 | 3 | 4 | /* 5 | * Given a null terminated string, remove any white spaces (tabs or spaces). 6 | * Eg: Input - "All greek to me." 7 | * Output - "Allgreektome" 8 | * 9 | * Runtime Complexity - Linear, O(n). 10 | * Memory Complexity - Constant, O(1). 11 | * 12 | * */ 13 | public static String removeWhiteSpaces(String s) { 14 | char[] arr = s.toCharArray(); 15 | int readIndex = 0; 16 | String result = ""; 17 | 18 | while (readIndex < arr.length && arr[readIndex] != '\0') { 19 | if(arr[readIndex] != ' ' && arr[readIndex] != '\t') { 20 | result += arr[readIndex]; 21 | } 22 | ++readIndex; 23 | } 24 | 25 | return result; 26 | } 27 | 28 | 29 | public static void main(String[] args) { 30 | String string = " All greek to me. \n"; 31 | System.out.println(removeWhiteSpaces(string)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | public class ReverseString { 2 | 3 | 4 | /* 5 | * Reverse characters in a sentence 6 | * Eg: "Hello World" -> "dlroW olleH" 7 | * 8 | * */ 9 | 10 | public static String reverseString(String s) { 11 | String reverse = ""; 12 | 13 | char[] charArr = s.toCharArray(); 14 | for(int c = charArr.length-1; c>=0; c--) { 15 | reverse += charArr[c]; 16 | } 17 | return reverse; 18 | } 19 | 20 | 21 | /* 22 | * Reverse words in a sentence 23 | * Eg: "Hello World" -> "World Hello" 24 | * 25 | * Linear, O(n) - Position of all the elements in the sentence is changed. 26 | * Memory Complexity - Constant, O(1). The solution reverses every word in-place i.e. 27 | * it does not require any extra space. 28 | * 29 | * */ 30 | 31 | 32 | /* 33 | * This solution of using a String called 'reverse' would affect performance if the string is really long. 34 | * Since string is immutable, every word added to the reverse String creates a new object. So if we have a really 35 | * long sentence, and we split that sentence & store in an array, (size of array n = 1Million, then for each iteration 36 | * a new string object would be created. 37 | * In order to address this issue, StringBuilder/StringBuffer can be used. They are mutable. 38 | * Difference between StringBuilder & StringBuffer - StringBuilder is not thread safe whereas StringBuffer is 39 | * thread-safe. 40 | * http://www.techtamasha.com/difference-between-string-and-stringbufferstringbuilder-in-java/28 41 | * */ 42 | 43 | public static StringJoiner reverseWord(String s){ 44 | String [] arr = s.split("\\s+");// 45 | StringJoiner mStringJoiner = new StringJoiner(" "); 46 | int numberOfWords = arr.length; 47 | for(int i = numberOfWords - 1; i >= 0; i--) 48 | mStringJoiner.add(arr[i]); 49 | return mStringJoiner; 50 | } 51 | 52 | /* 53 | *"\\s+" will split even if there is more than one space between two words. 54 | *StringJoiner works only in Java 8. 55 | *Pass the delimeter to the constructor while creating the StringJoiner object. 56 | *Add words using add() of StringJoiner class. 57 | *Here I have returned the StringJoiner object. 58 | *On printing, the toString() of Object class gets called and the reversed String gets printed. 59 | Note : If there is no support of Java 8 then use the function below but it will print the extra delimeter at the end of the sentence. 60 | So care has to be taken to remove it. 61 | * */ 62 | 63 | /*public static String reverseWord(String s) { 64 | String reverse = ""; 65 | 66 | String[] arr = s.split(" "); 67 | for(int i=arr.length-1; i>=0; i--) { 68 | reverse += arr[i] + " "; 69 | } 70 | 71 | return reverse; 72 | }*/ 73 | 74 | 75 | public static void main(String[] args) { 76 | String string = "The quick brown fox jumped over the lazy dog."; 77 | System.out.println(reverseString(string)); 78 | System.out.println(reverseWord(string)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /java/strings/StringMultiplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Delta X 3 | 4 | Given two strings,Multiply each letter's positional value (i.e A=1,B=2,..,Z=26) with other letters within the string. 5 | After performing the multiplication,apply mod(47) to the values and return "SAME" if both values else return "NOT SAME". 6 | 7 | Example: 8 | Input : string 1 = ABC 9 | string 2 = XYZ 10 | 11 | Output : NOT SAME 12 | */ 13 | 14 | import java.util.Scanner; 15 | 16 | class StringMultiplication { 17 | public static int convertToAscii(String s){ 18 | char[] ch = s.toCharArray(); 19 | int result = 1; 20 | for(char c : ch){ 21 | int character = (int)c; // returns ascii value of each character. 22 | int ascii = 64; //for upper case 23 | if(character >= 65 && character <= 90) 24 | result *= (character-ascii); 25 | } 26 | return result%47; 27 | } 28 | public static void main (String[] args) { 29 | Scanner sc = new Scanner(System.in); 30 | String s1 = sc.next(); 31 | String s2 = sc.next(); 32 | int number1 = convertToAscii(s1.toUpperCase()); 33 | int number2 = convertToAscii(s2.toUpperCase()); 34 | System.out.println(number1+","+number2); 35 | if(number1 == number2) 36 | System.out.println("SAME"); 37 | else 38 | System.out.println("NOT SAME"); 39 | } 40 | } -------------------------------------------------------------------------------- /java/strings/StringSegmentation.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | public class StringSegmentation { 5 | 6 | /* 7 | * Given a dictionary of words and an input string tell whether the input string can be completely 8 | * segmented into dictionary words 9 | * Eg: Input - Set dict = [hello, hell, on, now], String s = "hellonow" 10 | * Output - Can "hellonow" be segmented into Hello & now? - true or false 11 | * 12 | * Runtime Complexity - Polynomial, O(n2). 13 | * Memory Complexity - Polynomial, O(n2). Memory Complexity is O(n2), because we create substring on each recursion 14 | * call. 15 | * 16 | * We are using memorization - remembering the already solved substrings, so we don't go about solving them again. 17 | * This will reduce the runtime of the algorithm to O(n2) 18 | * 19 | * */ 20 | public static boolean canBeSegmented(Set firstDict, 21 | Set secondDict, 22 | String s) { 23 | 24 | for(int i=1; i firstDict = new HashSet<>(); 50 | firstDict.add("apple"); 51 | firstDict.add("pear"); 52 | firstDict.add("pier"); 53 | firstDict.add("pie"); 54 | 55 | Set secondDict = new HashSet<>(); 56 | String string = "pearpie"; 57 | System.out.println(canBeSegmented(firstDict,secondDict, string)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /java/strings/SubstringSmallestWindow.java: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Streamoid technologies, Amazon, MakeMyTrip 3 | 4 | Find the smallest window in a string containing all characters of another string 5 | Given two strings string1 and string2, find the smallest substring in string1 containing 6 | all characters of string2 efficiently. 7 | 8 | 9 | For Example: 10 | 11 | Input : string = "this is a test string" 12 | pattern = "tist" 13 | Output : Minimum window is "t stri" 14 | Explanation: "t stri" contains all the characters 15 | of pattern. 16 | 17 | Input : string = "geeksforgeeks" 18 | pattern = "ork" 19 | Output : Minimum window is "ksfor" 20 | */ 21 | 22 | // Algorithm: credits(geeksforgeeks) 23 | // 1- First check if length of string is less than 24 | // the length of given pattern, if yes 25 | // then "no such window can exist ". 26 | // 2- Store the occurrence of characters of given 27 | // pattern in a hash_pat[]. 28 | // 3- Start matching the characters of pattern with 29 | // the characters of string i.e. increment count 30 | // if a character matches 31 | // 4- Check if (count == length of pattern ) this 32 | // means a window is found 33 | // 5- If such window found, try to minimize it by 34 | // removing extra characters from beginning of 35 | // current window. 36 | // 6- Update min_length. 37 | // 7- Print the minimum length window. 38 | 39 | import java.util.*; 40 | 41 | class Strings{ 42 | public static String findSubstring(String string,String pattern){ 43 | int len1 = string.length(); 44 | int len2 = pattern.length(); 45 | 46 | if(len1 < len2){ //step 1. 47 | System.out.println("No such window can exist"); 48 | return ""; 49 | } 50 | 51 | int hash_str[] = new int[256]; 52 | int hash_pat[] = new int[256]; 53 | 54 | //step 2. 55 | for(int i=0;i hash_pat[string.charAt(start)] || hash_pat[string.charAt(start)] == 0){ 71 | if(hash_str[string.charAt(start)] > hash_pat[string.charAt(start)] || hash_pat[string.charAt(start)] == 0) 72 | hash_str[string.charAt(start)]--; 73 | start++; 74 | } 75 | //step 6. 76 | int length_window = j - start + 1; 77 | if(min_length > length_window){ 78 | min_length = length_window; 79 | start_index = start; 80 | } 81 | } 82 | } 83 | if(start_index == -1){ 84 | System.out.println("No such window exists"); 85 | return ""; 86 | } 87 | // step 7 88 | return string.substring(start_index,start_index + min_length); 89 | } 90 | public static void main(String args[]){ 91 | String str = "this is a test string"; 92 | String pat = "tist"; 93 | System.out.print("Smallest window is : " + findSubstring(str, pat)); 94 | } 95 | } -------------------------------------------------------------------------------- /java/strings/countAnagrams.java: -------------------------------------------------------------------------------- 1 | // Given a word and a text, return the count of occurences of anagrams of the word in the text(For eg: anagrams of word for are for, ofr, rof etc.) 2 | // For example : 3 | // Input: forxxorfxdofr 4 | // for 5 | // Output: 3 6 | 7 | import java.util.*; 8 | import java.io.*; 9 | 10 | class Anagrams{ 11 | final static int MAX = 256; 12 | // to check if two strings are equal. 13 | static boolean isAnagram(String s1, String s2){ 14 | char[] c1 = s1.toCharArray(); 15 | char[] c2 = s2.toCharArray(); 16 | Arrays.sort(c1); 17 | Arrays.sort(c2); 18 | if(Arrays.equals(c1, c2)) 19 | return true; 20 | return false; 21 | } 22 | 23 | static int countAnagrams(String text, String word){ 24 | int N = text.length(); 25 | int n = word.length(); 26 | int res = 0; 27 | for(int i=0;i<=N-n;i++){ 28 | String s = text.substring(i, i+n); 29 | if(isAnagram(word, s)) 30 | res++; 31 | } 32 | return res; 33 | } 34 | 35 | public static void main(String args[]){ 36 | String text = "forxxorfxdofr"; 37 | String word = "for"; 38 | System.out.println(countAnagrams(text, word)); 39 | } 40 | } -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/LargestNumberFormedByAnArray.js: -------------------------------------------------------------------------------- 1 | /* 2 | Commonly asked by - PayTM, Amazon, MakeMyTrip, OneDirect. 3 | 4 | Given a list of non negative integers, arrange them in such a manner that they form the largest number possible. 5 | 6 | The result is going to be very large, hence return the result in the form of a string. 7 | 8 | Example : 9 | Input - array = [3, 30, 34, 5, 9] 10 | Output - `9534330` (returned as a string). 11 | */ 12 | 13 | const largestNumber = (array) => { 14 | let number =[] 15 | let result = '' 16 | for(let i=0;i { 19 | let leftToRight = a + b 20 | let rightToLeft = b + a 21 | if(leftToRight > rightToLeft) 22 | return -1 23 | if(leftToRight < rightToLeft) 24 | return 1 25 | return 0 26 | }) 27 | for(let i=0;i { 34 | let maxSize = -1 35 | let start = 0 36 | for(let i=0;i maxSize){ 50 | maxSize = j-i+1 51 | start = i 52 | } 53 | } 54 | } 55 | return `start index is ${start} and ends at ${maxSize+start-1}.The size is ${maxSize}` 56 | } 57 | 58 | maxLen([1,1,0,1,0],5) 59 | 60 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/MissingNumber.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size n-1 and given that there are numbers from 1 to n with one missing, the missing number is to be found. 3 | 4 | Example: 5 | 6 | Input 7 | 8 | 1 2 3 5 9 | 10 | Output 11 | 4 12 | */ 13 | 14 | const findMissingNumbers = (array) => { 15 | let missingNumbers = [] 16 | array.sort() //sort the array to make sure the elements are in the increasing order 17 | for(let i=1;i { 11 | let frequency = [] 12 | let Sort = [] 13 | let result = [] 14 | array.forEach((value) => { 15 | if(value in frequency) 16 | frequency[value]++ 17 | else 18 | frequency[value] = 1 19 | }) 20 | for(let key in frequency) 21 | Sort.push([key, frequency[key]]) 22 | Sort.sort((a,b) => b[1] - a[1]) 23 | Sort.forEach((obj) => { 24 | for(let i=0;i { 12 | let count = 0 13 | for(let start=0;start tomorrow's price. 46 | if (i < days && prices[i] > prices[i + 1]) i++; 47 | 48 | buy = prices[i]; 49 | 50 | // avoid selling shares if the current price <= tomorrow's price. 51 | if (i < days && prices[i] <= prices[i + 1]) i++; 52 | 53 | sell = prices[i]; 54 | 55 | profit += sell - buy; 56 | } 57 | 58 | return profit; 59 | } 60 | 61 | // Approach 2: 62 | // Here we don't keep track of the purchases and just assume that stock was purchased 63 | // the previous day before selling only if the selling price is greater than buying price. 64 | function maxProfit(prices) { 65 | let profit = 0; 66 | for (let i = 1; i < prices.length; i++) { 67 | if (prices[i] > prices[i - 1]) { 68 | profit += prices[i] - prices[i - 1]; 69 | } 70 | } 71 | 72 | return profit; 73 | } 74 | 75 | maxProfit([7, 1, 5, 3, 6, 4]); //? 7 76 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/kadaneAlgorithm.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum. 3 | 4 | Input: 5 | The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. 6 | 7 | Output: 8 | Print the maximum sum of the contiguous sub-array in a separate line for each test case. 9 | 10 | Constraints: 11 | 1 ≤ T ≤ 200 12 | 1 ≤ N ≤ 1000 13 | -100 ≤ A[i] <= 100 14 | 15 | Example: 16 | Input 17 | 2 18 | 3 19 | 1 2 3 20 | 4 21 | -1 -2 -3 -4 22 | Output 23 | 6 24 | -1 25 | */ 26 | 27 | const maxSum = (array) => { 28 | let currentMaximum 29 | let globalMaximum 30 | 31 | currentMaximum = globalMaximum =array[0] 32 | 33 | for(let i=0;i globalMaximum) 37 | globalMaximum = currentMaximum 38 | return globalMaximum 39 | } 40 | 41 | const array = [-5,6,3,-2,14] 42 | console.log(maxSum(array)) 43 | 44 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/plusOne.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a non-empty array of digits representing a non-negative integer, increment one to the integer. 4 | 5 | The digits are stored such that the most significant digit is at the head of the list, 6 | and each element in the array contains a single digit. 7 | 8 | You may assume the integer does not contain any leading zero, except the number 0 itself. 9 | 10 | Example 1: 11 | 12 | Input: [1,2,3] 13 | Output: [1,2,4] 14 | Explanation: The array represents the integer 123. 15 | 16 | Example 2: 17 | 18 | Input: [4,3,2,1] 19 | Output: [4,3,2,2] 20 | Explanation: The array represents the integer 4321. 21 | 22 | */ 23 | 24 | /** 25 | * 26 | * @param {number[]} digits 27 | * @returns {number[]} 28 | */ 29 | const plusOne = (digits) => { 30 | const { length } = digits; 31 | for (let index = length - 1; index >= 0; index--) { 32 | // if there's no need of a carry, just add one to the digit and return 33 | if (digits[index] < 9) { 34 | digits[index] += 1; 35 | return digits; 36 | } 37 | // else replace the digit with 0 38 | digits[index] = 0; 39 | } 40 | // if the first element of the array is now 0, add 1 to the start of the array 41 | // example [9] + 1 -> [0] -> [1, 0] 42 | digits.unshift(1); 43 | 44 | return digits; 45 | }; 46 | 47 | plusOne([1, 2, 3]); // [1, 2, 4] 48 | plusOne([4, 3, 2, 1]); // [4, 3, 2, 2] 49 | plusOne([9]); // [1, 0] 50 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/rotate-array.js: -------------------------------------------------------------------------------- 1 | // Rotate an array k times to the right where k is non-negative. 2 | 3 | // Example 4 | // Input -> nums = [1,2,3,4,5,6,7], k =3 5 | // Output -> nums = [5,6,7,1,2,3,4] 6 | 7 | // Approach 1 8 | function rotate(nums, k) { 9 | for (let i = 0; i < k % nums.length; i++) { 10 | let previous = nums[nums.length - 1]; 11 | let temp; 12 | for (let j = 0; j < nums.length; j++) { 13 | temp = nums[j]; 14 | nums[j] = previous; 15 | previous = temp; 16 | } 17 | } 18 | } 19 | 20 | // Approach 2 (Reverse array) 21 | function rotate(nums, k) { 22 | // nums -> [1,2,3,4,5,6,7] 23 | k = k % nums.length; 24 | // reverse the entire array 25 | reverse(nums, 0, nums.length - 1); // nums -> [7,6,5,4,3,2,1] 26 | // reverse the first k members of the array 27 | reverse(nums, 0, k - 1); // nums -> [5,6,7,4,3,2,1] 28 | // reverse the last k members of the array 29 | reverse(nums, k, nums.length - 1); // nums -> [5,6,7,1,2,3,4] 30 | } 31 | 32 | function reverse(nums, start, end) { 33 | let temp; 34 | while (start < end) { 35 | temp = nums[start]; 36 | nums[start] = nums[end]; 37 | nums[end] = temp; 38 | start++; 39 | end--; 40 | } 41 | } 42 | 43 | let num = [1, 2, 3, 4, 5, 6, 7]; 44 | rotate(num, 3); 45 | console.log(num); // [5,6,7,1,2,3,4] 46 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/rotate-image.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 4 | 5 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. 6 | DO NOT allocate another 2D matrix and do the rotation. 7 | 8 | Example 1: 9 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 10 | Output: [[7,4,1],[8,5,2],[9,6,3]] 11 | 12 | Example 2: 13 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 14 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 15 | 16 | Example 3: 17 | Input: matrix = [[1,2],[3,4]] 18 | Output: [[3,1],[4,2]] 19 | 20 | */ 21 | 22 | /** 23 | * Rotates an image clockwise in-place. 24 | * @param {number[][]} image 25 | * @returns void 26 | */ 27 | function rotateImage(image) { 28 | // If we create a transpose of [[1,2],[3,4]] we get [[1,3],[2,4]] 29 | // whereas if we reverse the matrix to [[3,4], [1,2]], the transpose would be [[3,1], [4,2]] 30 | // we could also achieve this by reversing each row of the transpose of a matrix [[1,3],[2,4]] -> [[3,1],[4,2]] 31 | image.reverse(); 32 | 33 | let temp; 34 | 35 | // Find the transpose of the image matrix. 36 | for (let i = 0; i < image.length; i++) { 37 | for (let j = i + 1; j < image[i].length; j++) { 38 | temp = image[i][j]; 39 | image[i][j] = image[j][i]; 40 | image[j][i] = temp; 41 | } 42 | } 43 | } 44 | 45 | let image = [ 46 | [1, 2], 47 | [3, 4], 48 | ]; 49 | rotateImage(image); 50 | console.log(image); //? [[3,1],[4,2]] 51 | -------------------------------------------------------------------------------- /javascript/DataStructures/Arrays/subsets.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a set of distinct integers, numbers, return all possible subsets (the power set). 4 | 5 | Note: The solution set must not contain duplicate subsets. 6 | 7 | Example: 8 | 9 | Input: numbers = [1,2,3] 10 | Output: 11 | [ 12 | [3], 13 |   [1], 14 |   [2], 15 |   [1,2,3], 16 |   [1,3], 17 |   [2,3], 18 |   [1,2], 19 |   [] 20 | ] 21 | 22 | */ 23 | 24 | ((numbers) => { 25 | return numbers.reduce( 26 | (subsets, current) => { 27 | return subsets.concat(subsets.map((subset) => [...subset, current])); 28 | }, 29 | [[]] 30 | ); 31 | })([1, 2, 3]); 32 | -------------------------------------------------------------------------------- /javascript/DataStructures/Graphs/BFS.js: -------------------------------------------------------------------------------- 1 | const { createGraph } = require("./index"); 2 | 3 | const { maxVertices, adjacencyList } = createGraph([ 4 | [1, 0], 5 | [2, 0], 6 | [3, 1], 7 | [3, 2], 8 | ]); 9 | 10 | console.log(bfs(1)); 11 | 12 | function bfs(vertex) { 13 | // initialize the visited array with false. 14 | let visited = new Array(maxVertices).fill(false); 15 | 16 | // create a Queue to traverse through the graph 17 | let queue = []; 18 | 19 | // mark the vertex as visited. 20 | queue.push(vertex); 21 | visited[vertex] = true; 22 | 23 | while (queue.length) { 24 | // remove the vertex from the queue and print it. 25 | vertex = queue.pop(); 26 | console.log(vertex); 27 | 28 | // fetch all neighbours of the current vertex 29 | const neighbours = adjacencyList.get(vertex); 30 | 31 | // loop through the list of neighbours and add the vertex to the queue if 32 | // its not visited yet. 33 | for (const neighbour of neighbours) { 34 | if (!visited[neighbour]) { 35 | visited[neighbour] = true; 36 | queue.push(neighbour); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /javascript/DataStructures/Graphs/DFS.js: -------------------------------------------------------------------------------- 1 | const { createGraph } = require("./index"); 2 | 3 | const { maxVertices, adjacencyList } = createGraph([ 4 | [1, 0], 5 | [2, 0], 6 | [3, 1], 7 | [3, 2], 8 | ]); 9 | 10 | console.log(dfs(0)); 11 | 12 | function dfs(vertex) { 13 | // initialize the visited array with false. 14 | let visited = new Array(maxVertices).fill(false); 15 | dfsUtil(vertex, visited); 16 | 17 | // a recursive utility function to explore all adjacent vertices of the 'vertex' 18 | function dfsUtil(vertex, visited) { 19 | // mark the current vertex as visited and print it 20 | visited[vertex] = true; 21 | console.log(vertex); 22 | 23 | // get all neighbours of the current vertex 24 | const neighbours = adjacencyList.get(vertex); 25 | // now explore each and every vertex recursively until all vertices are visited. 26 | for (const neighbour of neighbours) { 27 | if (!visited[neighbour]) { 28 | dfsUtil(neighbour, visited); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /javascript/DataStructures/Graphs/index.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor(maxVertices) { 3 | this.maxVertices = maxVertices; 4 | this.adjacencyList = new Map(); 5 | } 6 | 7 | addVertex(vertex) { 8 | if (this.adjacencyList.size >= this.maxVertices) 9 | throw new Error("Exceeded number of vertices"); 10 | this.adjacencyList.set(vertex, []); 11 | } 12 | 13 | // assuming the graph is a undirected graph 14 | addEdge(vertexA, vertexB) { 15 | let neighboursOfA = this.adjacencyList.get(vertexA); 16 | let neighboursOfB = this.adjacencyList.get(vertexB); 17 | if ( 18 | neighboursOfA.indexOf(vertexB) !== -1 || 19 | neighboursOfB.indexOf(vertexA) !== -1 20 | ) 21 | throw new Error("Duplicated edges"); 22 | neighboursOfA.push(vertexB); 23 | neighboursOfB.push(vertexA); 24 | } 25 | 26 | displayGraph() { 27 | const vertices = this.adjacencyList.keys(); 28 | for (const vertex of vertices) { 29 | const edges = this.adjacencyList.get(vertex); 30 | let neighbours = ""; 31 | for (const edge of edges) { 32 | neighbours += edge + " "; 33 | } 34 | console.log(`${vertex} --> ${neighbours}`); 35 | } 36 | } 37 | } 38 | 39 | /** 40 | * Creates and returns a graph using adjacencyList 41 | * @param {any[]} adjacencyList 42 | */ 43 | const createGraph = function (adjacencyList) { 44 | let vertices = [...new Set(adjacencyList.flat())]; 45 | const graph = new Graph(vertices.length); 46 | for (const vertex of vertices) { 47 | graph.addVertex(vertex); 48 | } 49 | for (const [vertexA, vertexB] of adjacencyList) { 50 | graph.addEdge(vertexA, vertexB); 51 | } 52 | graph.displayGraph(); 53 | return graph; 54 | }; 55 | 56 | module.exports = { createGraph }; 57 | -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/DetectLoop.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - PayTM, Amazon, MakeMyTrip, Snapdeal, VMWare, Samsung, Qualcomm, Walmart. 3 | 4 | Given a linked list, check if the the linked list has a loop. 5 | 6 | Create a function that returns true if a linked list contains a cycle, or false if it terminates 7 | Usually we assume that a linked list will end with a null next pointer, for example: 8 | A -> B -> C -> D -> E -> null 9 | A 'cycle' in a linked list is when traversing the list would result in visiting the same nodes over and over 10 | This is caused by pointing a node in the list to another node that already appeared earlier in the list. Example: 11 | A -> B -> C 12 | ^ | 13 | | v 14 | E <- D 15 | Example code: 16 | const nodeA = new Node('A'); 17 | const nodeB = nodeA.next = new Node('B'); 18 | const nodeC = nodeB.next = new Node('C'); 19 | const nodeD = nodeC.next = new Node('D'); 20 | const nodeE = nodeD.next = new Node('E'); 21 | hasCycle(nodeA); // => false 22 | nodeE.next = nodeB; 23 | hasCycle(nodeA); // => true 24 | Constraint 1: Do this in linear time 25 | Constraint 2: Do this in constant space 26 | Constraint 3: Do not mutate the original nodes in any way 27 | Hint: Search for Floyd's Tortoise and Hare algorithm. 28 | */ 29 | 30 | function Node(data){ 31 | this.data = data 32 | this.next = null 33 | } 34 | 35 | // You can read more on cycle detection at https://en.wikipedia.org/wiki/Cycle_detection 36 | // but the main takeaway is that if hare moves twice as fast as tortoise 37 | // then a loop would be identifiable as the hare will eventually catch up with the tortoise. 38 | 39 | const hasCycle = (head) => { 40 | let tortoise = head 41 | let hare = head 42 | do{ 43 | if(hare.next === null) 44 | return false 45 | hare = hare.next 46 | if(hare.next === null) 47 | return false 48 | hare = hare.next 49 | tortoise = tortoise.next 50 | }while(tortoise !== hare) 51 | return true 52 | } 53 | 54 | const n1 = new Node('A'); 55 | const n2 = n1.next = new Node('B'); 56 | const n3 = n2.next = new Node('C'); 57 | const n4 = n3.next = new Node('D'); 58 | const n5 = n4.next = new Node('E'); 59 | console.log(hasCycle(n1)); // => false 60 | n5.next = n2; 61 | console.log(hasCycle(n1)); // => true 62 | -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/ImplementQueue.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Samsung, Oracle, Amazon 3 | 4 | Implement a Queue using Linked List. 5 | */ 6 | 7 | let Queue = {front:null, back:null} // Initialize empty queue. 8 | 9 | // constructor to implement a LL. 10 | function Node(data,next){ 11 | this.data = data 12 | this.next = next 13 | } 14 | 15 | // Adding elements to the queue with time complexity - O(1) 16 | function Enqueue(element){ 17 | let N = new Node(element,null) 18 | if(Queue.back === null){ 19 | Queue.front = N 20 | Queue.back = N 21 | }else{ 22 | Queue.back.next = N 23 | Queue.back = Queue.back.next 24 | } 25 | } 26 | 27 | // Remove the front element from the Queue with time complexity - O(1) 28 | function Dequeue(){ 29 | if(Queue.front !== null){ 30 | let first = Queue.front 31 | Queue.front = Queue.front.next 32 | return first.data 33 | }else{ 34 | if(Queue.back !== null) 35 | Queue.back = null 36 | return `Queue is empty` 37 | } 38 | } 39 | 40 | Enqueue(1); 41 | Enqueue(2); 42 | Enqueue(3); 43 | Dequeue(); -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/ImplementStack.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Samsung, Microsoft, Codenation. 3 | 4 | Implement Stack using LinkedList. 5 | */ 6 | 7 | class Node{ 8 | constructor(data){ 9 | this.data = data 10 | this.next = null 11 | } 12 | } 13 | 14 | class Stack{ 15 | constructor(){ 16 | this.top = null 17 | } 18 | push(item){ 19 | let node = new Node(item) 20 | if(this.top){ 21 | node.next = this.top 22 | this.top = node 23 | }else{ 24 | this.top = node 25 | } 26 | } 27 | pop(){ 28 | if(this.top){ 29 | let itemToPop = this.top 30 | this.top = this.top.next 31 | return itemToPop.data 32 | }else{ 33 | console('Stack is empty!') 34 | return false 35 | } 36 | } 37 | peek(){ 38 | if(this.top) { 39 | return this.top.data 40 | }else{ 41 | return null 42 | } 43 | } 44 | } 45 | 46 | let stack = new Stack() 47 | stack.push(10) // top: 10 48 | stack.push(20) // top: 20 49 | stack.push(30) // top: 30 50 | stack.push(40) // top: 40 51 | stack.pop() // top: 30 52 | stack.peek() // 30 -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/MergeLinkedList.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - VMWare, Amazon. 3 | 4 | Given K sorted linked list your task is to merge them. 5 | You need to complete mergeKList method that takes 2 arguments the arr[] 6 | that represents an array of sorted linked lists and an integer N denoting the 7 | no. of sorted linked lists. The method needs to return head of the obtained linked list. 8 | */ 9 | 10 | //definition of LL. 11 | function Node(data){ 12 | this.data = data 13 | this.next = null 14 | } 15 | 16 | const mergeTwoLists = (list1,list2) => { 17 | if(!list1) return list2 18 | if(!list2) return list1 19 | let result = new Node(-1) 20 | let temp = result 21 | while(list1 && list2){ 22 | if(list1.data < list2.data){ 23 | result.next = list1 24 | list1 = lis1.next 25 | }else{ 26 | result.next = list2 27 | list2 = list2.next 28 | } 29 | result = result.next 30 | } 31 | if(list1) result.next = list1 32 | if(list2) result.next = list2 33 | return temp.next 34 | } 35 | 36 | const mergeKLists = (lists) => { 37 | let result = lists[0] || null 38 | for(let i=1;i2->3->4->5 then output should be 3. 6 | 7 | If there are even nodes, then there would be two middle nodes, 8 | we need to print second middle element. For example, 9 | if given linked list is 1->2->3->4->5->6 then output should be 4. 10 | */ 11 | 12 | 13 | //constructor - called every time a new object is created. 14 | function Node(data,next){ 15 | this.data = data 16 | this.next = next 17 | } 18 | 19 | // setup some nodes and connect them to each other. 20 | // the linked list looks like: 21 | // (head) n5 -> n4 -> n3 -> n2 -> n1 -> null 22 | 23 | let n1 = new Node("Bapusaheb", null) 24 | let n2 = new Node("makes", n1) 25 | let n3 = new Node("lame", n2) 26 | let n4 = new Node("memes", n3) 27 | let n5 = new Node("everytime", n4) 28 | 29 | // assign a node as the head of the list. 30 | let head = n5 31 | 32 | // here we use two pointers, fastPointer and slowPointer where fastPointer is incremented twice 33 | // while slowPointer is incremented once. when fastPointer reaches the end of the list,slowPointer will be 34 | // pointing to the middle of the linked list. Voila! 35 | let fastPointer = head 36 | let slowPointer = head 37 | while(fastPointer.next !== null && fastPointer.next.next !== null){ 38 | fastPointer = fastPointer.next.next 39 | slowPointer = slowPointer.next 40 | } 41 | 42 | slowPointer.data // returns the data in the middle of the linked list. ;-) -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/Palindrome.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Microsoft, Amazon, Snapdeal. 3 | 4 | Given a singly linked list of integers, 5 | Your task is to complete the function isPalindrome that returns true 6 | if the given list is palindrome, else returns false. 7 | */ 8 | 9 | // TODO : 10 | // Create a new copy of the linked list. 11 | // Reverse the newly created linked list. 12 | // Compare the original linked list with the reversed linked list. 13 | 14 | function Node(data){ 15 | this.data = data 16 | this.next = null 17 | } 18 | 19 | Node.prototype.add = function(data){ 20 | const end = new Node(data) 21 | let current = this 22 | while(current.next !== null) 23 | current = current.next 24 | current.next = end 25 | return end 26 | } 27 | 28 | const isPalindrome = (list) => { 29 | const reversed = reverseAndClone(list) 30 | return isEqual(list, reversed) 31 | } 32 | 33 | const reverseAndClone = node => { 34 | let head = null 35 | while(node){ 36 | const copy = new Node(node.data) 37 | copy.next = head 38 | head = copy 39 | node = node.next 40 | } 41 | return head 42 | } 43 | 44 | const isEqual = (one, two) => { 45 | while(one && two){ 46 | if(one.data !== two.data) 47 | return false 48 | one = one.next 49 | two = two.next 50 | } 51 | return one === null && two === null 52 | } 53 | 54 | const list = new Node(5) 55 | list.add(4) 56 | list.add(3) 57 | list.add(4) 58 | list.add(5) 59 | isPalindrome(list) // true 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/ReverseLinkedList.js: -------------------------------------------------------------------------------- 1 | /* 2 | Asked by - Cognizant, Cisco, Adobe, Microsoft, MakeMyTrip, Snapdeal, SAP labs, Qualcomm, PayTM,VMWare ... 3 | 4 | Given pointer to the head node of a linked list, the task is to reverse the linked list. 5 | 6 | Input: You need to complete a method reverse() that takes head as argument and returns new head. 7 | Output: Reverse the linked list and return head of the modified list. 8 | */ 9 | 10 | // TESTCASE : 11 | // let input = { 12 | // value: 1, 13 | // next: { 14 | // value: 2, 15 | // next: { 16 | // value: 3, 17 | // next: { 18 | // value: 4, 19 | // next: null 20 | // } 21 | // } 22 | // } 23 | // } 24 | 25 | // reverse(input) - iterative 26 | // reverse(input,1) - recursion 27 | // reverse(input,) - third approach 28 | 29 | // 1. Iterative Approach. 30 | const reverse = (head) => { 31 | let result = null 32 | let stack = [] 33 | let current = head 34 | while(current){ 35 | stack.push(current) 36 | current = current.next 37 | } 38 | // set head to the end of the linkedlist. 39 | result = stack.pop() || [] 40 | current = result 41 | while(current){ // pop the rest of the data. 42 | current.next = stack.pop() 43 | current = current.next 44 | } 45 | return result 46 | } 47 | 48 | // 2. Recursive Approach. 49 | const reverse = (node,parent) => { 50 | let result = parent || {} 51 | if(node){ 52 | let child = node.next 53 | node.next = parent 54 | result = reverse(child,node) 55 | } 56 | return result 57 | } 58 | 59 | // 3. Time to impress the interviewer ;-) 60 | const reverse = (input,reversedList) => input === null ? reversedList 61 | : reverse(input.next, Object.assign(input,{next:reversedList || null})) 62 | 63 | // Object.assign - MDN Docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /javascript/DataStructures/LinkedList/RotateLinkedList.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list, rotate the linked list counter-clockwise by k nodes. 3 | Where k is a given positive integer smaller than or equal to length of the linked list. 4 | For example, if the given linked list is 10->20->30->40->50->60 and k is 4, 5 | the list should be modified to 50->60->10->20->30->40. 6 | */ 7 | 8 | // Input - 9 | let input = { 10 | value: 10, 11 | next: { 12 | value: 20, 13 | next: { 14 | value: 30, 15 | next: { 16 | value: 40, 17 | next: { 18 | value: 50, 19 | next: { 20 | value: 60, 21 | next: null 22 | } 23 | } 24 | } 25 | } 26 | } 27 | } 28 | 29 | const rotate = (head,k) => { 30 | let previousHead = head, 31 | previous = head, 32 | current = head, 33 | i = 1; 34 | while(current.next){ 35 | if(i === k+1){ 36 | head = current 37 | previous.next = null 38 | } 39 | previous = current 40 | current = current.next 41 | i++ 42 | } 43 | current.next = previousHead 44 | return head 45 | } 46 | 47 | 48 | 49 | 50 | rotate(input,3) -------------------------------------------------------------------------------- /javascript/GreedyAlgorithms/GreedyKnapsack.js: -------------------------------------------------------------------------------- 1 | /*In greedy algorithm, we find a 'safe move' which is a move that is the logical 2 | * best next move, and once taken, the move reduces the problem into a subproblem (and then we take the 3 | * next safe-move etc.). 4 | In the knapsack problem the safe-move is to put the maximum available weight 5 | * from the next most valuable item into the knapsack (to the extent that the knapsack can hold more 6 | * weight of course). After reducing the weight of that item to 0 we have a subproblem and can take the 7 | * maximum weight of the next most valuable item that will fit into the knapsack, and we do this greedy 8 | * move again and again. 9 | * 10 | * In our function the items are pre-sorted with the highest value/weight ratios first in descending 11 | * order (the most valuable items in descending order). Without pre-sorting, this function would run 12 | * O(n^2) because we'd need to do an inner loop finding the next most valuable item. With pre-sorting 13 | * with Quicksort or Mergesort you can get O(n log n) because our function would just be O(n) as in 14 | * this example. 15 | * 16 | */ 17 | 18 | const greedyKnapsack = (capacity,items) => { 19 | let total = 0 20 | /* we initialize the quantities array with 0 so that trailing items 21 | that are not included in the knapsack will still be represented in the quantities array 22 | */ 23 | const quantity = new Array(items.length).fill(0) 24 | let index = 0 25 | for(const i of items){ 26 | if(capacity === 0) /* knapsack is full */ return [total,quantity] 27 | // We include the maximum of the currently most valuable item that will still fit in the knapsack. 28 | const numberOfUnits = Math.min(i.weight, capacity) 29 | 30 | quantity[index] = numberOfUnits 31 | total += numberOfUnits * i.value/i.weight 32 | i.weight -= numberOfUnits 33 | capacity -= numberOfUnits 34 | index++ 35 | } 36 | return [total,quantity] 37 | } 38 | 39 | // items are sorted with the highest value/weight ratios first in descending order. 40 | greedyKnapsack(7, [{value:14, weight: 2},{value:18, weight: 3},{value:20, weight: 4},{value:20, weight: 10}]) 41 | 42 | //expected output - [ 42, [ 2, 3, 2, 0 ] ] -------------------------------------------------------------------------------- /javascript/GreedyAlgorithms/README.md: -------------------------------------------------------------------------------- 1 | # Greedy Algorithms 2 | 3 | A greedy algorithm is an algorithmic paradigm that follows the problem solving heuristic of making the locally optimal choice at each stage with the intent of finding a [global optimum](https://en.wikipedia.org/wiki/Maxima_and_minima). In many problems, a greedy strategy does not usually produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a globally optimal solution in a reasonable amount of time. 4 | 5 | ### Greedy Knapsack Problem 6 | 7 | Given weights and values of *n* items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. 8 | ``` 9 | Input : 10 | Items as (value, weight) pairs 11 | array[] = [{60, 10}, {100, 20}, {120, 30}] 12 | Knapsack Capacity, W = 50; 13 | Output : 14 | Maximum possible value = 220 15 | by taking items of weight 20 and 30 kg 16 | ``` 17 | 18 | ![Greedyknapsack](https://image.slidesharecdn.com/knapsackproblem-achchuthan-140506120412-phpapp02/95/greedy-knapsack-problem-by-y-achchuthan-5-638.jpg?cb=1399378079) 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /javascript/numbers/hammingDistance.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. 4 | 5 | Given two integers `x` and `y`, calculate the Hamming distance. 6 | 7 | Input: x = 1, y = 4 8 | 9 | Output: 2 10 | 11 | Explanation: 12 | 1 (0 0 0 1) 13 | 4 (0 1 0 0) 14 | ↑ ↑ 15 | 16 | The above arrows point to positions where the corresponding bits are different. 17 | 18 | */ 19 | 20 | /** 21 | * 22 | * @param {number} x 23 | * @param {number} y 24 | * @returns {number} 25 | */ 26 | const hammingDistance = (x, y) => { 27 | /* 28 | input -> 1, 4 29 | 1. XOR of two numbers -> 1 ^ 4 30 | 2. Convert the number to its binary form -> 101 31 | 3. Remove 0s from the string and return the length of this new string 32 | */ 33 | return (x ^ y).toString(2).replace(/0/g, "").length; 34 | }; 35 | 36 | hammingDistance(1, 4); // 2 37 | hammingDistance(2, 5); // 3 38 | -------------------------------------------------------------------------------- /javascript/search/BinarySearch.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Search using recursion 3 | * Time complexity - Olog(n) 4 | * Memory Complexity - O(logn) - as it will consume memory on the stack 5 | */ 6 | let steps = 0 7 | 8 | const binarySearch = (array,key) => { 9 | const mid = Math.floor(array.length / 2) 10 | 11 | steps++ 12 | 13 | if(array.length === 1){ 14 | if(array[0] === key){ 15 | return true 16 | }else{ 17 | return false 18 | } 19 | } 20 | 21 | if(array[mid] > key){ 22 | const left = array.slice(0,mid+1) 23 | return binarySearch(left,key) 24 | } else if(array[mid] < key){ 25 | const right = array.slice(mid,array.length) 26 | return binarySearch(right,key) 27 | } else { 28 | console.log(`No. of steps to find ${key} in the given array is ${steps}`) 29 | return true 30 | } 31 | } 32 | 33 | const array = [1,2,3,4,5,6,7,8,9,10] 34 | console.log(binarySearch(array,9)) 35 | //output : No of steps to find 9 in the given array is 3 36 | //true -------------------------------------------------------------------------------- /javascript/search/BinarySearchTree.js: -------------------------------------------------------------------------------- 1 | /* 2 | Binary tree - is a tree data structure in which each node has at most two children, 3 | which are referred to as the left child and the right child. 4 | 5 | Binary search tree - keep their keys in the sorted order so that lookup and other operations can use the principle of binary search. 6 | - each comparison allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time proportional to the logarithm of the number of items stored in the tree. 7 | - This is much better than the linear time required to find items by key in an (unsorted) array but slower than the corresponding operations on hash tables. 8 | */ 9 | 10 | class BinarySearchTree { 11 | constructor() { 12 | this.root = null 13 | } 14 | insertNode(val) { 15 | var node = { 16 | data: val, 17 | left: null, 18 | right: null 19 | }; 20 | 21 | var currentNode 22 | 23 | if (!this.root) { 24 | this.root = node 25 | } else { 26 | currentNode = this.root 27 | while (currentNode) { 28 | if (val < currentNode.data) { 29 | if (!currentNode.left) { 30 | currentNode.left = node 31 | break 32 | } else { 33 | currentNode = currentNode.left 34 | } 35 | } else if (val > currentNode.data) { 36 | if (!currentNode.right) { 37 | currentNode.right = node 38 | break 39 | } else { 40 | currentNode = currentNode.right 41 | } 42 | } else { 43 | console.log('Ignoring this value due to duplicate values') 44 | break 45 | } 46 | } 47 | } 48 | } 49 | } 50 | 51 | var BST = new BinarySearchTree(); 52 | 53 | BST.insertNode(8); 54 | BST.insertNode(3); 55 | BST.insertNode(10); 56 | BST.insertNode(1); 57 | BST.insertNode(6); 58 | BST.insertNode(14); 59 | BST.insertNode(4); 60 | BST.insertNode(7); 61 | BST.insertNode(13); 62 | 63 | console.log(BST); -------------------------------------------------------------------------------- /javascript/search/README.md: -------------------------------------------------------------------------------- 1 | # Searching techniques 2 | 3 | ## Binary Search 4 | 5 | Binary search is used to perform a very efficient search on sorted dataset. The time complexity is `O(log2N)`. Idea is to repeatedly divide in half the portion of the list that could contain the item, until we narrow it down to one possible item. 6 | 7 | ![binary search](https://camo.githubusercontent.com/0444b608b78c3b30c443095b5f7c57ecaa8ab52c/68747470733a2f2f626c6f672e70656e6a65652e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031352f30342f62696e6172792d616e642d6c696e6561722d7365617263682d616e696d6174696f6e732e676966) 8 | 9 | ## Binary Search Tree 10 | 11 | **Binary tree** is a tree data structure in which each node has at most two children, 12 | which are referred to as the left child and the right child. 13 | 14 | **Binary search tree** 15 | * keep their keys in the sorted order so that lookup and other operations can use the principle of binary search. 16 | * each comparison allows the operations to skip about half of the tree, so that each lookup, insertion or deletion takes time proportional to the logarithm of the number of items stored in the tree. 17 | * This is much better than the linear time required to find items by key in an (unsorted) array but slower than the corresponding operations on hash tables. -------------------------------------------------------------------------------- /javascript/sort/BubbleSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 1. Bubble sort is the simplest sorting algorithm that compares two adjacent elements in an array and swaps the largest of the two values to the end. 3 | * 2. The worst case time complexity of bubble sort is O(n2): this is because for each iteration n-1 comparisons will be done. 4 | * 3. The best case time complexity will be O(n): this is when the list is already sorted 5 | * 4. The space time complexity will be O(1): since only one memory space is required for the temp variable. 6 | */ 7 | const bubbleSort = (array) => { 8 | let swap 9 | do{ 10 | swap = false 11 | for(let i=0;i array[i+1]){ 14 | [array[i],array[i+1]] = [array[i+1],array[i]] 15 | swap = true 16 | } 17 | } 18 | }while(swap) 19 | return array 20 | } 21 | 22 | const array = [25,23,3,56,14] 23 | bubbleSort(array) 24 | -------------------------------------------------------------------------------- /javascript/sort/InsertionSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Insertion sort compares the current element with the element on the left. 3 | * If it is found to be smaller it is swapped with the element on the left. 4 | * Worst Case Time Complexity : O(n2) 5 | * Best Case Time Complexity : O(n) 6 | * Average Time Complexity : O(n2) 7 | * Space Complexity : O(1) 8 | * This makes it inefficient to operate on larger datasets 9 | */ 10 | 11 | const insertionSort = (array) => { 12 | if(array.length == 1) 13 | return array; 14 | for(let i=1;i0;j--){ 16 | if(array[j] < array[j-1]){ 17 | [array[j],array[j-1]] = [array[j-1],array[j]] 18 | } 19 | } 20 | } 21 | return array 22 | } 23 | 24 | const array = [25,23,3,26,4] 25 | insertionSort(array) 26 | -------------------------------------------------------------------------------- /javascript/sort/MergeSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge sort uses divide & conquer method by splitting the array into smaller parts until there is only one element. 3 | * The elements are then compared and sorted and merged. 4 | * Split the arr into half by finding the median. 5 | * Call mergeSort on the first half and mergeSort on the second half. Then merge the two halves. 6 | * The time complexity of merge sort is always O(n log n): in all 3 cases (worst, average and best) as merge sort 7 | * always divides the array in two halves and take linear time to merge two halves. 8 | */ 9 | 10 | const mergeSort = array => { 11 | if(array.length === 1) 12 | return array 13 | 14 | //split the array into two halves,left and right 15 | let middle = Math.floor(array.length / 2) 16 | let left = array.slice(0,middle) 17 | let right = array.slice(middle) 18 | 19 | //divide and conquer - keep slicing the arrays until we obtain an array with a single item. 20 | return merge(mergeSort(left),mergeSort(right)) 21 | } 22 | 23 | const merge = (left,right) => { 24 | const array = [] 25 | while(left.length && right.length){ 26 | if(left[0] < right[0]){ 27 | array.push(left.shift()) //pushes the first element of the left array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) 28 | } else { 29 | array.push(right.shift()) 30 | } 31 | } 32 | // concatenate arrays to form a single sorted array 33 | return array.concat(left.slice()).concat(right.slice()) 34 | } 35 | 36 | const array = [4,232,2,45,66,7,88] 37 | mergeSort(array) 38 | -------------------------------------------------------------------------------- /javascript/sort/QuickSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an integer array, sort it in ascending order using quicksort. 3 | * 4 | * Runtime Complexity - Linearithmic, O(nlogn). 5 | * Memory Complexity - Logarithmic, O(logn). 6 | * Note: Recursive solution has O(logn) memory complexity as it will consume memory on the stack. 7 | * 8 | * 9 | * Step 1: Select a pivot element from the array, usually the first element 10 | * Step 2: Compare the pivot element with the current element. If the current element is less than the pivot, 11 | * shift the current element to the left side and if it is greater than the pivot, shift it to the right 12 | * side of the pivot. 13 | * Step 3: Recursively sort the sublists on the right and left sides of the pivot 14 | */ 15 | 16 | const quickSort = (array,left,right) => { 17 | left = left || 0 18 | right = right || array.length - 1 19 | 20 | const pivot = partition(array,left,right) 21 | 22 | if(left < pivot - 1) 23 | quickSort(array,left,pivot - 1) 24 | if(right > pivot) 25 | quickSort(array,pivot,right) 26 | 27 | return array 28 | } 29 | 30 | const partition = (array,left,right) => { 31 | //find the pivot element - middle element would be an ideal pivot 32 | const pivot = Math.floor((left + right) / 2) 33 | //refer Step 2 34 | while(left <= right){ 35 | while(array[left] < array[pivot]) 36 | left++ 37 | while (array[right] > array[pivot]) 38 | right-- 39 | 40 | if(left <= right){ 41 | //swap the elements 42 | [array[left],array[right]] = [array[right],array[left]] 43 | left++ 44 | right-- 45 | } 46 | } 47 | //return the left index as the pivot value. 48 | return left 49 | } 50 | 51 | const array = [24,23,535,5,44,21] 52 | quickSort(array) 53 | -------------------------------------------------------------------------------- /javascript/sort/README.md: -------------------------------------------------------------------------------- 1 | # Sort 2 | ## Bubble Sort 3 | Bubble Sort is a 4 | simple sorting algorithm that repeatedly steps through 5 | the list to be sorted, compares each pair of adjacent 6 | items and swaps them if they are in the wrong order. 7 | The pass through the list is repeated until no swaps 8 | are needed, which indicates that the list is sorted. 9 | 10 | ![Algorithm Visualization](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif) 11 | 12 | 13 | ## Insertion Sort 14 | 15 | Insertion sort compares the current element with the element on the left.If it is found to be smaller it is swapped with the element on the left. 16 | 17 | ![Algorithm Visualization](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) 18 | 19 | ## Merge Sort 20 | 21 | Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. 22 | 23 | ![Merge Sort](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif) 24 | 25 | A recursive merge sort algorithm used to sort an array of 7 26 | integer values. These are the steps a human would take to 27 | emulate merge sort (top-down). 28 | 29 | ![Merge Sort](https://upload.wikimedia.org/wikipedia/commons/e/e6/Merge_sort_algorithm_diagram.svg) 30 | 31 | ## Quick Sort 32 | Quick sort is a sorting technique that sequences a list by continuously dividing the list into two parts and moving the lower items to one side and the higher items to the other. It starts by picking one item in the entire list to serve as a pivot point. The pivot could be the first item or a randomly chosen one. All items that compare lower than the pivot are moved to the left of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left side and moves those items to left and right of the pivot and continues the pivot picking and dividing until there is only one item left in the group. It then proceeds to the right side and performs the same operation again. 33 | 34 | ![Quick Sort](https://upload.wikimedia.org/wikipedia/commons/9/9c/Quicksort-example.gif) 35 | 36 | ## Selection sort 37 | 38 | Selection sort is the simplest sorting algorithm. It finds the smallest element in the array and swaps it with the first position in the array. Then the second smallest and swaps it with the second position etc. 39 | 40 | ![Selection Sort](https://upload.wikimedia.org/wikipedia/commons/9/94/Selection-Sort-Animation.gif) 41 | 42 | 43 | 44 | | Algorithm | Time Complexity (best,average,worst) | Space Complexity | 45 | |---------|-------------- |-----------| 46 | |**Bubble Sort**|O(n), O(n2), O(n2)|O(1)| 47 | |**Insertion Sort**|O(n), O(n2), O(n2)|O(1)| 48 | |**Merge Sort**|O(n log(n))|O(n)| 49 | |**Quick Sort**|O(n log(n)), O(n log(n)), O(n2)|O(log(n))| 50 | |**Selection Sort**|O(n2), O(n2), O(n2)|O(1)| 51 | -------------------------------------------------------------------------------- /javascript/sort/SelectionSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 1. Selection sort is the simplest sorting algorithm. It finds the smallest element in the array and swaps it with the first position in the array. Then the second smallest and swaps it with the second position etc. 3 | * 2. Worst Case Time Complexity : O(n2) 4 | * 3. Best Case Time Complexity : O(n2) 5 | * 4. Average Time Complexity : O(n2) 6 | * 5. Space Complexity : O(1) 7 | * This makes it inefficient to operate on larger datasets 8 | */ 9 | 10 | const selectionSort = (array) => { 11 | if(array.length === 1) 12 | return array 13 | 14 | for(let i=0;i { 33 | let shouldReward = true; 34 | 35 | let attendanceMatches = attendance.match(/a/gi); 36 | 37 | if (attendanceMatches !== null && attendanceMatches.length > 1) 38 | shouldReward = false; 39 | else if (/LLL+/i.test(attendance)) shouldReward = false; 40 | 41 | return shouldReward; 42 | }; 43 | 44 | rewardStudent("PPALL"); // true 45 | rewardStudent("PAAL"); // false 46 | -------------------------------------------------------------------------------- /python/power.py: -------------------------------------------------------------------------------- 1 | # Asked by - Delta X 2 | 3 | # 2 players play a game. A number is given as input. If the number is a power of 2(i.e, 2^1, 2^2 .. 2^64), 4 | # then divide the number by 2 and pass the number to the other player. Else, if the number is not a power 5 | # of 2, then subtract the number with its nearest 2 power number and pass the number to the other player. 6 | # PlayerA always starts the game. The player who gets to value 1(one) is the winner. Output the name of 7 | # the winner, i.e, 'PlayerA' or 'PlayerB' 8 | 9 | # Ex: 10 | # n = 10 11 | # Output: PlayerB 12 | 13 | # n = 12 14 | # Output = PlayerA 15 | 16 | import math 17 | 18 | #Function to check if a number is a power of 2. 19 | def check(n): 20 | val = 1 21 | for i in range(1, 65): 22 | val = val * 2 23 | if(n == val): 24 | return -1 #return -1 if it is a power of 2 25 | elif(val > n): 26 | return i-1 #return the nearest power value 27 | 28 | n = int(input("Enter n")) 29 | 30 | turn = 1 #to keep track of which player is playing 31 | count = 0 32 | 33 | while(n != 1): 34 | count = count + 1 35 | if(count % 2 == 0): 36 | turn = 2 #playerB turn 37 | else: 38 | turn = 1 #playerA turn 39 | 40 | val = check(n) #check if number is a power of 2 41 | 42 | if (val == -1): 43 | n = n / 2 44 | else: 45 | n = n - math.pow(2, val) 46 | 47 | if (turn == 1): 48 | print("PlayerA") 49 | else: 50 | print("PlayerB") 51 | -------------------------------------------------------------------------------- /python/queues/FIFOpageReplacement.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In operating systems that use paging for memory management, page replacement algorithm are needed to 3 | decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not 4 | present in memory, page fault occurs and Operating System replaces one of the existing pages with newly 5 | needed page. Different page replacement algorithms suggest different ways to decide which page to replace. 6 | The target for all algorithms is to reduce number of page faults. 7 | 8 | First In First Out (FIFO) page replacement algorithm 9 | This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all 10 | pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced 11 | page in the front of the queue is selected for removal. 12 | 13 | Example -1. Consider page reference string 1, 3, 0, 3, 5, 6 and 3 page slots. 14 | 15 | Initially all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —> 3 Page Faults. 16 | when 3 comes, it is already in memory so —> 0 Page Faults. 17 | Then 5 comes, it is not available in memory so it replaces the oldest page slot i.e 1. —>1 Page Fault. 18 | Finally 6 comes, it is also not available in memory so it replaces the oldest page slot i.e 3 —>1 Page Fault. 19 | 20 | So total page faults = 6. 21 | ''' 22 | #using inbuilt modules for queue 23 | from collections import deque 24 | 25 | queue = deque([]) 26 | 27 | #input number of page slots 28 | 29 | cap = int(input()) 30 | 31 | #input number of pages 32 | 33 | n=int(input()) 34 | 35 | fault=0 36 | 37 | for i in range(0,n): 38 | k=int(input()) 39 | if k not in queue: 40 | if len(queue) < cap: 41 | queue.append(k) 42 | fault+=1 43 | else: 44 | queue.popleft() 45 | queue.append(k) 46 | fault+=1 47 | print(queue) 48 | 49 | print(fault) 50 | -------------------------------------------------------------------------------- /python/queues/ImplementationUsingLists.py: -------------------------------------------------------------------------------- 1 | # Python3 program for array implementation of queue 2 | 3 | # Class Queue to represent a queue 4 | class Queue: 5 | # __init__ function 6 | def __init__(self, capacity): 7 | self.front = self.size = 0 8 | self.rear = capacity - 1 9 | self.Q = [None]*capacity # empty Queue 10 | self.capacity = capacity 11 | 12 | # Queue is full when size becomes 13 | # equal to the capacity 14 | def isFull(self): 15 | return self.size == self.capacity 16 | 17 | # Queue is empty when size is 0 18 | def isEmpty(self): 19 | return self.size == 0 20 | 21 | # Function to add an item to the queue. 22 | # It changes rear and size 23 | def EnQueue(self, item): 24 | if self.isFull(): 25 | return 26 | self.rear = (self.rear + 1) % (self.capacity) 27 | self.Q[self.rear] = item 28 | self.size = self.size + 1 29 | 30 | # Function to remove an item from queue. 31 | # It changes front and size 32 | def DeQueue(self): 33 | if self.isEmpty(): 34 | print("-1",end=" ") 35 | return 36 | 37 | print(str(self.Q[self.front]),end=" ") 38 | self.front = (self.front + 1) % (self.capacity) 39 | self.size = self.size -1 40 | 41 | # Function to get front of queue 42 | def que_front(self): 43 | if self.isEmpty(): 44 | print("Queue is empty") 45 | print("Front item is", self.Q[self.front]) 46 | 47 | # Function to get rear of queue 48 | def que_rear(self): 49 | if self.isEmpty(): 50 | print("Queue is empty") 51 | print("Rear item is", self.Q[self.rear]) 52 | 53 | 54 | #TEST : 55 | q = Queue(100) 56 | t = int(input()) 57 | for t in range(0,t): 58 | n = int(input()) 59 | inp = input() 60 | arr=inp.split() 61 | i=0 62 | while n>0: 63 | if arr[i]=='1': 64 | i=i+1 65 | q.EnQueue(arr[i]) 66 | i=i+1 67 | elif arr[i]=='2': 68 | q.DeQueue() 69 | i=i+1 70 | n-=1 -------------------------------------------------------------------------------- /python/queues/InterleavingElements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue. We are allowed to use only queue data structure. 3 | 4 | Examples: 5 | 6 | Input : 1 2 3 4 7 | Output : 1 3 2 4 8 | 9 | Input : 11 12 13 14 15 16 17 18 19 20 10 | Output : 11 16 12 17 13 18 14 19 15 20 11 | ''' 12 | 13 | # Python3 program for array implementation of queue 14 | 15 | # Class Queue to represent a queue 16 | class Queue: 17 | # __init__ function 18 | def __init__(self, capacity): 19 | self.front = self.size = 0 20 | self.rear = capacity - 1 21 | self.Q = [None]*capacity # empty Queue 22 | self.capacity = capacity 23 | 24 | # Queue is full when size becomes 25 | # equal to the capacity 26 | def isFull(self): 27 | return self.size == self.capacity 28 | 29 | # Queue is empty when size is 0 30 | def isEmpty(self): 31 | return self.size == 0 32 | 33 | # Function to add an item to the queue. 34 | # It changes rear and size 35 | def EnQueue(self, item): 36 | if self.isFull(): 37 | return 38 | self.rear = (self.rear + 1) % (self.capacity) 39 | self.Q[self.rear] = item 40 | self.size = self.size + 1 41 | 42 | # Function to remove an item from queue. 43 | # It changes front and size 44 | def DeQueue(self): 45 | if self.isEmpty(): 46 | print("-1",end=" ") 47 | return 48 | 49 | #print(str(self.Q[self.front]),end=" ") 50 | self.front = (self.front + 1) % (self.capacity) 51 | self.size = self.size -1 52 | 53 | # Function to get front of queue 54 | def que_front(self): 55 | if self.isEmpty(): 56 | print("Queue is empty") 57 | #print("Front item is", self.Q[self.front]) 58 | return self.Q[self.front] 59 | 60 | # Function to get rear of queue 61 | def que_rear(self): 62 | if self.isEmpty(): 63 | print("Queue is empty") 64 | #print("Rear item is", self.Q[self.rear]) 65 | return self.Q[self.rear] 66 | 67 | 68 | 69 | #enter no. of elements 70 | n=int(input()) 71 | 72 | q=Queue(n) 73 | q1=Queue(n) 74 | q2=Queue(n) 75 | 76 | #enter elements 77 | for i in range(0,n): 78 | q.EnQueue(input()) 79 | 80 | #insert first half in q1 81 | for j in range(0,int(n/2)): 82 | q1.EnQueue(q.que_front()) 83 | q.DeQueue() 84 | 85 | #insert second half in q2 86 | for k in range(0,int(n/2)): 87 | q2.EnQueue(q.que_front()) 88 | q.DeQueue() 89 | 90 | 91 | #insert back into q alternatively 92 | for i in range(0,int(n/2)): 93 | q.EnQueue(q1.que_front()) 94 | print(q1.que_front(),end="\t") 95 | q1.DeQueue() 96 | q.EnQueue(q2.que_front()) 97 | print(q2.que_front(),end="\t") 98 | q2.DeQueue() 99 | 100 | -------------------------------------------------------------------------------- /python/queues/LinkedListImplementation.py: -------------------------------------------------------------------------------- 1 | # Python3 program to demonstrate linked list 2 | # based implementation of queue 3 | 4 | # A linked list (LL) node 5 | # to store a queue entry 6 | class Node: 7 | def __init__(self, data): 8 | self.data = data 9 | self.next = None 10 | 11 | # A class to represent a queue 12 | 13 | # The queue, front stores the front node 14 | # of LL and rear stores ths last node of LL 15 | class Queue: 16 | def __init__(self): 17 | self.front = self.rear = None 18 | 19 | def isEmpty(self): 20 | return self.front is None 21 | 22 | # Method to add an item to the queue 23 | def EnQueue(self, item): 24 | temp = Node(item) 25 | if self.rear is None: 26 | self.front = self.rear = temp 27 | return 28 | self.rear.next = temp 29 | self.rear = temp 30 | 31 | # Method to remove an item from queue 32 | def DeQueue(self): 33 | if self.isEmpty(): 34 | return 35 | temp = self.front 36 | self.front = temp.next 37 | if(self.front is None): 38 | self.rear = None 39 | return str(temp.data) 40 | 41 | # Driver Code 42 | if __name__== '__main__': 43 | q = Queue() 44 | q.EnQueue(10) 45 | q.EnQueue(20) 46 | q.DeQueue() 47 | q.DeQueue() 48 | q.EnQueue(30) 49 | q.EnQueue(40) 50 | q.EnQueue(50) 51 | print("Dequeued item is " + q.DeQueue()) 52 | 53 | -------------------------------------------------------------------------------- /python/stacks/GeneralImplementation.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of stack 2 | 3 | # import maxsize from sys module 4 | # Used to return -infinite when stack is empty 5 | from sys import maxsize 6 | 7 | # Function to create a stack. It initializes size of stack as 0 8 | def createStack(): 9 | stack = [] 10 | return stack 11 | 12 | # Stack is empty when stack size is 0 13 | def isEmpty(stack): 14 | return len(stack) == 0 15 | 16 | # Function to add an item to stack. It increases size by 1 17 | def push(stack, item): 18 | stack.append(item) 19 | #print("pushed to stack " + item) 20 | 21 | # Function to remove an item from stack. It decreases size by 1 22 | def pop(stack): 23 | if (isEmpty(stack)): 24 | return str(-maxsize -1) #return minus infinite 25 | 26 | return stack.pop() -------------------------------------------------------------------------------- /python/stacks/InfixToPostfix.py: -------------------------------------------------------------------------------- 1 | # Python program to convert infix expression to postfix 2 | 3 | # Class to convert the expression 4 | class Conversion: 5 | 6 | # Constructor to initialize the class variables 7 | def __init__(self, capacity): 8 | self.top = -1 9 | self.capacity = capacity 10 | # This array is used a stack 11 | self.array = [] 12 | # Precedence setting 13 | self.output = [] 14 | self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3} 15 | 16 | # check if the stack is empty 17 | def isEmpty(self): 18 | return True if self.top == -1 else False 19 | 20 | # Return the value of the top of the stack 21 | def peek(self): 22 | return self.array[-1] 23 | 24 | # Pop the element from the stack 25 | def pop(self): 26 | if not self.isEmpty(): 27 | self.top -= 1 28 | return self.array.pop() 29 | else: 30 | return "$" 31 | 32 | # Push the element to the stack 33 | def push(self, op): 34 | self.top += 1 35 | self.array.append(op) 36 | 37 | # A utility function to check is the given character 38 | # is operand 39 | def isOperand(self, ch): 40 | return ch.isalpha() 41 | 42 | # Check if the precedence of operator is strictly 43 | # less than top of stack or not 44 | def notGreater(self, i): 45 | try: 46 | a = self.precedence[i] 47 | b = self.precedence[self.peek()] 48 | return True if a <= b else False 49 | except KeyError: 50 | return False 51 | 52 | # The main function that converts given infix expression 53 | # to postfix expression 54 | def infixToPostfix(self, exp): 55 | 56 | # Iterate over the expression for conversion 57 | for i in exp: 58 | # If the character is an operand, 59 | # add it to output 60 | if self.isOperand(i): 61 | self.output.append(i) 62 | 63 | # If the character is an '(', push it to stack 64 | elif i == '(': 65 | self.push(i) 66 | 67 | # If the scanned character is an ')', pop and 68 | # output from the stack until and '(' is found 69 | elif i == ')': 70 | while( (not self.isEmpty()) and self.peek() != '('): 71 | a = self.pop() 72 | self.output.append(a) 73 | if (not self.isEmpty() and self.peek() != '('): 74 | return -1 75 | else: 76 | self.pop() 77 | 78 | # An operator is encountered 79 | else: 80 | while(not self.isEmpty() and self.notGreater(i)): 81 | self.output.append(self.pop()) 82 | self.push(i) 83 | 84 | # pop all the operator from the stack 85 | while not self.isEmpty(): 86 | self.output.append(self.pop()) 87 | 88 | print ("".join(self.output)) -------------------------------------------------------------------------------- /python/stacks/PostfixEvaluation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a postfix expression, the task is to evaluate the expression and print the final value.Operators will only include the basic arithmetic operators like *,/,+ and - . 3 | 4 | Input: 5 | The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an postfix expression. 6 | 7 | Output: 8 | For each test case, evaluate the postfix expression and print the value. 9 | 10 | Constraints: 11 | 1 <= T <= 100 12 | 1 <= length of expression <= 100 13 | 14 | Example: 15 | 16 | Input: 17 | 2 18 | 231*+9- 19 | 123+*8- 20 | 21 | Output: 22 | -4 23 | -3 24 | ''' 25 | 26 | # Python program to evaluate value of a postfix expression 27 | 28 | # Class to convert the expression 29 | class Evaluate: 30 | 31 | # Constructor to initialize the class variables 32 | def __init__(self, capacity): 33 | self.top = -1 34 | self.capacity = capacity 35 | # This array is used a stack 36 | self.array = [] 37 | 38 | # check if the stack is empty 39 | def isEmpty(self): 40 | return True if self.top == -1 else False 41 | 42 | # Return the value of the top of the stack 43 | def peek(self): 44 | return self.array[-1] 45 | 46 | # Pop the element from the stack 47 | def pop(self): 48 | if not self.isEmpty(): 49 | self.top -= 1 50 | return self.array.pop() 51 | else: 52 | return "$" 53 | 54 | # Push the element to the stack 55 | def push(self, op): 56 | self.top += 1 57 | self.array.append(op) 58 | 59 | 60 | # The main function that converts given infix expression 61 | # to postfix expression 62 | def evaluatePostfix(self, exp): 63 | 64 | # Iterate over the expression for conversion 65 | for i in exp: 66 | 67 | # If the scanned character is an operand 68 | # (number here) push it to the stack 69 | if i.isdigit(): 70 | self.push(i) 71 | 72 | # If the scanned character is an operator, 73 | # pop two elements from stack and apply it. 74 | else: 75 | val1 = self.pop() 76 | val2 = self.pop() 77 | self.push(str(eval(val2 + i + val1))) 78 | 79 | return self.pop() 80 | 81 | n = int(input()) 82 | for i in range(0,n): 83 | expr = input() 84 | obj = Evaluate(len(expr)) 85 | x = int(float(obj.evaluatePostfix(expr))) #int(0.0) gives an error, hence int(float(0.0)) 86 | print(x) -------------------------------------------------------------------------------- /python/stacks/StacksUsingArrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement a Stack using Array . 3 | 4 | Input (To be used for Expected Output): 5 | 6 | The first line of the input contains an integer 'T' denoting the number of test cases. Then T test cases follow. 7 | First line of each test case contains an integer Q denoting the number of queries . 8 | A Query Q is of 2 Types 9 | (i) 1 x (a query of this type means pushing 'x' into the stack) 10 | (ii) 2 (a query of this type means to pop element from stack and print the poped element) 11 | 12 | The second line of each test case contains Q queries seperated by space. 13 | 14 | Output: 15 | The output for each test case will be space separated integers having -1 if the stack is empty else the element poped out from the stack . 16 | You are required to complete the two methods push which take one argument an integer 'x' to be pushed into the stack and pop which returns a integer poped out from the stack. 17 | 18 | Constraints: 19 | 1<=T<=100 20 | 1<=Q<=100 21 | 1<=x<=100 22 | 23 | Example: 24 | Input 25 | 1 26 | 5 27 | 1 2 1 3 2 1 4 2 28 | 29 | Output 30 | 3 4 31 | ''' 32 | 33 | # Python program for implementation of stack 34 | 35 | # import maxsize from sys module 36 | # Used to return -infinite when stack is empty 37 | from sys import maxsize 38 | 39 | # Function to create a stack. It initializes size of stack as 0 40 | def createStack(): 41 | stack = [] 42 | return stack 43 | 44 | # Stack is empty when stack size is 0 45 | def isEmpty(stack): 46 | return len(stack) == 0 47 | 48 | # Function to add an item to stack. It increases size by 1 49 | def push(stack, item): 50 | stack.append(item) 51 | #print("pushed to stack " + item) 52 | 53 | # Function to remove an item from stack. It decreases size by 1 54 | def pop(stack): 55 | if (isEmpty(stack)): 56 | return str(-maxsize -1) #return minus infinite 57 | 58 | return stack.pop() 59 | st = createStack() 60 | t = int(input()) 61 | for t in range(0,t): 62 | n = int(input()) 63 | inp = input() 64 | arr=inp.split() 65 | #print(arr) 66 | #print(n) 67 | i=0 68 | while n>0: 69 | if arr[i]=='1': 70 | i=i+1 71 | push(st,arr[i]) 72 | i=i+1 73 | elif arr[i]=='2': 74 | print(pop(st),end=' ') 75 | i=i+1 76 | n-=1 77 | 78 | #print(st) -------------------------------------------------------------------------------- /python/stacks/StringReversalUsingStacks.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An string of words is given, the task is to reverse the string using stack. 3 | 4 | Input: 5 | 6 | The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains a string s of words without spaces. 7 | 8 | Output: 9 | 10 | For each test case ,print the reverse of the string in new line. 11 | 12 | Constraints: 13 | 14 | 1<=T<=100 15 | 1<=length of the string <=100 16 | 17 | Example: 18 | 19 | Input: 20 | 21 | 2 22 | Python 23 | StackImplementation 24 | 25 | Output: 26 | 27 | nohtyP 28 | noitatnemelpmIkcatS 29 | ''' 30 | 31 | # Python program to reverse a string using stack 32 | 33 | # Function to create an empty stack. It initializes size of stack as 0 34 | def createStack(): 35 | stack=[] 36 | return stack 37 | 38 | # Function to determine the size of the stack 39 | def size(stack): 40 | return len(stack) 41 | 42 | # Stack is empty if the size is 0 43 | def isEmpty(stack): 44 | if size(stack) == 0: 45 | return true 46 | 47 | # Function to add an item to stack . It increases size by 1 48 | def push(stack,item): 49 | stack.append(item) 50 | 51 | #Function to remove an item from stack. It decreases size by 1 52 | def pop(stack): 53 | if isEmpty(stack): return 54 | return stack.pop() 55 | 56 | # A stack based function to reverse a string 57 | def reverse(string): 58 | n = len(string) 59 | 60 | # Create a empty stack 61 | stack = createStack() 62 | 63 | # Push all characters of string to stack 64 | for i in range(0,n,1): 65 | push(stack,string[i]) 66 | 67 | # Making the string empty since all characters are saved in stack 68 | string="" 69 | 70 | # Pop all characters of string and put them back to string 71 | for i in range(0,n,1): 72 | string+=pop(stack) 73 | 74 | return string 75 | 76 | n = int(input()) 77 | for i in range(0,n): 78 | str1 = input() 79 | str2 = reverse(str1) 80 | print(str2) --------------------------------------------------------------------------------