├── .gitignore ├── Chapter-02 ├── highArrayApp.java ├── lowArrayApp.java └── orderedArray.java ├── Chapter-03 ├── bubbleSort.java ├── insertionSort.java └── selectionSort.java ├── Chapter-04 ├── BracketsApp.java ├── CheckOutApp.java ├── CircularDeque.java ├── CircularQueue.java ├── DeQueueApp.java ├── PriorityQueue.java ├── QueueApp.java ├── ReverseApp.java ├── StackApp.java └── infixPostfix.java ├── Chapter-05 ├── CircularList.java ├── DequeueList.java ├── DoubleEnded.java ├── DoubleLinklist.java ├── JosephusProblem.java ├── MatrixList.java ├── PriorityLinkedlist.java ├── ReverseDoubleLinkedList.java ├── SingleEnded.java └── StackList.java ├── Chapter-06 ├── (6.5).java ├── Anagram.java ├── BinarySearch.java ├── Factorial.java ├── Knapsack │ ├── Knapsack_MultiSolution.java │ └── Knapsack_OneSolution.java ├── MergeSort.java ├── NumberPower.java ├── RecursiveMultiplication.java ├── TowerHanoi.java └── Triangular.java ├── Chapter-07 ├── Partition.java ├── QuickSort.java └── shellSort.java ├── Chapter-08 ├── BinaryTreeFromString.java ├── BinaryTreeImplementation.java └── SegmentTree.java ├── Chapter-12 └── heap_12_1.java ├── Chapter-13 ├── BFS.java ├── DFS.java └── MST.java ├── Chapter-14 ├── Hamiltonian.java └── hamiltoniancycle.java ├── Practice Problems ├── Arrays │ ├── A Very Big Sum │ │ ├── AVeryBigSum.java │ │ └── Readme.md │ ├── Arrange Students │ │ ├── ArrangeStudents.java │ │ └── README.md │ ├── Breaking The Records │ │ ├── BreakingTheRecords.java │ │ └── Readme.md │ ├── Find All Numbers Disappeared In An Array │ │ ├── FindAllNumbersDisappearedInAnArray.java │ │ └── README.md │ ├── Knight's Possible Moves │ │ ├── KnightsPossibleMoves.java │ │ └── README.md │ ├── Maximum Subarray │ │ ├── MaximumSubarray.java │ │ └── README.md │ ├── MaximumCircularSum │ │ ├── MaximumCircularSum.java │ │ └── Readme.md │ ├── Non Decreasing Array │ │ ├── NonDecreasingArray.java │ │ └── README.md │ ├── Palindrome │ │ ├── README.md │ │ └── solution.java │ ├── PlusMInus │ │ ├── PlusMInus.java │ │ └── Readme.md │ ├── Product Array │ │ ├── ProductArray.java │ │ └── README.md │ ├── README.md │ ├── Sock Merchant │ │ ├── README.md │ │ └── SockMerchant.java │ ├── Solving For Queries With Cups │ │ ├── README.md │ │ └── SolvingForQueriesWithCups.java │ ├── SpiralPrintClockWise │ │ ├── Readme.md │ │ └── SpiralPrintClockWise.java │ ├── Square Diagonals │ │ ├── README.md │ │ └── SquareDiagonals.java │ ├── Sum Triplet │ │ ├── Readme.md │ │ └── SumTriplet.java │ ├── The Block Problem │ │ ├── README.md │ │ └── The Blocks Problem.java │ ├── Two Sum │ │ ├── README.md │ │ └── TwoSum.java │ ├── Valid Suduko │ │ ├── README.md │ │ └── ValidSudoku.java │ ├── Walking Robot Simulation │ │ ├── README.md │ │ └── WalkingRobotSimulation.java │ └── WavePrintRowWise │ │ ├── Readme.md │ │ └── WavePrintRowWise.java ├── Backtracking │ ├── Combination Sum │ │ ├── CombinationSum.java │ │ └── README.md │ ├── PermutationsOfString │ │ ├── PermutationsOfString.java │ │ └── README.md │ ├── README.md │ ├── Rat In A Maze │ │ ├── README.md │ │ └── RatMaze.java │ ├── Sudoku │ │ ├── README.md │ │ └── Sudoku.java │ └── WordBreakProblem │ │ ├── README.md │ │ └── WordBreakProblem.java ├── BinarySearch │ ├── Aggressive Cow │ │ ├── AggressiveCow.java │ │ └── README.md │ ├── BookAllocationProblem │ │ ├── BookAllocationProblem.java │ │ └── Readme.md │ ├── PainterProblem │ │ ├── PainterProblem.java │ │ └── Readme.md │ └── README.md ├── Divide_the_chockolate │ ├── README.md │ └── solution.java ├── Dynamic Programming │ ├── Edit_Distance │ │ ├── Edit_Distance.java │ │ └── README.md │ ├── README.md │ └── Unique Paths │ │ ├── README.md │ │ └── UniquePaths.java ├── LinkedList │ ├── Find middle of LinkedList │ │ ├── README.md │ │ └── midLL.java │ ├── LastOccurrence │ │ ├── LastOccurrence.java │ │ └── README.md │ ├── Merge two sorted LinkedLists │ │ ├── MergeTwoSortedLinkedLists.java │ │ └── README.md │ ├── Palindrome LinkedList │ │ ├── PalindromeLinkedList.java │ │ └── README.md │ ├── README.md │ ├── RemoveFirstLastOccurence │ │ ├── README.md │ │ └── RemoveFirstLastOccurence.java │ ├── Reverse LinkedList │ │ ├── README.md │ │ └── ReverseLinkedList.java │ └── Swap nodes in pairs │ │ ├── README.md │ │ └── SwapNodesInPairs.java ├── Maths │ ├── Adding Reversed Numbers │ │ ├── AddingReversedNumbers.java │ │ └── README.md │ ├── Back to Intermediate Math │ │ ├── IntermediateMath.java │ │ └── README.md │ ├── Increasing Decreasing Sequence │ │ ├── IncDecSequence.java │ │ └── README.md │ ├── Jewel-eating Monsters │ │ ├── JewelEatingMonsters.java │ │ └── README.md │ ├── My Sqrt │ │ ├── MySqrt.java │ │ └── README.md │ ├── Plus One │ │ ├── PlusOne.java │ │ └── README.md │ ├── Power x To n │ │ ├── PowerxTon.java │ │ └── README.md │ ├── README.md │ ├── Reach A Number │ │ ├── README.md │ │ └── ReachANumber.java │ ├── Reduced Subtracted Form │ │ ├── README.md │ │ └── ReducedSubstractionForm.java │ ├── The 3n + 1 problem │ │ ├── README.md │ │ └── The3nplus1.java │ └── ZSUM - Just add it │ │ ├── README.md │ │ └── Zsum.java ├── Patterns │ ├── Diamond │ │ ├── Diamond.java │ │ └── README.md │ ├── Ganeshas Pattern │ │ ├── GaneshasPattern.java │ │ └── README.md │ ├── Hollow Rhombus │ │ ├── HollowRhombus.java │ │ └── README.md │ ├── PatternHourGlass │ │ ├── PatternHourGlass.java │ │ └── Readme.md │ ├── README.md │ ├── RightAlphabeticTriangle │ │ ├── README.md │ │ └── RightAlphabeticTriangle.java │ └── Sandglass │ │ ├── README.md │ │ └── Sandglass.java ├── README.md ├── Stack │ ├── Maximum Area Histogram │ │ ├── MaximumAreaHistogram.java │ │ └── README.md │ ├── Maximum Element │ │ ├── MaximumElement.java │ │ └── README.md │ ├── README.md │ └── Sort Stack │ │ ├── README.md │ │ └── SortStack.java └── Strings │ ├── Buddy String │ ├── BuddyString.java │ └── README.md │ ├── Hamming Distance │ ├── HammingDistance.java │ └── README.md │ ├── Help Me Play │ ├── HelpMePlay.java │ └── README.md │ ├── Longest Substring without Repeating Char │ ├── LongestSubstringWithoutRepeatingChar.java │ └── README.md │ ├── README.md │ ├── Reverse In Parentheses │ ├── README.md │ └── ReverseInParentheses.java │ ├── Valid Palindrome │ ├── README.md │ └── ValidPalindrome.java │ ├── Valid Word Abbreviation │ ├── README.md │ └── ValidWordAbbreviation.java │ └── ZigZag Conversion │ ├── README.md │ └── ZigZagConversion.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .DS_Store -------------------------------------------------------------------------------- /Chapter-02/lowArrayApp.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Solved by Sumeet Kulkarni (https://github.com/sumeetk321) 3 | */ 4 | 5 | class LowArray { 6 | private long[] a; 7 | 8 | public LowArray(int len) { 9 | a = new long[len]; 10 | } 11 | 12 | public void set(int index, long val) { 13 | a[index] = val; 14 | } 15 | 16 | public long get(int index) { 17 | return a[index]; 18 | } 19 | } 20 | 21 | class lowArrayApp { 22 | public static void main(String[] args) { 23 | LowArray arr; 24 | arr = new LowArray(100); 25 | int size = 0; 26 | int j; 27 | arr.set(0, 12); 28 | arr.set(1, 2819); 29 | arr.set(2, 29); 30 | arr.set(3, 315); 31 | arr.set(4, 2211); 32 | arr.set(5, 1); 33 | arr.set(6, 191); 34 | arr.set(7, 0); 35 | arr.set(8, 47); 36 | arr.set(9, 317); 37 | size = 10; 38 | for (j = 0; j < size; j++) { 39 | System.out.print(arr.get(j) + " "); 40 | } 41 | System.out.println(""); 42 | int searchKey = 78; 43 | for (j = 0; j < size; j++) { 44 | if (arr.get(j) == searchKey) { 45 | break; 46 | } 47 | } 48 | if (j == size) { 49 | System.out.println("Can’t find " + searchKey); 50 | } else { 51 | System.out.println("Found " + searchKey); 52 | } 53 | for (j = 0; j < size; j++) { 54 | if (arr.get(j) == 191) { 55 | break; 56 | } 57 | } 58 | for (int k = j; k < size; k++) { 59 | arr.set(k, arr.get(k + 1)); 60 | } 61 | size--; 62 | for (j = 0; j < size; j++) { 63 | System.out.print(arr.get(j) + " "); 64 | } 65 | System.out.println(""); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Chapter-03/bubbleSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | 4 | Solution for Programming Projects 5 | 3.1, 3.4 6 | */ 7 | 8 | 9 | class ArrayBub { 10 | private long[] a; 11 | private int nElems; 12 | 13 | public ArrayBub(int max) { 14 | a = new long[max]; 15 | nElems = 0; 16 | } 17 | 18 | public void insert(long value) { 19 | a[nElems] = value; 20 | nElems++; 21 | } 22 | 23 | public void display() { 24 | for(int j=0; j1; out--) 36 | for(in=0; in a[in+1] ) 38 | swap(in, in+1); 39 | } 40 | 41 | 42 | public void biDirectionBubbleSort() { 43 | int out=nElems-1, in, _out=0; 44 | 45 | boolean isSwap = true; 46 | 47 | while(isSwap) { 48 | isSwap = false; 49 | 50 | for(in=_out; in a[in+1] ) { 52 | swap(in, in+1); 53 | isSwap=true; 54 | } 55 | } 56 | 57 | for(in=out-1; in>_out; in--) { 58 | if(a[in] < a[in-1]) { 59 | swap(in, in-1); 60 | isSwap=true; 61 | } 62 | } 63 | 64 | _out++; 65 | out--; 66 | } 67 | 68 | } 69 | 70 | public void oddEvenSort() { 71 | boolean isSwap=true; 72 | 73 | while(isSwap) { 74 | isSwap = false; 75 | 76 | for(int in=1; in a[in+1] ) { 78 | swap(in, in+1); 79 | isSwap=true; 80 | } 81 | } 82 | 83 | for(int in=0; in a[in+1] ) { 85 | swap(in, in+1); 86 | isSwap=true; 87 | } 88 | } 89 | 90 | } 91 | 92 | } 93 | 94 | private void swap(int one, int two) { 95 | long temp = a[one]; 96 | a[one] = a[two]; 97 | a[two] = temp; 98 | 99 | } 100 | 101 | } 102 | 103 | class bubbleSort { 104 | public static void main(String[] args) { 105 | int maxSize = 100; 106 | ArrayBub arr = new ArrayBub(maxSize); 107 | 108 | arr.insert(77); 109 | arr.insert(99); 110 | arr.insert(44); 111 | arr.insert(55); 112 | arr.insert(22); 113 | arr.insert(88); 114 | arr.insert(11); 115 | arr.insert(00); 116 | arr.insert(66); 117 | arr.insert(33); 118 | 119 | arr.display(); 120 | 121 | // arr.oddEvenSort(); 122 | 123 | // arr.display(); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Chapter-03/selectionSort.java: -------------------------------------------------------------------------------- 1 | class ArraySel { 2 | private long[] a; 3 | private int nElems; 4 | 5 | public ArraySel(int max) { 6 | a = new long[max]; 7 | nElems = 0; 8 | } 9 | 10 | public void insert(long value) { 11 | a[nElems] = value; 12 | nElems++; 13 | } 14 | 15 | public void display() { 16 | for(int j=0; j 1) { 35 | Node newN = new Node(-1); 36 | p.fLink = newN; 37 | p = newN; 38 | col--; 39 | } 40 | } 41 | 42 | public Node getStart() { 43 | return start; 44 | } 45 | } 46 | 47 | 48 | class Matrix { 49 | private int n; //row 50 | private int m; //col 51 | private Row[] r; 52 | private Node start; 53 | 54 | public Matrix(int n, int m) { 55 | this.n = n; 56 | this.m = m; 57 | start = null; 58 | r = new Row[n]; 59 | 60 | check(); 61 | generateMatix(); 62 | } 63 | 64 | private void check() { 65 | if(n <= 0 || m <= 0) { 66 | System.out.println("Value of 'n' & 'm' must be greater than 0"); 67 | System.exit(0); 68 | } 69 | } 70 | 71 | private void generateMatix() { 72 | 73 | for(int i=0; i n || y > m || x <= 0 || y <= 0) { 96 | System.out.println("(x,y) such that 0 < x < "+ n + " and 0 < y < " + m + "."); 97 | return; 98 | } 99 | 100 | for(int row=1; row1) { 105 | cell = cell.fLink; 106 | col--; 107 | } 108 | 109 | cell.data = data; 110 | } 111 | 112 | public void display() { 113 | Node row = start; 114 | 115 | while(row != null) { 116 | Node cell = row; 117 | while(cell != null) { 118 | System.out.print(cell.data + " "); 119 | cell = cell.fLink; 120 | } 121 | System.out.println(); 122 | row = row.dLink; 123 | } 124 | 125 | System.out.println(); 126 | } 127 | } 128 | 129 | class MatrixList { 130 | public static void main(String[] args) { 131 | Matrix m = new Matrix(2,2); 132 | m.display(); //Empty 133 | 134 | //Value filling 135 | m.insert(1,0,23); 136 | m.insert(1,2,13); 137 | m.insert(2,1,43); 138 | m.insert(2,2,41); 139 | m.display(); //After filling 140 | } 141 | } -------------------------------------------------------------------------------- /Chapter-05/PriorityLinkedlist.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | 4 | Solution for Programming Project 5 | 5.1 6 | */ 7 | 8 | class Node { 9 | int data; 10 | Node next; 11 | 12 | public Node(int data) { 13 | this.data = data; 14 | this.next = null; 15 | } 16 | } 17 | 18 | class SortedLinkedList { 19 | Node start; 20 | 21 | 22 | public SortedLinkedList() { 23 | start = null; 24 | } 25 | 26 | public void insert(int data) { 27 | Node newNode = new Node(data); 28 | 29 | Node p,p1; 30 | p = p1 = start; 31 | 32 | if(start == null) { 33 | start = newNode; 34 | } else { 35 | 36 | while(p != null && data > p.data) { 37 | p1 = p; 38 | p = p.next; 39 | } 40 | 41 | if(p == null) { 42 | p1.next = newNode; 43 | 44 | } else if(p1 == p) { 45 | newNode.next = p; 46 | start = newNode; 47 | 48 | } else { 49 | newNode.next = p; 50 | p1.next = newNode; 51 | } 52 | } 53 | } 54 | 55 | public int delete() { 56 | int temp; 57 | Node p = start; 58 | 59 | temp = p.data; 60 | start = p.next; 61 | p.next = null; 62 | return temp; 63 | } 64 | 65 | public void display() { 66 | Node n = start; 67 | 68 | while(n != null) { 69 | System.out.print(n.data + " "); 70 | n = n.next; 71 | } 72 | System.out.println(); 73 | } 74 | } 75 | 76 | class PriorityQueue { 77 | 78 | SortedLinkedList sortList; 79 | 80 | public PriorityQueue() { 81 | sortList = new SortedLinkedList(); 82 | } 83 | 84 | public void insert(int data) { 85 | sortList.insert(data); 86 | } 87 | 88 | public int delete() { 89 | return sortList.delete(); 90 | } 91 | 92 | public void display() { 93 | sortList.display(); 94 | } 95 | } 96 | 97 | class PriorityLinkedlist { 98 | public static void main(String[] args) { 99 | PriorityQueue pq = new PriorityQueue(); 100 | 101 | pq.insert(10); 102 | pq.insert(5); 103 | pq.insert(7); 104 | pq.insert(27); 105 | pq.insert(25); 106 | pq.insert(35); 107 | 108 | pq.display(); 109 | 110 | pq.delete(); 111 | pq.delete(); 112 | pq.display(); 113 | } 114 | } 115 | 116 | -------------------------------------------------------------------------------- /Chapter-05/ReverseDoubleLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: vanshbhasin157 (https://github.com/vanshbhasin157) 3 | Modified By: Sandeep Ranjan (1641012352) 4 | */ 5 | 6 | class Node { 7 | 8 | int data; 9 | Node next, prev; 10 | 11 | Node(int data) { 12 | this.data = data; 13 | next = prev = null; 14 | } 15 | } 16 | 17 | class DLL { 18 | 19 | private Node head; 20 | 21 | public DLL() { 22 | head = null; 23 | } 24 | 25 | void reverse() { 26 | Node temp = null; 27 | Node current = head; 28 | 29 | while (current != null) 30 | { 31 | temp = current.prev; 32 | current.prev = current.next; 33 | current.next = temp; 34 | current = current.prev; 35 | } 36 | 37 | if (temp != null) { 38 | head = temp.prev; 39 | } 40 | } 41 | 42 | public void insert(int data) { 43 | 44 | Node new_node = new Node(data); 45 | new_node.next = head; 46 | 47 | if (head != null) { 48 | head.prev = new_node; 49 | } 50 | 51 | head = new_node; 52 | } 53 | 54 | void printList() { 55 | Node p = head; 56 | while (p != null) { 57 | System.out.print(p.data + " "); 58 | p = p.next; 59 | } 60 | } 61 | } 62 | 63 | class ReverseDoubleLinkedList { 64 | 65 | public static void main(String[] args) { 66 | DLL list = new DLL(); 67 | 68 | 69 | list.insert(2); 70 | list.insert(4); 71 | list.insert(8); 72 | list.insert(10); 73 | 74 | System.out.println("Original linked list "); 75 | list.printList(); 76 | 77 | list.reverse(); 78 | System.out.println(""); 79 | System.out.println("The reversed Linked List is "); 80 | list.printList(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Chapter-05/StackList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | 4 | Solution for Programming Project 5 | 5.4 6 | */ 7 | 8 | class Node { 9 | int data; 10 | Node link; 11 | 12 | Node(int data) { 13 | this.data = data; 14 | this.link = null; 15 | } 16 | } 17 | 18 | class CircularLinklist { 19 | private Node current; 20 | 21 | public CircularLinklist() { 22 | current = null; 23 | } 24 | 25 | public void insert(int data) { 26 | Node newNode = new Node(data); 27 | 28 | if(current == null) { 29 | newNode.link = newNode; 30 | current = newNode; 31 | } else { 32 | newNode.link = current.link; 33 | current.link = newNode; 34 | current = newNode; 35 | } 36 | } 37 | 38 | public void delete() { 39 | Node p = current; 40 | 41 | if(p.link == current) { 42 | current = null; 43 | } else { 44 | do { 45 | p = p.link; 46 | } while(p.link != current); 47 | 48 | p.link = current.link; 49 | current = p; 50 | } 51 | } 52 | 53 | public void display() { 54 | Node p = current; 55 | 56 | if(current != null) { 57 | do { 58 | p = p.link; 59 | 60 | System.out.print(p.data + " "); 61 | } while(p != current); 62 | System.out.println(); 63 | } else { 64 | System.out.println("List Empty"); 65 | } 66 | } 67 | } 68 | 69 | class Stack { 70 | private CircularLinklist cll; 71 | private int size; 72 | private int ele; 73 | 74 | public Stack(int size) { 75 | cll = new CircularLinklist(); 76 | this.size = size; 77 | this.ele = -1; 78 | } 79 | 80 | public void insert(int data) { 81 | if(isFull()) { 82 | System.out.println("Stack Full"); 83 | } else { 84 | cll.insert(data); 85 | ele++; 86 | } 87 | } 88 | 89 | public void delete() { 90 | if(isEmpty()) { 91 | System.out.println("Stack Empty"); 92 | } else { 93 | cll.delete(); 94 | ele--; 95 | } 96 | } 97 | 98 | private boolean isFull() { 99 | return ele == (size-1); 100 | } 101 | 102 | private boolean isEmpty() { 103 | return ele == -1; 104 | } 105 | 106 | public void display() { 107 | if(isEmpty()) { 108 | System.out.println("Stack Empty"); 109 | } else { 110 | cll.display(); 111 | } 112 | } 113 | } 114 | 115 | class StackList { 116 | public static void main(String[] args) { 117 | Stack theStack = new Stack(5); 118 | 119 | theStack.insert(10); 120 | theStack.insert(20); 121 | theStack.insert(30); 122 | theStack.insert(40); 123 | theStack.insert(50); 124 | 125 | theStack.display(); 126 | 127 | theStack.delete(); 128 | theStack.insert(60); 129 | 130 | theStack.display(); 131 | } 132 | } -------------------------------------------------------------------------------- /Chapter-06/(6.5).java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | import java.util.*; 3 | 4 | // Method 1: 5 | class Combinations{ 6 | 7 | static void makeCombiUtil(Vector tmp, int n, int left, int k) 8 | { 9 | if (k == 0) { 10 | System.out.println(tmp); 11 | return; 12 | } 13 | 14 | for (int i = left; i <= n; ++i) 15 | { 16 | tmp.add(i); 17 | makeCombiUtil(tmp, n, i + 1, k - 1); 18 | 19 | tmp.remove(tmp.size()-1); 20 | } 21 | } 22 | 23 | static void makeCombi(int n, int k) 24 | { 25 | 26 | Vector tmp=new Vector<>(); 27 | makeCombiUtil(tmp, n, 1, k); 28 | } 29 | 30 | 31 | public static void main(String args[]) 32 | { 33 | // given number 34 | Scanner s=new Scanner(System.in); 35 | int n = s.nextInt(); 36 | int k = s.nextInt(); 37 | makeCombi(n, k); 38 | 39 | } 40 | } 41 | 42 | //Method 2: 43 | class Comb { 44 | 45 | static void combination(int arr[], int data[], int start, 46 | int end, int index, int r) 47 | { 48 | if (index == r) 49 | { 50 | for (int j=0; j= r-index; i++) 56 | { 57 | data[index] = arr[i]; 58 | combination(arr, data, i+1, end, index+1, r); 59 | } 60 | } 61 | 62 | static void print(int arr[], int n, int r) 63 | { 64 | int data[]=new int[r]; 65 | combination(arr, data, 0, n-1, 0, r); 66 | } 67 | 68 | public static void main (String[] args) { 69 | Scanner s=new Scanner(System.in); 70 | int n=s.nextInt(); 71 | int i=0,j=0; 72 | int arr[]=new int[n]; 73 | for(i=1;i<=n;i++) 74 | { 75 | arr[j++]=i; 76 | } 77 | int r = s.nextInt(); 78 | print(arr, n, r); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Chapter-06/Anagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class Anagram { 6 | static char[] arr; 7 | static int size; 8 | 9 | public static void main(String[] args) { 10 | String input = "STOP"; 11 | size = input.length(); 12 | arr = new char[size]; 13 | 14 | for(int i=0; i high) 32 | return size; 33 | 34 | else { 35 | if(arr[mid] < key) 36 | return binarySearch(key, mid+1, high); 37 | else 38 | return binarySearch(key, low, mid-1); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter-06/Factorial.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class Factorial { 6 | public static void main(String[] args) { 7 | final int FNO = 5; 8 | 9 | System.out.println(FNO + "! is " + fact(FNO)); 10 | } 11 | 12 | public static int fact(int n){ 13 | if(n==1) return 1; 14 | else 15 | return( n * fact(n-1) ); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-06/Knapsack/Knapsack_MultiSolution.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Ganesh varma (https://github.com/gane5hvarma) 3 | Modified By: Sandeep Ranjan (1641012352) 4 | */ 5 | 6 | class Knapsack_MultiSolution { 7 | public static int length; 8 | public static int[] weights; 9 | 10 | public static boolean knapsack(int startPoint,int capacity){ 11 | if(weights[startPoint]==capacity){ 12 | System.out.print(weights[startPoint] + " "); 13 | return true; 14 | } 15 | else{ 16 | if(weights[startPoint]"); 42 | for(int i=0; i "); 49 | knapsack(0,capacity); 50 | 51 | } 52 | } -------------------------------------------------------------------------------- /Chapter-06/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class MergeSort { 6 | static int[] arr; 7 | static int size; 8 | 9 | public static void main(String[] args) { 10 | arr = new int[]{14, 2, 52, 36, 34, 78}; 11 | size = arr.length; 12 | 13 | System.out.println("Before sort"); 14 | 15 | for(int i : arr) 16 | System.out.print(i + " "); 17 | 18 | System.out.println(); 19 | 20 | mergeSort(0,size-1); 21 | 22 | System.out.println("After sort"); 23 | 24 | for(int i : arr) 25 | System.out.print(i + " "); 26 | 27 | } 28 | 29 | public static void mergeSort(int low, int high) { 30 | if(low < high) { 31 | int mid = (low+high) / 2; 32 | 33 | mergeSort(low, mid); 34 | mergeSort(mid+1, high); 35 | 36 | merge(low, mid, high); 37 | } 38 | } 39 | 40 | public static void merge(int low,int mid, int high) { 41 | 42 | int n1 = mid - low + 1; 43 | int n2 = high - mid; 44 | 45 | int[] left = new int[n1]; 46 | int[] right = new int[n2]; 47 | 48 | for (int i=0; iinter 18 | System.out.println("Disk " + topN +" from " + from + " to "+ to); 19 | doTowers(topN-1, inter, from, to); // inter-->to 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter-06/Triangular.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class Triangular { 6 | public static void main(String[] args) { 7 | final int TNO = 5; 8 | 9 | System.out.println(TNO + " Triangular is " + triangle(TNO)); 10 | } 11 | 12 | public static int triangle(int n){ 13 | if(n==1) return 1; 14 | else 15 | return( n + triangle(n-1) ); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter-07/Partition.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | Modified By: Siddhart Saurabh 4 | 5 | Solution for Programming Projects 6 | 7.1, 7 | */ 8 | 9 | class ArrayPart { 10 | private int[] a; 11 | private int nElems; 12 | 13 | public ArrayPart(int max) { 14 | a = new int[max]; 15 | nElems = 0; 16 | } 17 | 18 | public void insert(int value) { 19 | a[nElems] = value; 20 | nElems++; 21 | } 22 | 23 | public int size() { 24 | return nElems; 25 | } 26 | 27 | public void display() { 28 | for(int j=0; j l && a[--right] > pivot); 40 | 41 | if(left >= right) break; 42 | else swap(left, right); 43 | } 44 | 45 | return left; 46 | } 47 | 48 | // 7.1 49 | public int partitionIt(int left, int right) { 50 | int pivot = a[right]; 51 | int leftPtr = left - 1; 52 | int rightPtr = right; 53 | 54 | while(true) { 55 | while(a[++leftPtr] < pivot); 56 | 57 | while(rightPtr > left && a[--rightPtr] > pivot); 58 | if(leftPtr >= rightPtr) 59 | break; 60 | else 61 | swap(leftPtr, rightPtr); 62 | } 63 | 64 | swap(leftPtr, right); 65 | return leftPtr; 66 | } 67 | 68 | private void swap(int i, int j){ 69 | int temp = a[i]; 70 | a[i] = a[j]; 71 | a[j] = temp; 72 | } 73 | } 74 | 75 | class Partition { 76 | public static void main(String[] args) { 77 | int maxSize = 10; 78 | ArrayPart arr = new ArrayPart(maxSize); 79 | 80 | arr.insert(77); 81 | arr.insert(99); 82 | arr.insert(44); 83 | arr.insert(55); 84 | arr.insert(22); 85 | arr.insert(88); 86 | arr.insert(11); 87 | arr.insert(00); 88 | arr.insert(66); 89 | arr.insert(33); 90 | 91 | arr.display(); 92 | 93 | int pivot = 50; 94 | int partIndex = arr.doPartition(0, arr.size()-1, pivot); 95 | System.out.println("Pivot: " + pivot); 96 | System.out.println("Less that Pivot: [0," + (partIndex-1) + "]"); 97 | System.out.println("More that Pivot: [" + partIndex + "," + (arr.size()-1) +"]"); 98 | 99 | arr.display(); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Chapter-07/QuickSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class ArrayQuick { 6 | private int[] arr; 7 | private int nElems; 8 | 9 | public ArrayQuick(int max) { 10 | arr = new int[max]; 11 | nElems = 0; 12 | } 13 | 14 | public void insert(int value) { 15 | arr[nElems] = value; 16 | nElems++; 17 | } 18 | 19 | public void display() { 20 | for(int j=0; j 0 && arr[--rightPtr] > pivot); 46 | 47 | if(leftPtr >= rightPtr) 48 | break; 49 | else 50 | swap(leftPtr, rightPtr); 51 | } 52 | 53 | swap(leftPtr, right); 54 | 55 | return leftPtr; 56 | } 57 | 58 | private void swap(int indx1, int indx2) { 59 | int temp = arr[indx1]; 60 | arr[indx1] = arr[indx2]; 61 | arr[indx2] = temp; 62 | } 63 | } 64 | 65 | 66 | class QuickSort { 67 | public static void main(String[] args) { 68 | int maxSize = 10; 69 | ArrayQuick a = new ArrayQuick(maxSize); 70 | 71 | a.insert(77); 72 | a.insert(99); 73 | a.insert(44); 74 | a.insert(55); 75 | a.insert(22); 76 | a.insert(88); 77 | a.insert(11); 78 | a.insert(86); 79 | a.insert(66); 80 | a.insert(33); 81 | 82 | a.quickSort(0, maxSize-1); 83 | a.display(); 84 | 85 | } 86 | } -------------------------------------------------------------------------------- /Chapter-07/shellSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Solved By: Sandeep Ranjan (1641012352) 3 | */ 4 | 5 | class ArrayShell { 6 | private int[] a; 7 | private int nElems; 8 | 9 | public ArrayShell(int max) { 10 | a = new int[max]; 11 | nElems = 0; 12 | } 13 | 14 | public void insert(int value) { 15 | a[nElems] = value; 16 | nElems++; 17 | } 18 | 19 | public void display() { 20 | for(int j=0; j 0) { 32 | for(int out=h; out h-1 && a[in - h] >= temp) { 37 | a[in] = a[in-h]; 38 | in -= h; 39 | } 40 | 41 | a[in] = temp; 42 | } 43 | 44 | // Reducing Knuth’s 45 | h = (h-1) / 3; 46 | } 47 | 48 | return; 49 | } 50 | } 51 | 52 | class ShellSort { 53 | public static void main(String[] args) { 54 | int maxSize = 11; 55 | ArrayShell arr = new ArrayShell(maxSize); 56 | 57 | arr.insert(77); 58 | arr.insert(99); 59 | arr.insert(44); 60 | arr.insert(55); 61 | arr.insert(22); 62 | arr.insert(88); 63 | arr.insert(11); 64 | arr.insert(00); 65 | arr.insert(66); 66 | arr.insert(33); 67 | 68 | arr.shellSort(); 69 | arr.display(); 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Chapter-08/SegmentTree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | class SegmentTree 5 | { 6 | int st[]; 7 | Segment(int []arr, int n) 8 | { 9 | int x = (int) Math.ceil((Math.log(n)/Math.log(2))); 10 | int max_size = 2 *(int) (Math.pow(2,x) - 1); 11 | st = new int[max_size]; 12 | 13 | constSegmentUtil(arr,0,n-1,0); 14 | } 15 | 16 | int constSegmentUtil(int []arr, int ss,int se,int si) 17 | { 18 | if(ss == se) 19 | { 20 | st[si] = arr[ss]; 21 | return arr[ss]; 22 | } 23 | int mid = getMid(ss,se); 24 | st[si] = max(constSegmentUtil(arr,ss,mid,2*si+1),constSegmentUtil(arr,mid+1,se,2*si+2)); 25 | return st[si]; 26 | } 27 | 28 | int getMid(int s,int e) 29 | { 30 | return s + (e - s)/2; 31 | } 32 | 33 | int max(int a,int b) 34 | { 35 | if(a > b) 36 | { 37 | return a; 38 | } 39 | else{ 40 | return b; 41 | } 42 | } 43 | 44 | void print(){ 45 | for (int i=0;i=se) 54 | { 55 | return st[si]; 56 | } 57 | 58 | if(seqe) 59 | { 60 | return 0; 61 | } 62 | 63 | int mid = getMid(ss,se); 64 | 65 | return max(getMaxUtil(ss,mid,qs,qe,2*si+1),getMaxUtil(mid+1,se,qs,qe,2*si+2)); 66 | } 67 | 68 | 69 | int getMax(int n,int qs,int qe){ 70 | 71 | if(qs > qe || qs < 0 || qe > n-1){ 72 | return -1; 73 | } 74 | 75 | return getMaxUtil(0,n-1,qs,qe,0); 76 | } 77 | 78 | public static void main (String[] args) throws java.lang.Exception 79 | { 80 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 81 | int t = Integer.parseInt(br.readLine());//for testcase 82 | String []temp = br.readLine().split(" ");//taking array as string 83 | int []arr = new int[t]; 84 | for(int i=0;i"); 46 | System.out.print("1"); 47 | return 1; 48 | } 49 | else 50 | return 0; 51 | } 52 | 53 | for(int v=1;v10 30 | 31 | ## Example: 32 | 33 | **Input** 34 | 35 | ```java 36 | 5 37 | 1000000001 1000000002 1000000003 1000000004 1000000005 38 | ``` 39 | 40 | Output 41 | 42 | ```java 43 | 5000000015 44 | ``` 45 | 46 | **Note:** The range of the 32 bit integer is (-231) to (231 - 1) or [-2147483648, 2147483648]. When we add several integer values, the resulting sum might exceed the above range. You might need to use long int C/C++/Java to store such sums. 47 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Arrange Students/ArrangeStudents.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ArrangeStudents { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | 7 | int t = sc.nextInt(); 8 | 9 | while(t-- > 0) { 10 | int n = sc.nextInt(); 11 | 12 | List a = new ArrayList<>(); 13 | 14 | for (int i = 0; i < n; i++) { 15 | a.add(sc.nextInt()); 16 | } 17 | 18 | List b = new ArrayList<>(); 19 | 20 | for (int i = 0; i < n; i++) { 21 | b.add(sc.nextInt()); 22 | } 23 | 24 | String result = arrangeStudents(a, b); 25 | System.out.println(result); 26 | } 27 | } 28 | 29 | public static String arrangeStudents(List a, List b) { 30 | int size = a.size(); 31 | 32 | if(size == 1) return "YES"; 33 | 34 | Collections.sort(a); 35 | Collections.sort(b); 36 | 37 | List merged = new ArrayList<>(); 38 | List merged_sorted = new ArrayList<>(); 39 | 40 | for(int i=0; i(merged); 46 | Collections.sort(merged_sorted); 47 | 48 | if(merged.equals(merged_sorted)) return "YES"; 49 | 50 | merged = new ArrayList<>(); 51 | 52 | for(int i=0; i max){ max = scores[i]; countMax++; } 16 | if(scores[i] < min){ min = scores[i]; countMin++; } 17 | } 18 | result[0] = countMax; result[1] = countMin; 19 | return result; 20 | 21 | } 22 | 23 | private static final Scanner scanner = new Scanner(System.in); 24 | 25 | public static void main(String[] args) throws IOException { 26 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 27 | 28 | int n = scanner.nextInt(); 29 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 30 | 31 | int[] scores = new int[n]; 32 | 33 | String[] scoresItems = scanner.nextLine().split(" "); 34 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 35 | 36 | for (int i = 0; i < n; i++) { 37 | int scoresItem = Integer.parseInt(scoresItems[i]); 38 | scores[i] = scoresItem; 39 | } 40 | 41 | int[] result = breakingRecords(scores); 42 | 43 | for (int i = 0; i < result.length; i++) { 44 | bufferedWriter.write(String.valueOf(result[i])); 45 | 46 | if (i != result.length - 1) { 47 | bufferedWriter.write(" "); 48 | } 49 | } 50 | 51 | bufferedWriter.newLine(); 52 | 53 | bufferedWriter.close(); 54 | 55 | scanner.close(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Find All Numbers Disappeared In An Array/FindAllNumbersDisappearedInAnArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class FindAllNumbersDisappearedInAnArray { 4 | public static void main(String[] args) { 5 | int a[] = {4,3,2,7,8,2,3,1}; 6 | int n = a.length; 7 | 8 | Arrays.sort(a); 9 | 10 | int sum = ((n+1)*n)/2; 11 | 12 | int p = 1; 13 | 14 | List list = new ArrayList(); 15 | 16 | int prev = 0; 17 | for(int i = 0; i= 0 && y >= 0 && x < n && y < m && board[x][y] == 0) 36 | count++; 37 | } 38 | 39 | return count; 40 | 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Practice Problems/Arrays/Knight's Possible Moves/README.md: -------------------------------------------------------------------------------- 1 | # Knight's Possible Moves 2 | 3 | **Problem from GeekForGeeks** 4 | 5 | Given a chess board of dimension `m * n`. Find number of possible moves where knight can be moved on a chessboard from given position. If `board[i][j] = 1` then the block is filled by something else, otherwise empty. 6 | 7 | Assume that board consist of all pieces of same color, i.e., there are no blocks being attacked.. 8 | 9 | Solve it without **division operator** and in `O(n)` 10 | 11 | ### **Example** 12 | 13 | **Input**: 14 | 15 | ``` java 16 | board[][] = {{1, 0, 1, 0}, 17 | {0, 1, 1, 1}, 18 | {1, 1, 0, 1}, 19 | {0, 1, 1, 1}} 20 | pos = (2, 2) 21 | ``` 22 | 23 | **Output:**: 24 | 25 | ``` java 26 | 4 27 | ``` 28 | 29 | 30 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Maximum Subarray/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | class MaximunSubarray { 2 | public static void main(String[] args) { 3 | 4 | int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3}; 5 | 6 | System.out.println(maxSubArray(arr)); 7 | } 8 | 9 | public static int maxSubArray(int[] arr) { 10 | int n = arr.length; 11 | int[] dp = new int[n]; 12 | dp[0] = arr[0]; 13 | int max = dp[0]; 14 | 15 | for(int i = 1; i < n; i++) { 16 | dp[i] = arr[i] + ( dp[i-1] > 0 ? dp[i-1] : 0); 17 | max = Math.max(max, dp[i]); 18 | } 19 | 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Maximum Subarray/README.md: -------------------------------------------------------------------------------- 1 | # Maximum Subarray 2 | 3 | **Problem from GeeksForGeeks** 4 | 5 | Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. 6 | 7 | ### Example: 8 | **Input**: `[-2, -3, 4, -1, -2, 1, 5, -3]` 9 | 10 | **Output:**: `7` 11 | 12 | **Explanation**: The contiguous subarray `[4, -1, -2, 1, 5]` has the largest sum = `7`. 13 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/MaximumCircularSum/MaximumCircularSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class MaximumCircularSum { 4 | //form the maximum continous sum possible in circular array 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | int[] a = new int[n]; 10 | for (int i = 0; i < n; i++) { 11 | a[i] = sc.nextInt(); 12 | } 13 | 14 | // circular sum = Math.max(max subarray,total sum-minimum sum) 15 | 16 | // max subarray= if the maximum lies in between i.e. no point of circular array 17 | // use normal kadne theorem 18 | int mxc = a[0]; 19 | int mxg = a[0]; 20 | for (int i = 1; i < n; i++) { 21 | mxc = Math.max(a[i], mxc + a[i]); 22 | if (mxc > mxg) { 23 | mxg = mxc; 24 | } 25 | } 26 | 27 | //if subarray is circular i.e. wrapped therefore find lowest sum with the help of same array and subtract from total 28 | // min subarray 29 | int mic = a[0]; 30 | int mig = a[0]; 31 | for (int i = 1; i < n; i++) { 32 | mic = Math.min(a[i], mic + a[i]); 33 | if (mic < mig) { 34 | mig = mic; 35 | } 36 | } 37 | 38 | 39 | int to = 0; 40 | for(int i= 0;i= prev) { 17 | prev = nums[i]; 18 | continue; 19 | } 20 | 21 | if(c) return false; 22 | c = true; 23 | 24 | if (i == 1 || nums[i] >= nums[i - 2]) { 25 | prev = nums[i]; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Non Decreasing Array/README.md: -------------------------------------------------------------------------------- 1 | # Non Decreasing Array 2 | 3 | **Problem from LeetCode** 4 | 5 | Given an array with n integers, your task is to check if it could become **non-decreasing** by modifying at most 1 element. 6 | 7 | We define an array is non-decreasing if `array[i] <= array[i + 1]` holds for every **i** `(1 <= i < n)`. 8 | 9 | **Note**: The n belongs to `[1, 10,000]`. 10 | 11 | ### Example: 12 | **Input**: `[4,2,3]` 13 | 14 | **Output:**: `true` 15 | 16 | **Explanation**: You could modify the first 4 to 1 to get a non-decreasing array. 17 | 18 | **Input**: `[4,2,1]` 19 | 20 | **Output:**: `false` 21 | 22 | **Explanation**: You can't get a non-decreasing array by modify at most one element. 23 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Palindrome/README.md: -------------------------------------------------------------------------------- 1 | # Palindrome with Stack and Queue 2 | 3 | ## Use Stack and Queue to check whether a String is a palindrome 4 | 5 | Hint: 6 | 7 | Example word: *dad* 8 | 9 | stack: push(d), push(a), push(d) : d, a, d 10 | 11 | queue: add(d), add(a), add(d) : d, a, d 12 | 13 | #### Examples: 14 | 15 | // should return true 16 | System.out.println(checkForPalindrome("abccba")); 17 | // should return true 18 | System.out.println(checkForPalindrome("Was it a car or a cat I saw?")); 19 | // should return true 20 | System.out.println(checkForPalindrome("I did, did I?")); 21 | // should return false 22 | System.out.println(checkForPalindrome("hello")); 23 | // should return true 24 | System.out.println(checkForPalindrome("Don't nod")); 25 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Palindrome/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | 3 | public static boolean checkForPalindrome(String string) { 4 | 5 | LinkedList stack = new LinkedList(); 6 | LinkedList queue = new LinkedList(); 7 | String lowerCase = string.toLowerCase(); 8 | 9 | for (int i = 0; i < lowerCase.length(); i++) { 10 | char c = lowerCase.charAt(i); 11 | if (c >= 'a' && c <= 'z') { 12 | queue.addLast(c); 13 | stack.push(c); 14 | } 15 | } 16 | 17 | while (!stack.isEmpty()) { 18 | if (!stack.pop().equals(queue.removeFirst())) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/PlusMInus/PlusMInus.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | 12 | static void plusMinus(int[] arr) { 13 | 14 | int dimension = arr.length; 15 | double positives = 0; 16 | double negatives = 0; 17 | double zeros = 0; 18 | 19 | for (int i = 0; i < dimension; i++) { 20 | if (arr[i] > 0) { 21 | positives++; 22 | } else if (arr[i] < 0) { 23 | negatives++; 24 | } else { 25 | zeros++; 26 | } 27 | } 28 | 29 | positives /= dimension; 30 | negatives /= dimension; 31 | zeros /= dimension; 32 | 33 | System.out.printf("%.6f\n%.6f\n%.6f\n", positives, negatives, zeros); 34 | 35 | } 36 | 37 | private static final Scanner scanner = new Scanner(System.in); 38 | 39 | public static void main(String[] args) { 40 | int n = scanner.nextInt(); 41 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 42 | 43 | int[] arr = new int[n]; 44 | 45 | String[] arrItems = scanner.nextLine().split(" "); 46 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 47 | 48 | for (int i = 0; i < n; i++) { 49 | int arrItem = Integer.parseInt(arrItems[i]); 50 | arr[i] = arrItem; 51 | } 52 | 53 | plusMinus(arr); 54 | 55 | scanner.close(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/PlusMInus/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | # PLUS MINUS HACKERRANK PROBLEM 3 | 4 | ## Problem statement 5 | 6 | Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal. 7 | 8 | e.g., array =[1,1,0,-1,-1] i.e., n=5 elements 9 | 10 | so positives= 2/5, negatives= 2/5 and zeros = 1/5 11 | 12 | then Output : 13 | 0.400000 14 | 0.400000 15 | 0.200000 16 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Product Array/ProductArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ProductArray { 4 | public static void main(String[] args) { 5 | int[] arr = {10, 3, 5, 6, 2}; 6 | int n = arr.length; 7 | 8 | int[] prod = productArray(arr, n); 9 | 10 | for (int i = 0; i < n; i++) 11 | System.out.print(prod[i] + " "); 12 | } 13 | 14 | public static int[] productArray(int[] arr, int n) { 15 | if (n == 1) { 16 | return new int[]{0}; 17 | } 18 | 19 | int left[] = new int[n]; 20 | int right[] = new int[n]; 21 | int prod[] = new int[n]; 22 | 23 | left[0] = 1; 24 | 25 | right[n - 1] = 1; 26 | 27 | for (int i = 1; i < n; i++) 28 | left[i] = arr[i - 1] * left[i - 1]; 29 | 30 | for (int i = n - 2; i >= 0; i--) 31 | right[i] = arr[i + 1] * right[i + 1]; 32 | 33 | for (int i = 0; i < n; i++) 34 | prod[i] = left[i] * right[i]; 35 | 36 | return prod; 37 | 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /Practice Problems/Arrays/Product Array/README.md: -------------------------------------------------------------------------------- 1 | # Product Array 2 | 3 | **Problem from PrepBytes** 4 | 5 | Given an array of `n` integers, construct a Product Array `prod[]` such that `prod[i]` is equal to the product of all the elements of `arr[]` except `arr[i]`. 6 | 7 | Solve it without **division operator** and in `O(n)` 8 | 9 | ### **Example** 10 | 11 | **Input**: 12 | 13 | ``` java 14 | arr[] = {10, 3, 5, 6, 2} 15 | ``` 16 | 17 | **Output:**: 18 | 19 | ``` java 20 | prod[] = {180, 600, 360, 300, 900} 21 | ``` 22 | 23 | 24 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/README.md: -------------------------------------------------------------------------------- 1 | # Arrays 2 | 3 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 4 | 5 | ## Problems 6 | 7 | - [ A Very Big Sum](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/A%20Very%20Big%20Sum) 8 | - [Arrange Students](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Arrange%20Students) 9 | - [Breaking The Records](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Breaking%20The%20Records) 10 | - [Find All Numbers Disappeared In An Array](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Find%20All%20Numbers%20Disappeared%20In%20An%20Array) 11 | - [Knight's Possible Moves](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Knight's%20Possible%20Moves) 12 | - [Maximum Subarray](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Maximum%20Subarray) 13 | - [MaximumCircularSum]() 14 | - [Non Decreasing Array](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Non%20Decreasing%20Array) 15 | - [Product Array](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Product%20Array) 16 | - [Sock Merchant](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Sock%20Merchant) 17 | - [Solving For Queries With Cups](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Solving%20For%20Queries%20With%20Cups) 18 | - [Square Diagonals](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Square%20Diagonals) 19 | - [The Block Problem](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/The%20Block%20Problem) 20 | - [Two Sum](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Two%20Sum) 21 | - [Valid Suduko](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Valid%20Suduko) 22 | - [Walking Robot Simulation](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays/Walking%20Robot%20Simulation) 23 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Sock Merchant/README.md: -------------------------------------------------------------------------------- 1 | # Sock Merchant 2 | 3 | **Problem from Hackerrank** 4 | 5 | John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. 6 | 7 | For Example, 8 | 9 | there are **n** = `7` socks with colors **ar** = `[1,2,1,2,1,3,2]` . 10 | There is one pair of color `1` and one of color `2` . There are three odd socks left, one of each color. The number of pairs is `2`. 11 | 12 | **Input Format** : 13 | The first line contains an integer `n`, the number of socks represented in `ar` . 14 | The second line contains `n` space-separated integers describing the colors `ar[i]` of the socks in the pile. 15 | 16 | **Output Format** : 17 | Return the total number of matching pairs of socks that John can sell. 18 | 19 | ### **Example** 20 | 21 | **Sample Input** : 22 | 23 | `9` 24 | `[10,20,20,10,10,30,50,10,20]` 25 | 26 | **Sample Output** : `3` 27 | 28 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Sock Merchant/SockMerchant.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class SockMerchant{ 3 | public static void main(String[] args) { 4 | 5 | Scanner scanner = new Scanner(System.in); 6 | 7 | int n = scanner.nextInt(); 8 | int[] ar = new int[n]; 9 | 10 | for (int i = 0; i < n; i++) 11 | { 12 | ar[i] = scanner.nextInt(); 13 | } 14 | int len = n; 15 | int i=0,j=0,k=0,count=0; 16 | for(i=0;ith ball in the cup _ballsi_ such that there's atmost ball in each of the cups, therefore the elements of balls are pairwise distinct. 6 | 7 | Now, you perform `s` swaps, each swap contains two integers `a` and `b`, you are required to swap the positions of cups at index `a` and index `b`. 8 | 9 | Finally, you are asked `q` queries, each query contains two space separated integers `l` and `r`, you need to answer the total number of balls that are present in the cups having index from `l` to `r` (both inclusive). 10 | 11 | For example, `n=4`, `m=2`, `balls={2,4}` . Now you perform `s=3` swaps, where you swap the following cups: 12 | 13 | - 2nd and 4th 14 | - 2nd and 1st 15 | - 2nd and 3rd 16 | 17 | Finally, the balls would be at the indices `{1,4}` . So, for example, if we turned over all the cups from `l=2` to `r=4`, the number of balls found would be `1`. 18 | 19 | **Input Format** 20 | 21 | The first line of input contains `4` space separated integers `n`, `m`, `s` and `q` denoting the number of cups, number of balls, number of swaps performed and the number of queries respectively. 22 | 23 | The second line of input contains `m` space separated integers ball1, ball2, ball3 ... balln where balli denotes the position of ball `i`. 24 | 25 | The next `s` lines containts two space separated integer `a` and `b` - the indices of cups needed to be swapped in this query. 26 | 27 | The next `q` lines containts two space separated integer `l` and `r`, the description of each query. 28 | 29 | **Constraints** 30 | 31 | - 2 <= `n` <= 109 32 | - 1 <= `m` <= 105 33 | - 1 <= `s, q` <= 6.104 34 | - 1 <= ballsi, `a`, `b` <= `n`, `a` != `b` 35 | - 1 <= `l` <= `r` <= `n` 36 | 37 | **Output Format** 38 | 39 | Print `q` space separated integers, where the `i`th integer denote the answer for the `i`th query. 40 | 41 | ## Examples: 42 | 43 | ### Example 1 44 | 45 | **Sample Input** : 46 | 47 | ```java 48 | 3 1 3 2 49 | 2 50 | 1 2 51 | 1 3 52 | 3 1 53 | 1 2 54 | 1 3 55 | ``` 56 | 57 | **Sample Output** : 58 | 59 | ```java 60 | 1 1 61 | ``` 62 | 63 | **Explanation**: After the given swaps, the ball will be at position **1**, hence, for both the queries, the answer is **1**. 64 | 65 | ### Example 2 66 | 67 | **Sample Input** : 68 | 69 | ```java 70 | 3 2 2 2 71 | 1 3 72 | 1 3 73 | 3 2 74 | 1 2 75 | 3 3 76 | ``` 77 | 78 | **Sample Output** : 79 | 80 | ```java 81 | 2 0 82 | ``` 83 | 84 | **Explanation**: After the given swaps, the balls would be at positions `{1,2}`. Hence, for the first query the answer would be **2** (There are **2** balls in the range `[1,2]`) and for the second query, the answer would be **0** (There are no balls in the cup **3**). 85 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/SpiralPrintClockWise/Readme.md: -------------------------------------------------------------------------------- 1 | Take as input a two-d array. Wave print it column-wise. 2 | 3 | Input Format 4 | Two integers M(row) and N(colomn) and further M * N integers(2-d array numbers). 5 | 6 | Constraints 7 | Both M and N are between 1 to 10. 8 | 9 | Output Format 10 | All M * N integers seperated by commas with 'END' wriiten in the end(as shown in example). 11 | 12 | Sample Input 13 | 4 4 14 | 11 12 13 14 15 | 21 22 23 24 16 | 31 32 33 34 17 | 41 42 43 44 18 | Sample Output 19 | 11, 21, 31, 41, 42, 32, 22, 12, 13, 23, 33, 43, 44, 34, 24, 14, END 20 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/SpiralPrintClockWise/SpiralPrintClockWise.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class SpiralPrintClockWise { 5 | 6 | public static void main(String[] args) { 7 | 8 | Scanner sc = new Scanner(System.in); 9 | int m = 0; 10 | if (sc.hasNext()) { 11 | m = sc.nextInt(); 12 | } 13 | int n = 0; 14 | if (sc.hasNext()) { 15 | n = sc.nextInt(); 16 | } 17 | int[][] a = new int[m][n]; 18 | for (int i = 0; i < m; i++) { 19 | for (int j = 0; j < n; j++) { 20 | a[i][j] = sc.nextInt(); 21 | } 22 | } 23 | int top, bottom, left, right, count, direction; 24 | top = 0; 25 | bottom = a.length - 1; 26 | left = 0; 27 | right = a[top].length - 1; 28 | count = (bottom + 1) * (right + 1); 29 | direction = 1; 30 | 31 | while (left <= right && top <= bottom) { 32 | if (count > 0) { 33 | if (direction == 1) { 34 | for (int i = left; i <= right; i++) { 35 | System.out.print(a[top][i] + ", "); 36 | count--; 37 | } 38 | direction = 2; 39 | top++; 40 | } 41 | } 42 | if (count > 0) { 43 | if (direction == 2) { 44 | for (int i = top; i <= bottom; i++) { 45 | System.out.print(a[i][right] + ", "); 46 | count--; 47 | } 48 | direction = 3; 49 | right--; 50 | } 51 | } 52 | if (count > 0) { 53 | if (direction == 3) { 54 | for (int i = right; i >= left; i--) { 55 | System.out.print(a[bottom][i] + ", "); 56 | count--; 57 | } 58 | direction = 4; 59 | bottom--; 60 | } 61 | } 62 | if (count > 0) { 63 | if (direction == 4) { 64 | for (int i = bottom; i >= top; i--) { 65 | System.out.print(a[i][left] + ", "); 66 | count--; 67 | } 68 | direction = 1; 69 | left++; 70 | } 71 | } 72 | 73 | } 74 | System.out.println("END"); 75 | 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Square Diagonals/README.md: -------------------------------------------------------------------------------- 1 | # Square Diagonals 2 | 3 | **Problem from CodingClub** 4 | 5 | Print square of diagonals elememts in a 2D matrix in `O(n)` time complexity. 6 | 7 | ### **Example** 8 | 9 | **Input**: 10 | 11 | ``` java 12 | mat = { 13 | {1,2,3}, 14 | {4,5,6}, 15 | {7,8,9} 16 | }; 17 | ``` 18 | 19 | **Output:**: 20 | 21 | ``` java 22 | 1 25 81 23 | 9 25 49 24 | ``` 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Square Diagonals/SquareDiagonals.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class SquareDiagonals { 4 | public static void main(String[] args) { 5 | int mat[][] = { 6 | {1,2,3}, 7 | {4,5,6}, 8 | {7,8,9} 9 | }; 10 | 11 | square(mat); 12 | } 13 | 14 | public static void square(int[][] mat) { 15 | int size = mat.length; 16 | int d1[] = new int[size]; 17 | int d2[] = new int[size]; 18 | 19 | int x = 0, y = 0; 20 | int r = size - 1; 21 | 22 | for(int i=0; i x) { 29 | h--; 30 | } else { 31 | l++; 32 | } 33 | } 34 | 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Two Sum/README.md: -------------------------------------------------------------------------------- 1 | # Two Sum 2 | 3 | **Problem from LeetCode** 4 | 5 | Given an array of integers, return indices of the two numbers such that they add up to a specific target 6 | 7 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 8 | 9 | ### Example: 10 | **Input**: 11 | ```java 12 | nums = [2, 7, 11, 15]; target = 9; 13 | ``` 14 | 15 | **Output:**: 16 | ```java 17 | [0, 1] 18 | ``` 19 | 20 | **Explanation**: Because `nums[0]` + `nums[1]` = 2 + 7 = 9, -------------------------------------------------------------------------------- /Practice Problems/Arrays/Two Sum/TwoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | class TwoSum { 5 | public static void main(String[] args) { 6 | int[] nums = [2, 7, 11, 15]; 7 | int target = 9; 8 | } 9 | 10 | public static int[] twoSum(int[] nums, int target) { 11 | Map map = new HashMap(); 12 | 13 | for(int i = 0; i set = new HashSet(); 24 | 25 | for (int row = 0; row < n ; row++) { 26 | for (int col = 0; col < n; col++) { 27 | if (grid[row][col] != '.' && !set.add(grid[row][col] + " in row " + row)) 28 | return false; 29 | if (grid[row][col] != '.' && !set.add(grid[row][col] + " in col " + col)) 30 | return false; 31 | if (grid[row][col] != '.' && !set.add(grid[row][col] + " in square " + row/3 + " " + col/3)) 32 | return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Practice Problems/Arrays/Walking Robot Simulation/README.md: -------------------------------------------------------------------------------- 1 | # Walking Robot Simulation 2 | 3 | **Problem from LeetCode** 4 | 5 | A robot on an infinite grid starts at point `(0, 0)` and faces north. The robot can receive one of three possible types of commands: 6 | 7 | - `-2`: turn left 90 degrees 8 | - `-1`: turn right 90 degrees 9 | - `1 <= x <= 9`: move forward x units 10 | 11 | 12 | Some of the grid squares are obstacles. 13 | 14 | The `i`-th obstacle is at grid point `(obstacles[i][0], obstacles[i][1])` 15 | 16 | If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.) 17 | 18 | Return the **square** of the maximum Euclidean distance that the robot will be from the origin. 19 | 20 | **Note**: 21 | 22 | 1. `0 <= commands.length <= 10000` 23 | 2. `0 <= obstacles.length <= 10000` 24 | 3. `-30000 <= obstacle[i][0] <= 30000` 25 | 4. `-30000 <= obstacle[i][1] <= 30000` 26 | 5. The answer is guaranteed to be less than `2 ^ 31`. 27 | 28 | ### **Example** 29 | 30 | **Input**: 31 | 32 | ``` java 33 | commands = [4,-1,4,-2,4]; 34 | obstacles = [[2,4]] 35 | ``` 36 | 37 | **Output:**: 38 | 39 | ``` java 40 | 65 41 | ``` 42 | **Explanation**: robot will be stuck at `(1, 4)` before turning left and going to `(1, 8)` 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/Walking Robot Simulation/WalkingRobotSimulation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class WalkingRobotSimulation { 4 | public static void main(String[] args) { 5 | int[] commands = {-2,-1,8,9,6}; 6 | int[][] obstacles = new int[][]{{-1,3},{0,1},{-1,5},{-2,-4},{5,4},{-2,-3},{5,-1},{1,-1},{5,5},{5,2}}; 7 | 8 | System.out.println(robotSim(commands, obstacles)); 9 | } 10 | 11 | public static int robotSim(int[] commands, int[][] obstacles) { 12 | 13 | Set set = new HashSet<>(); 14 | 15 | for (int[] obs : obstacles) { 16 | set.add(obs[0] + " " + obs[1]); 17 | } 18 | 19 | int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 20 | 21 | int x = 0; 22 | int y = 0; 23 | int d = 0; 24 | int ans = 0; 25 | 26 | for(int c : commands) { 27 | if(c == -1) { 28 | d++; 29 | if (d == 4) { 30 | d = 0; 31 | } 32 | } else if(c == -2) { 33 | d--; 34 | if (d == -1) { 35 | d = 3; 36 | } 37 | } else { 38 | while(c > 0 && !set.contains((x+dirs[d][0]) + " " + (y+dirs[d][1]))) { 39 | x += dirs[d][0]; 40 | y += dirs[d][1]; 41 | c--; 42 | } 43 | } 44 | 45 | ans = Math.max(ans, x*x + y*y); 46 | } 47 | 48 | return ans; 49 | 50 | } 51 | 52 | 53 | } -------------------------------------------------------------------------------- /Practice Problems/Arrays/WavePrintRowWise/Readme.md: -------------------------------------------------------------------------------- 1 | Take as input a two-d array. Wave print it row-wise. 2 | 3 | Input Format 4 | Two integers M(row) and N(column) and further M * N integers(2-d array numbers). 5 | 6 | Constraints 7 | Both M and N are between 1 to 10. 8 | 9 | Output Format 10 | All M * N integers are seperated by commas with 'END' written in the end(as shown in example). 11 | 12 | Sample Input 13 | 4 4 14 | 11 12 13 14 15 | 21 22 23 24 16 | 31 32 33 34 17 | 41 42 43 44 18 | Sample Output 19 | 11, 12, 13, 14, 24, 23, 22, 21, 31, 32, 33, 34, 44, 43, 42, 41, END 20 | -------------------------------------------------------------------------------- /Practice Problems/Arrays/WavePrintRowWise/WavePrintRowWise.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class WavePrintRowWise { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | int n = 0, m = 0; 9 | if (sc.hasNext()) { 10 | m = sc.nextInt(); 11 | } 12 | n = sc.nextInt(); 13 | int[][] arr = new int[m][n]; 14 | for (int i = 0; i < m; i++) { 15 | for (int j = 0; j < n; j++) { 16 | arr[i][j] = sc.nextInt(); 17 | } 18 | } 19 | for (int i = 0; i < m; i++) { 20 | if (i % 2 == 0) { 21 | for (int j = 0; j < n; j++) { 22 | System.out.print(arr[i][j] + ", "); 23 | } 24 | } else { 25 | for (int j = n - 1; j >= 0; j--) { 26 | System.out.print(arr[i][j] + ", "); 27 | } 28 | } 29 | 30 | } 31 | System.out.println("END"); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Combination Sum/CombinationSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.Collections; 5 | 6 | public class CombinationSum { 7 | 8 | public static void main(String args[]) { 9 | int[] candidates = {2, 3, 6, 7}; 10 | int target = 7; 11 | 12 | List> solution = combinationSum(candidates, target); 13 | 14 | System.out.println("["); 15 | for(int i = 0; i row = solution.get(i); 17 | System.out.println(" " + row + ","); 18 | } 19 | System.out.println("]"); 20 | 21 | } 22 | 23 | public static List> combinationSum(int[] candidates, int target) { 24 | if(candidates == null || candidates.length == 0) { 25 | return Collections.emptyList(); 26 | } 27 | 28 | final List> res = new ArrayList<>(); 29 | 30 | Arrays.sort(candidates); 31 | 32 | helper(candidates, target, 0, new ArrayList<>(), res); 33 | 34 | return res; 35 | } 36 | 37 | private static void helper(int[] candidates, int target, int pos, List comb, List> res) { 38 | if(target == 0) { 39 | res.add(new ArrayList<>(comb)); 40 | return; 41 | } 42 | 43 | for(int i = pos; i< candidates.length; i++) { 44 | int newTarget = target - candidates[i]; 45 | 46 | if(newTarget >= 0) { 47 | comb.add(candidates[i]); 48 | helper(candidates, newTarget, i, comb, res); 49 | comb.remove(comb.size() - 1); 50 | } else { 51 | break; 52 | } 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Combination Sum/README.md: -------------------------------------------------------------------------------- 1 | # Combination Sum 2 | 3 | **Problem from LeetCoder** 4 | 5 | Given a set of candidate numbers (`candidates`) (without duplicates) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sums to `target`. 6 | 7 | The same repeated number may be chosen from `candidates` unlimited number of times. 8 | 9 | **Note** : 10 | - All numbers (including target) will be positive integers. 11 | - The solution set must not contain duplicate combinations. 12 | 13 | ### Examples: 14 | 15 | #### 1 16 | 17 | **Input** : 18 | ```java 19 | candidates = [2,3,6,7], target = 7 20 | ``` 21 | 22 | **Output:** : 23 | ```java 24 | [ 25 | [7], 26 | [2,2,3] 27 | ] 28 | ``` 29 | #### 2 30 | 31 | **Input** : 32 | ```java 33 | candidates = [2,3,5], target = 8 34 | ``` 35 | 36 | **Output:** : 37 | ```java 38 | [ 39 | [2,2,2,2], 40 | [2,3,3], 41 | [3,5] 42 | ] 43 | ``` 44 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/PermutationsOfString/PermutationsOfString.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class PermutationsOfString { 4 | 5 | public static void main(String args[]) { 6 | 7 | String input = "ABC"; 8 | HashSet resultSet = new HashSet(); 9 | 10 | permutation(input, 0, resultSet); 11 | 12 | for (String str : resultSet) { 13 | System.out.println(str); 14 | } 15 | 16 | } 17 | 18 | public static void permutation(String input, int fixedIndex, HashSet resultSet) { 19 | 20 | 21 | if (fixedIndex == input.length()-1) { 22 | resultSet.add(input); 23 | return; 24 | } 25 | 26 | for (int i = fixedIndex; i < input.length(); i++) { 27 | 28 | input = swap(input, fixedIndex, i); 29 | resultSet.add(input); 30 | permutation(input, fixedIndex+1, resultSet); 31 | input = swap(input, fixedIndex, i); 32 | 33 | } 34 | 35 | } 36 | 37 | public static String swap(String s, int i, int j) { 38 | 39 | char[] input = s.toCharArray(); 40 | 41 | char temp = input[i]; 42 | input[i] = input[j]; 43 | input[j] = temp; 44 | 45 | return String.valueOf(input); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/PermutationsOfString/README.md: -------------------------------------------------------------------------------- 1 | # Permutations of a given string 2 | 3 | **Problem from GeeksForGeeks** 4 | 5 | A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. 6 | Your task is to print all permutations of a given `input` string in new line. 7 | 8 | ### Examples: 9 | 10 | #### 1 11 | 12 | **Input** : 13 | ```java 14 | input = "ABC" 15 | ``` 16 | 17 | **Output:** : 18 | ```java 19 | ACB 20 | BCA 21 | ABC 22 | CBA 23 | BAC 24 | CAB 25 | ``` 26 | 27 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/README.md: -------------------------------------------------------------------------------- 1 | # Backtracking 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Combination Sum](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/blob/master/Practice%20Problems/Backtracking/Combination%20Sum) -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Rat In A Maze/README.md: -------------------------------------------------------------------------------- 1 | # Rat In A Maze 2 | 3 | **Problem from GeeksForGeeks** 4 | A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down. 5 | In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves. 6 | 7 | **Algorithm:** 8 | If destination is reached 9 | print the solution matrix 10 | Else 11 | a) Mark current cell in solution matrix as 1. 12 | b) Move forward in the horizontal direction and recursively check if this 13 | move leads to a solution. 14 | c) If the move chosen in the above step doesn't lead to a solution 15 | then move down and check if this move leads to a solution. 16 | d) If none of the above solutions works then unmark this cell as 0 17 | (BACKTRACK) and return false. 18 | 19 | 20 | ### Example: 21 | 22 | **Input** : 23 | ```java 24 | maze[][] = { { 1, 0, 0, 0 }, 25 | { 1, 1, 0, 1 }, 26 | { 0, 1, 0, 0 }, 27 | { 1, 1, 1, 1 } } 28 | ``` 29 | 30 | **Output:** : 31 | ```java 32 | The 1 values show the path of rat. 33 | 1 0 0 0 34 | 1 1 0 0 35 | 0 1 0 0 36 | 0 1 1 1 37 | ``` 38 | 39 | 40 | ### Complexity Analysis: 41 | 42 | **Time Complexity:** O(2^(n^2)). 43 | The recursion can run upperbound 2^(n^2) times. 44 | 45 | **Space Complexity:** O(n^2). 46 | Output matrix is required so an extra space of size n*n is needed. 47 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Rat In A Maze/RatMaze.java: -------------------------------------------------------------------------------- 1 | /* Java program to solve Rat in a Maze problem using backtracking */ 2 | 3 | public class RatMaze { 4 | 5 | // Size of the maze 6 | static int N; 7 | 8 | /* A utility function to print solution matrix sol[N][N] */ 9 | void printSolution(int sol[][]) 10 | { 11 | for (int i = 0; i < N; i++) { 12 | for (int j = 0; j < N; j++) 13 | System.out.print( 14 | " " + sol[i][j] + " "); 15 | System.out.println(); 16 | } 17 | } 18 | 19 | /* A utility function to check if x, y is valid index for N*N maze */ 20 | boolean isSafe( 21 | int maze[][], int x, int y) 22 | { 23 | // if (x, y outside maze) return false 24 | return (x >= 0 && x < N && y >= 0 25 | && y < N && maze[x][y] == 1); 26 | } 27 | 28 | /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and 29 | prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ 30 | boolean solveMaze(int maze[][]) 31 | { 32 | int sol[][] = new int[N][N]; 33 | 34 | if (solveMazeUtil(maze, 0, 0, sol) == false) { 35 | System.out.print("Solution doesn't exist"); 36 | return false; 37 | } 38 | 39 | printSolution(sol); 40 | return true; 41 | } 42 | 43 | /* A recursive utility function to solve Maze problem */ 44 | boolean solveMazeUtil(int maze[][], int x, int y, 45 | int sol[][]) 46 | { 47 | // if (x, y is goal) return true 48 | if (x == N - 1 && y == N - 1 49 | && maze[x][y] == 1) { 50 | sol[x][y] = 1; 51 | return true; 52 | } 53 | 54 | // Check if maze[x][y] is valid 55 | if (isSafe(maze, x, y) == true) { 56 | // mark x, y as part of solution path 57 | sol[x][y] = 1; 58 | 59 | /* Move forward in x direction */ 60 | if (solveMazeUtil(maze, x + 1, y, sol)) 61 | return true; 62 | 63 | /* If moving in x direction doesn't give solution then Move down in y direction */ 64 | if (solveMazeUtil(maze, x, y + 1, sol)) 65 | return true; 66 | 67 | /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ 68 | sol[x][y] = 0; 69 | return false; 70 | } 71 | 72 | return false; 73 | } 74 | 75 | public static void main(String args[]) 76 | { 77 | RatMaze rat = new RatMaze(); 78 | int maze[][] = { { 1, 0, 0, 0 }, 79 | { 1, 1, 0, 1 }, 80 | { 0, 1, 0, 0 }, 81 | { 1, 1, 1, 1 } }; 82 | 83 | N = maze.length; 84 | rat.solveMaze(maze); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Sudoku/README.md: -------------------------------------------------------------------------------- 1 | # Sudoku 2 | 3 | **Problem from GeeksForGeeks** 4 | 5 | Given a partially filled 9×9 2D array `grid[9][9]`, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9. 6 | 7 | ### Example: 8 | 9 | **Input** : 10 | ```java 11 | grid = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], 12 | [5, 2, 0, 0, 0, 0, 0, 0, 0], 13 | [0, 8, 7, 0, 0, 0, 0, 3, 1], 14 | [0, 0, 3, 0, 1, 0, 0, 8, 0], 15 | [9, 0, 0, 8, 6, 3, 0, 0, 5], 16 | [0, 5, 0, 0, 9, 0, 6, 0, 0], 17 | [1, 3, 0, 0, 0, 0, 2, 5, 0], 18 | [0, 0, 0, 0, 0, 0, 0, 7, 4], 19 | [0, 0, 5, 2, 0, 6, 3, 0, 0] ] 20 | ``` 21 | 22 | **Output:** : 23 | ```java 24 | 3 1 6 5 7 8 4 9 2 25 | 5 2 9 1 3 4 7 6 8 26 | 4 8 7 6 2 9 5 3 1 27 | 2 6 3 4 1 5 9 8 7 28 | 9 7 4 8 6 3 1 2 5 29 | 8 5 1 7 9 2 6 4 3 30 | 1 3 8 9 4 7 2 5 6 31 | 6 9 2 3 5 1 8 7 4 32 | 7 4 5 2 8 6 3 1 9 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/Sudoku/Sudoku.java: -------------------------------------------------------------------------------- 1 | public class Sudoku { 2 | 3 | public static void main(String args[]) { 4 | //Given Sudoku in form of 2D array, 5 | //Note: '0' represents empty place. 6 | int[][] grid = { 7 | {0, 0, 8, 3, 1, 9, 4, 0, 2}, 8 | {0, 0, 1, 4, 5, 2, 3, 0, 0}, 9 | {2, 3, 4, 6, 0, 0, 5, 9, 1}, 10 | {6, 1, 9, 0, 0, 4, 0, 0, 0}, 11 | {0, 2, 5, 0, 9, 0, 0, 0, 0}, 12 | {4, 0, 0, 2, 0, 0, 9, 1, 5}, 13 | {1, 4, 3, 0, 0, 7, 0, 5, 9}, 14 | {0, 0, 6, 9, 0, 3, 1, 0, 0}, 15 | {9, 7, 2, 1, 0, 5, 8, 3, 0} }; 16 | 17 | if (solveSudoku(grid) == false) { 18 | System.out.println("No solution exists!!"); 19 | } 20 | else 21 | printSudoku(grid); 22 | } 23 | 24 | public static boolean isSafe(int[][] grid, int row, int col, int n) { 25 | int rowStart = -1, colStart = -1; 26 | 27 | // check the same row 28 | for (int j = 0; j < grid.length; j++) { 29 | if (j == col) continue; 30 | if (grid[row][j] == n) return false; 31 | } 32 | 33 | //check same column 34 | for (int i = 0; i < grid.length; i++) { 35 | if (i == row) continue; 36 | 37 | if (grid[i][col] == n) return false; 38 | } 39 | 40 | //check same 3 x 3 grid 41 | rowStart = row - row % 3; 42 | colStart = col - col % 3; 43 | 44 | for (int i = 0; i < 3; i++) { 45 | colStart = col - col % 3; 46 | for (int j = 0; j < 3; j++) { 47 | if (rowStart == row && colStart == col) continue; 48 | 49 | if (grid[rowStart][colStart] == n) return false; 50 | 51 | colStart++; 52 | } 53 | rowStart++; 54 | } 55 | 56 | //This means, it is safe to place the number 'n' at position grid[row][col] 57 | return true; 58 | } 59 | 60 | public static boolean solveSudoku(int[][] grid) { 61 | int row = -1, col = -1; 62 | boolean res = true; 63 | 64 | for (int i = 0; i < grid.length; i++) { 65 | for (int j = 0; j < grid.length; j++) { 66 | if (grid[i][j] == 0) { 67 | row = i; 68 | col = j; 69 | res = false; 70 | break; 71 | } 72 | } 73 | if (!res) 74 | break; 75 | } 76 | 77 | //If res is true, it means there isn't any '0' present in our Sudoku, hence the Sudoku is solved! 78 | if (res) 79 | return true; 80 | 81 | for (int n = 1; n <= 9; n++) { 82 | if (isSafe(grid, row, col, n)) { 83 | grid[row][col] = n; 84 | if (solveSudoku(grid)) 85 | return true; 86 | else 87 | //backtrack and initialize the current position with '0' as before 88 | grid[row][col] = 0; 89 | } 90 | } 91 | 92 | return res; 93 | } 94 | 95 | public static void printSudoku(int[][] grid) { 96 | for (int i = 0; i < 9; i++) { 97 | for (int j = 0; j < 9; j++) { 98 | System.out.print(grid[i][j] + " "); 99 | } 100 | System.out.println(); 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/WordBreakProblem/README.md: -------------------------------------------------------------------------------- 1 | # Word Break Problem 2 | 3 | **Problem from GeeksForGeeks** 4 | 5 | Given a valid `sentence` without any spaces between the words and a `dictionary` of valid English words, find all possible ways to break the `sentence` in individual `dictionary` words. 6 | 7 | ### Examples: 8 | 9 | #### 1 10 | 11 | **Input** : 12 | ```java 13 | dictionary = ["mobile","samsung","sam","sung","man","mango", "icecream","and", "go","love","ice","cream","we"], 14 | sentence = "weloveicecreamandmango" 15 | ``` 16 | 17 | **Output:** : 18 | ```java 19 | we love ice cream and man go 20 | we love ice cream and mango 21 | we love icecream and man go 22 | we love icecream and mango 23 | ``` 24 | 25 | #### 2 26 | 27 | **Input** : 28 | ```java 29 | dictionary = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "and", "cream", "icecream", "man", "go", "mango"] 30 | sentence = "ilikesamsungmobile" 31 | ``` 32 | 33 | **Output:** : 34 | ```java 35 | i like sam sung mobile 36 | i like samsung mobile 37 | ``` 38 | -------------------------------------------------------------------------------- /Practice Problems/Backtracking/WordBreakProblem/WordBreakProblem.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashSet; 3 | import java.util.List; 4 | 5 | public class WordBreakProblem { 6 | 7 | public static void main(String args[]) { 8 | 9 | //HashSet will store our dictionary elements to provide O(1) lookup 10 | HashSet set = new HashSet<>(); 11 | 12 | //Given Dictionary 13 | String[] dict = {"mobile","samsung","sam","sung", 14 | "man","mango", "icecream","and", 15 | "go","love","ice","cream","we"}; 16 | 17 | //Adding elements to HashSet 18 | for (String s : dict) { 19 | set.add(s); 20 | } 21 | 22 | String input = "weloveicecreamandmango"; 23 | 24 | List ans = new ArrayList(); 25 | 26 | //function call 27 | findPossibleStrings(set, input, "", ans); 28 | 29 | //print answers 30 | for (String s : ans) 31 | System.out.println(s); 32 | 33 | } 34 | 35 | public static void findPossibleStrings(HashSet set, String in, String result, List ans) { 36 | 37 | if (in.length() == 0) { 38 | ans.add(result); 39 | } 40 | 41 | for (int i = 0; i < in.length(); i++) { 42 | String left = in.substring(0, i+1); 43 | if (set.contains(left)) { 44 | String right = in.substring(i+1); 45 | findPossibleStrings(set, right, result + left + " ", ans); 46 | } 47 | } 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Practice Problems/BinarySearch/Aggressive Cow/AggressiveCow.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class aggrCow { 5 | 6 | public static void main (String args[]) throws IOException { 7 | 8 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 9 | int T=Integer.parseInt(br.readLine()); 10 | while(T--!=0) { 11 | String inp[]=br.readLine().split(" "); 12 | int N=Integer.parseInt(inp[0]); 13 | int C=Integer.parseInt(inp[1]); 14 | int ar[]=new int[N]; 15 | for(int i=0;i=d) { 40 | pre=ar[i]; 41 | c++; 42 | if(c==cows){ 43 | return true; 44 | } 45 | } 46 | } 47 | return false; 48 | } 49 | } -------------------------------------------------------------------------------- /Practice Problems/BinarySearch/Aggressive Cow/README.md: -------------------------------------------------------------------------------- 1 | # Aggressive Cow 2 | 3 | Farmer John has built a new long barn, with `N` (2 <= `N` <= 100,000) stalls. The stalls are located along a straight line at positions `x1`,...,`xN` (0 <= `xi` <= 1,000,000,000). 4 | 5 | His `C` (2 <= `C` <= `N`) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance? 6 | 7 | ## Input 8 | 9 | `t` – the number of test cases, then `t` test cases follows. 10 | Line 1: Two space-separated integers: `N` and `C` 11 | Lines 2: `N+1`: Line `i+1` contains an integer stall location, `xi` 12 | 13 | ## Output 14 | For each test case output one integer: the largest minimum distance. 15 | 16 | ### Example 17 | 18 | **Input** : 19 | ```java 20 | 1 21 | 5 3 22 | 1 23 | 2 24 | 8 25 | 4 26 | 9 27 | ``` 28 | 29 | **Output** : 30 | ```java 31 | 3 32 | ``` 33 | 34 | **Explanation** 35 | 36 | FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3. 37 | -------------------------------------------------------------------------------- /Practice Problems/BinarySearch/BookAllocationProblem/BookAllocationProblem.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | public class BookAllocationProblem { 5 | //we need to minimize the maximum number of pages alloted to a student i.e. we need to minimize the stress on students 6 | public static boolean isValid(int[] a,int n,int m,int mid) { 7 | int s=0; 8 | int c=1; 9 | for(int i=0;imid) { 12 | s=a[i]; 13 | c++; 14 | } 15 | } 16 | if(c>m) { 17 | return false; 18 | }else { 19 | return true; 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner sc = new Scanner(System.in); 25 | int t = 0; 26 | if (sc.hasNext()) { 27 | t = sc.nextInt(); 28 | } 29 | while (t-- != 0) { 30 | int n = sc.nextInt(); 31 | int m = sc.nextInt(); 32 | int[] a = new int[n]; 33 | int s = 0;//sum of array elements 34 | for (int i = 0; i < n; i++) { 35 | a[i] = sc.nextInt(); 36 | s += a[i]; 37 | } 38 | if(n mid) { 13 | s = a[i]; 14 | p++; 15 | } 16 | } 17 | return p; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner sc = new Scanner(System.in); 22 | int k = -1; 23 | if (sc.hasNext()) { 24 | k = sc.nextInt(); 25 | } 26 | int n = sc.nextInt(); 27 | int[] a = new int[n]; 28 | long s = 0;//sum 29 | int m = 0;//max 30 | for (int i = 0; i < n; i++) { 31 | a[i] = sc.nextInt(); 32 | s += a[i]; 33 | m = Math.max(m, a[i]); 34 | } 35 | 36 | long l = m;//lowest time = max block length in array 37 | long h = s;//maximum time = sum of all board length 38 | while (l < h) { 39 | long mid = (l + h) / 2; 40 | if (pno(a, n, mid) <= k) {//if it is possible to paint in this time 41 | h = mid;//try to search for more lower value therefore dec h 42 | // we cant do h= mid -1 as we need a answer and mid was possible 43 | } else { 44 | l = mid + 1;//it wasn't possible then search in upper half and inc l 45 | } 46 | } 47 | System.out.println(l); 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Practice Problems/BinarySearch/PainterProblem/Readme.md: -------------------------------------------------------------------------------- 1 | Given K painters to paint N boards where each painter takes 1 unit of time to paint 1 unit of boards i.e. if the length of a particular board is 5, it will take 5 units of time to paint the board. Compute the minimum amount of time to paint all the boards. 2 | 3 | Note that: 4 | 5 | Every painter can paint only contiguous segments of boards. 6 | A board can only be painted by 1 painter at maximum. 7 | Input Format 8 | First line contains K which is the number of painters. Second line contains N which indicates the number of boards. Third line contains N space separated integers representing the length of each board. 9 | 10 | Constraints 11 | 1 <= K <= 10 12 | 1 <= N <= 10 13 | 1<= Length of each Board <= 10^8 14 | 15 | Output Format 16 | Output the minimum time required to paint the board. 17 | 18 | Sample Input 19 | 2 20 | 2 21 | 1 10 22 | Sample Output 23 | 10 24 | -------------------------------------------------------------------------------- /Practice Problems/BinarySearch/README.md: -------------------------------------------------------------------------------- 1 | # BinarySearch 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Aggressive Cow](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/blob/master/Practice%20Problems/BinarySearch/Aggressive%20Cow) 6 | -------------------------------------------------------------------------------- /Practice Problems/Divide_the_chockolate/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/4b5d161f5feacaa2a264c4f80de2d86d1960a32a/Practice Problems/Divide_the_chockolate/README.md -------------------------------------------------------------------------------- /Practice Problems/Divide_the_chockolate/solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/4b5d161f5feacaa2a264c4f80de2d86d1960a32a/Practice Problems/Divide_the_chockolate/solution.java -------------------------------------------------------------------------------- /Practice Problems/Dynamic Programming/Edit_Distance/README.md: -------------------------------------------------------------------------------- 1 | # Edit Distance 2 | **Problem from LeetCode** 3 | 4 | Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. 5 | 6 | You have the following 3 operations permitted on a word: 7 | 1.Insert a character 8 | 2.Delete a character 9 | 3.Replace a character 10 | 11 | ### Examples: 12 | 13 | #### I 14 | 15 | **Input** : 16 | ```java 17 | abc 18 | dc 19 | ``` 20 | 21 | **Output:** : 22 | ```java 23 | 2 24 | ``` 25 | **Explanation** : 26 | abc -> bc (remove 'a') 27 | bc -> dc (replace 'b' with 'd') 28 | 29 | #### 2 30 | 31 | **Input** : 32 | ```java 33 | horse 34 | ros 35 | ``` 36 | 37 | **Output:** : 38 | ```java 39 | 3 40 | ``` 41 | **Explanation** : 42 | horse -> rorse (replace 'h' with 'r') 43 | rorse -> rose (remove 'r') 44 | rose -> ros (remove 'e') 45 | 46 | 47 | 48 | 49 | The solution given provides both recursive, memoization and Dynamic Programming Solution with proper commenting 50 | -------------------------------------------------------------------------------- /Practice Problems/Dynamic Programming/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Edit Distance](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/blob/master/Practice%20Problems/Dynamic%20Programming/Edit_Distance) 6 | - [Unique Paths](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/blob/master/Practice%20Problems/Dynamic%20Programming/Unique%20Paths) 7 | -------------------------------------------------------------------------------- /Practice Problems/Dynamic Programming/Unique Paths/README.md: -------------------------------------------------------------------------------- 1 | # Unique Paths 2 | 3 | **Problem from LeetCoder** 4 | 5 | A robot is located at the top-left corner of a `m` x `n` grid (marked 'Start' in the diagram below). 6 | 7 | ![diagram](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) 8 | 9 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 10 | 11 | How many possible unique paths are there? 12 | 13 | **Note** : `m` and `n` will be at most `100`. 14 | 15 | 16 | ### Examples: 17 | 18 | #### 1 19 | 20 | **Input** : 21 | ```java 22 | m = 3, n = 2 23 | ``` 24 | 25 | **Output:** : 26 | ```java 27 | 3 28 | ``` 29 | **Explanation** : 30 | From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 31 | 1. Right -> Right -> Down 32 | 2. Right -> Down -> Right 33 | 3. Down -> Right -> Right 34 | 35 | #### 2 36 | 37 | **Input** : 38 | ```java 39 | m = 7, n = 3 40 | ``` 41 | 42 | **Output:** : 43 | ```java 44 | 28 45 | ``` 46 | -------------------------------------------------------------------------------- /Practice Problems/Dynamic Programming/Unique Paths/UniquePaths.java: -------------------------------------------------------------------------------- 1 | public class UniquePaths { 2 | 3 | static int[][] paths = new int[101][101]; 4 | 5 | public static void main(String args[]) { 6 | 7 | int m = 7; 8 | int n = 3; 9 | 10 | int noOfPaths = uniquePaths(m,n); 11 | 12 | System.out.println(noOfPaths); 13 | } 14 | 15 | public static int uniquePaths(int m, int n) { 16 | if(m <= 0 || n <= 0) return 0; 17 | if(m == 1 || n == 1) return 1; 18 | 19 | if(paths[m][n] == 0) { 20 | paths[m][n] = uniquePaths(m-1, n) + uniquePaths(m, n-1); 21 | } 22 | 23 | return paths[m][n]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Find middle of LinkedList/README.md: -------------------------------------------------------------------------------- 1 | # Find middle of LinkedList 2 | 3 | Find middle of a singly linked list 4 | 5 | ### Example: 6 | **Input** : 7 | 8 | ``` java 9 | 1->2->3->4->5->NULL 10 | ``` 11 | 12 | **Output:** : 13 | 14 | ``` java 15 | 3 16 | ``` 17 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Find middle of LinkedList/midLL.java: -------------------------------------------------------------------------------- 1 | package ip1_n; 2 | import java.io.BufferedReader; 3 | import java.io.IOException; 4 | import java.io.InputStreamReader; 5 | public class midLL { 6 | // Solution ------------------------------------------------------- 7 | public ListNode middleNode(ListNode head) { 8 | ListNode slow = head; 9 | ListNode fast = head; 10 | while(fast != null && fast.next != null ){ 11 | fast = fast.next.next; 12 | slow = slow.next; 13 | } 14 | return slow; 15 | } 16 | 17 | // DRIVER CODE ----------------------------------------------------- 18 | public static class ListNode { 19 | int val; 20 | ListNode next; 21 | ListNode(int x) { val = x; } 22 | } 23 | public static int[] stringToIntegerArray(String input) { 24 | input = input.trim(); 25 | input = input.substring(1, input.length() - 1); 26 | if (input.length() == 0) { 27 | return new int[0]; 28 | } 29 | 30 | String[] parts = input.split(","); 31 | int[] output = new int[parts.length]; 32 | for(int index = 0; index < parts.length; index++) { 33 | String part = parts[index].trim(); 34 | output[index] = Integer.parseInt(part); 35 | } 36 | return output; 37 | } 38 | 39 | public static ListNode stringToListNode(String input) { 40 | // Generate array from the input 41 | int[] nodeValues = stringToIntegerArray(input); 42 | 43 | // Now convert that list into linked list 44 | ListNode dummyRoot = new ListNode(0); 45 | ListNode ptr = dummyRoot; 46 | for(int item : nodeValues) { 47 | ptr.next = new ListNode(item); 48 | ptr = ptr.next; 49 | } 50 | return dummyRoot.next; 51 | } 52 | 53 | public static String listNodeToString(ListNode node) { 54 | if (node == null) { 55 | return "[]"; 56 | } 57 | 58 | String result = ""; 59 | while (node != null) { 60 | result += Integer.toString(node.val) + ", "; 61 | node = node.next; 62 | } 63 | return "[" + result.substring(0, result.length() - 2) + "]"; 64 | } 65 | 66 | public static void main(String[] args) throws IOException { 67 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 68 | String line; 69 | while ((line = in.readLine()) != null) { 70 | ListNode head = stringToListNode(line); 71 | 72 | ListNode ret = new midLL().middleNode(head); 73 | 74 | String out = listNodeToString(ret); 75 | 76 | System.out.print(out); 77 | } 78 | } 79 | // DRIVER CODE ends----------------------------------------------------- 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/LastOccurrence/LastOccurrence.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | public class LastOccurrence 5 | { 6 | public static void main(String[] args) 7 | { 8 | LinkedList linkedList = new LinkedList(); 9 | 10 | linkedList.add("Apple"); 11 | linkedList.add("Banana"); 12 | linkedList.add("Strawberry"); 13 | linkedList.add("Guava"); 14 | linkedList.add("Strawberry"); 15 | linkedList.add("Mango"); 16 | linkedList.add("Banana"); 17 | linkedList.add("Papaya"); 18 | linkedList.add("Strawberry"); 19 | linkedList.add("Kiwi"); 20 | linkedList.add("Apple"); 21 | 22 | System.out.println("Enter the element who's last index is to be returned"); 23 | Scanner input = new Scanner(System.in); 24 | String element = input.nextLine(); 25 | 26 | 27 | System.out.println("The linked list: " + linkedList); 28 | 29 | System.out.println("Last index of " + element + " " + linkedList.lastIndexOf(element)); 30 | } 31 | } -------------------------------------------------------------------------------- /Practice Problems/LinkedList/LastOccurrence/README.md: -------------------------------------------------------------------------------- 1 | # Last Occurrence(Index) of an Element in Linked List 2 | 3 | Given a particular element in a linked list, find the index of its last occurrence. 4 | 5 | ### Example: 6 | **Linked List**: [Apple, Banana, Strawberry, Guava, Strawberry, Mango, Banana, Papaya, Strawberry, Kiwi, Apple] 7 | **Input** : Apple 8 | 9 | **Output:** : 10 | 11 | ``` 12 | Last index of Apple 10 13 | ``` 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Merge two sorted LinkedLists/MergeTwoSortedLinkedLists.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int x) { 5 | val = x; 6 | } 7 | } 8 | 9 | public class MergeTwoSortedLinkedLists { 10 | public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | if (l1 == null) 12 | return l2; 13 | else if (l2 == null) 14 | return l1; 15 | 16 | if (l1.val > l2.val) { 17 | l2.next = mergeTwoLists(l1,l2.next); 18 | return l2; 19 | } 20 | 21 | l1.next = mergeTwoLists(l1.next,l2); 22 | return l1; 23 | } 24 | 25 | public static void main(String[] args) { 26 | ListNode firstListNode1 = new ListNode(1); 27 | ListNode firstListNode2 = new ListNode(2); 28 | firstListNode1.next = firstListNode2; 29 | ListNode firstListNode3 = new ListNode(4); 30 | firstListNode2.next = firstListNode3; 31 | 32 | ListNode secondListNode1 = new ListNode(1); 33 | ListNode secondListNode2 = new ListNode(3); 34 | secondListNode1.next = secondListNode2; 35 | ListNode secondListNode3 = new ListNode(4); 36 | secondListNode2.next = secondListNode3; 37 | 38 | ListNode mergedListNode = mergeTwoLists(firstListNode1, secondListNode1); 39 | 40 | 41 | System.out.print(mergedListNode.val); 42 | mergedListNode = mergedListNode.next; 43 | while (mergedListNode != null) { 44 | System.out.print("->" + mergedListNode.val); 45 | mergedListNode = mergedListNode.next; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Merge two sorted LinkedLists/README.md: -------------------------------------------------------------------------------- 1 | # Merge two sorted LinkedLists 2 | Merge two sorted linked lists and return it as a new list. 3 | The new list should be made by splicing together the nodes of the first two lists. 4 | Implementation should have a method with two ListNode parameters. 5 | 6 | ### Example: 7 | **Input** : 8 | 9 | ``` java 10 | 1->2->4, 1->3->4 11 | ``` 12 | 13 | **Output:** : 14 | 15 | ``` java 16 | 1->1->2->3->4->4 17 | ``` 18 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Palindrome LinkedList/PalindromeLinkedList.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int x) { 5 | val = x; 6 | } 7 | } 8 | 9 | public class PalindromeLinkedList { 10 | public static boolean isPalindrome(ListNode head) { 11 | if (head == null) return true; 12 | if (head.next == null) return true; 13 | ListNode fast = head; 14 | ListNode slow = head; 15 | while (fast != null && fast.next != null) { 16 | fast = fast.next.next; 17 | slow = slow.next; 18 | } 19 | ListNode rev = reverse(head, slow); 20 | if (fast != null) slow = slow.next; 21 | while (rev != null) { 22 | if (rev.val != slow.val) return false; 23 | rev = rev.next; 24 | slow = slow.next; 25 | } 26 | return true; 27 | 28 | } 29 | 30 | private static ListNode reverse(ListNode head, ListNode end) { 31 | ListNode front = head; 32 | ListNode back = head.next; 33 | while (back != end) { 34 | ListNode tmp = back.next; 35 | back.next = front; 36 | front = back; 37 | back = tmp; 38 | } 39 | head.next = null; 40 | return front; 41 | } 42 | 43 | public static void main(String[] args) { 44 | ListNode firstListNode1 = new ListNode(1); 45 | ListNode firstListNode2 = new ListNode(2); 46 | firstListNode1.next = firstListNode2; 47 | System.out.println(isPalindrome(firstListNode1)); 48 | 49 | ListNode secondListNode1 = new ListNode(1); 50 | ListNode secondListNode2 = new ListNode(2); 51 | secondListNode1.next = secondListNode2; 52 | ListNode secondListNode3 = new ListNode(2); 53 | secondListNode2.next = secondListNode3; 54 | ListNode secondListNode4 = new ListNode(1); 55 | secondListNode3.next = secondListNode4; 56 | 57 | System.out.println(isPalindrome(secondListNode1)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Palindrome LinkedList/README.md: -------------------------------------------------------------------------------- 1 | # Palindrome LinkedList 2 | 3 | Given a singly linked list, determine if it is a palindrome. 4 | 5 | ### Example: 6 | **Input** : 7 | 8 | ``` java 9 | 1->2 10 | ``` 11 | 12 | **Output:** : 13 | false 14 | 15 | **Input** : 16 | 17 | ``` java 18 | 1->2->2->1 19 | ``` 20 | 21 | **Output:** : 22 | true 23 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/README.md: -------------------------------------------------------------------------------- 1 | # LinkedList 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Merge two sorted LinkedLists](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList/Merge%20two%20sorted%20LinkedLists) 6 | - [Palindrome LinkedList](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList/Palindrome%20LinkedList) 7 | - [Reverse LinkedList](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList/Reverse%20LinkedList) 8 | - [Swap nodes in pairs](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList/Swap%20nodes%20in%20pairs) 9 | - [Find middle of LinkedList](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList/Find%20middle%20of%20LinkedList) 10 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/RemoveFirstLastOccurence/README.md: -------------------------------------------------------------------------------- 1 | # Remove First and Last Occurence of an element in a Linked List 2 | 3 | Given an element remove the first and last occurence of it in the linked list. 4 | 5 | ### Example: 6 | **Input** : `Alaska` 7 | 8 | **Output:** :``` 9 | Original Linked List: 10 | [Alaska, California, Texas, New York, Texas, Alaska, Florida, California, Arizona, Texas, Alaska, Arizona, California, Florida, Texas, Washington, New York, Washington] 11 | After removing first occurence of Alaska : 12 | [California, Texas, New York, Texas, Alaska, Florida, California, Arizona, Texas, Alaska, Arizona, California, Florida, Texas, Washington, New York, Washington] 13 | After removing last occurence of Alaska : 14 | [California, Texas, New York, Texas, Alaska, Florida, California, Arizona, Texas, Arizona, California, Florida, Texas, Washington, New York, Washington] 15 | ``` 16 | 17 | 18 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/RemoveFirstLastOccurence/RemoveFirstLastOccurence.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class RemoveFirstLastOccurence 5 | { 6 | public static void main(String[] args) 7 | { 8 | LinkedList linkedList = new LinkedList(); 9 | 10 | linkedList.add("Alaska"); 11 | linkedList.add("California"); 12 | linkedList.add("Texas"); 13 | linkedList.add("New York"); 14 | linkedList.add("Texas"); 15 | linkedList.add("Alaska"); 16 | linkedList.add("Florida"); 17 | linkedList.add("California"); 18 | linkedList.add("Arizona"); 19 | linkedList.add("Texas"); 20 | linkedList.add("Alaska"); 21 | linkedList.add("Arizona"); 22 | linkedList.add("California"); 23 | linkedList.add("Florida"); 24 | linkedList.add("Texas"); 25 | linkedList.add("Washington"); 26 | linkedList.add("New York"); 27 | linkedList.add("Washington"); 28 | 29 | Scanner input = new Scanner(System.in); 30 | 31 | System.out.println("Which element's first and last occurence do you want to remove?"); 32 | 33 | String element = input.nextLine(); 34 | 35 | System.out.println("Original Linked List: "); 36 | 37 | System.out.println(linkedList); 38 | 39 | System.out.println("After removing first occurence of " + element + " : "); 40 | 41 | linkedList.removeFirstOccurrence(element); 42 | 43 | System.out.println(linkedList); 44 | 45 | System.out.println("After removing last occurence of " + element + " : "); 46 | 47 | linkedList.removeLastOccurrence(element); 48 | 49 | System.out.println(linkedList); 50 | } 51 | } -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Reverse LinkedList/README.md: -------------------------------------------------------------------------------- 1 | # Reverse LinkedList 2 | 3 | Reverse a singly linked list 4 | 5 | ### Example: 6 | **Input** : 7 | 8 | ``` java 9 | 1->2->3->4->5->NULL 10 | ``` 11 | 12 | **Output:** : 13 | 14 | ``` java 15 | 5->4->3->2->1->NULL 16 | ``` 17 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Reverse LinkedList/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int x) { 5 | val = x; 6 | } 7 | } 8 | 9 | public class ReverseLinkedList { 10 | public static ListNode reverseList(ListNode head) { 11 | ListNode prev = null; 12 | ListNode curr = head; 13 | while (curr != null) { 14 | ListNode nextTemp = curr.next; 15 | curr.next = prev; 16 | prev = curr; 17 | curr = nextTemp; 18 | } 19 | return prev; 20 | } 21 | 22 | public static void main(String[] args) { 23 | ListNode node1 = new ListNode(1); 24 | ListNode node2 = new ListNode(2); 25 | node1.next = node2; 26 | ListNode node3 = new ListNode(3); 27 | node2.next = node3; 28 | ListNode node4 = new ListNode(4); 29 | node3.next = node4; 30 | ListNode node5 = new ListNode(5); 31 | node4.next = node5; 32 | 33 | ListNode reversedNode = reverseList(node1); 34 | while (reversedNode != null) { 35 | System.out.print(reversedNode.val + "->"); 36 | reversedNode = reversedNode.next; 37 | } 38 | System.out.print("NULL"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Swap nodes in pairs/README.md: -------------------------------------------------------------------------------- 1 | # Swap nodes in pairs 2 | 3 | Given a linked list, swap every two adjacent nodes and return its head. 4 | 5 | You may not modify the values in the list's nodes, only nodes itself may be changed. 6 | 7 | ### Example: 8 | **Input** : 9 | 10 | ``` java 11 | 1->2->3->4 12 | ``` 13 | 14 | **Output:** : 15 | 16 | ``` java 17 | 2->1->4->3 18 | ``` 19 | -------------------------------------------------------------------------------- /Practice Problems/LinkedList/Swap nodes in pairs/SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int x) { 5 | val = x; 6 | } 7 | } 8 | 9 | public class SwapNodesInPairs { 10 | public static ListNode swapPairs(ListNode head) { 11 | if (head == null) return null; 12 | if (head.next == null) return head; 13 | ListNode first = head; 14 | ListNode second = head.next; 15 | ListNode nextNode = second.next; 16 | second.next = first; 17 | first.next = swapPairs(nextNode); 18 | return second; 19 | } 20 | 21 | public static void main(String[] args) { 22 | ListNode node1 = new ListNode(1); 23 | ListNode node2 = new ListNode(2); 24 | node1.next = node2; 25 | ListNode node3 = new ListNode(3); 26 | node2.next = node3; 27 | ListNode node4 = new ListNode(4); 28 | node3.next = node4; 29 | swapPairs(node1); 30 | System.out.print(node2.val); 31 | while (node2.next != null) { 32 | node2 = node2.next; 33 | System.out.print("->" + node2.val); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Adding Reversed Numbers/AddingReversedNumbers.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | class AddingReversedNumbers { 5 | 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | 10 | while (n != 0) { 11 | BigInteger first = sc.nextBigInteger(); 12 | BigInteger second = sc.nextBigInteger(); 13 | 14 | String result = reverseAndAdd(first, second); 15 | 16 | System.out.println(result); 17 | n--; 18 | } 19 | } 20 | 21 | 22 | public static String reverseAndAdd(BigInteger first, BigInteger second) { 23 | StringBuilder firstString = new StringBuilder(first + ""); 24 | StringBuilder secondString = new StringBuilder(second + ""); 25 | 26 | BigInteger firstReversed = new BigInteger(firstString.reverse().toString()); 27 | BigInteger secondReversed = new BigInteger(secondString.reverse().toString()); 28 | BigInteger result = firstReversed.add(secondReversed); 29 | String resultReversed = new StringBuilder(result + "").reverse().toString(); 30 | 31 | return resultReversed.replaceFirst("^0*", ""); 32 | } 33 | } -------------------------------------------------------------------------------- /Practice Problems/Maths/Adding Reversed Numbers/README.md: -------------------------------------------------------------------------------- 1 | # Adding Reversed Numbers 2 | 3 | **Problem from UVA** 4 | 5 | The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play. 6 | 7 | Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros. 8 | 9 | ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12). 10 | 11 | ## Input 12 | The input consists of `N` cases. The first line of the input contains only positive integer `N`. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. **Numbers will be at most `200` characters long**. 13 | 14 | ## Output 15 | For each case, print exactly one line containing only one integer — the reversed sum of two reversed numbers. **Omit any leading zeros in the output**. 16 | 17 | ### Example: 18 | 19 | **Input** : 20 | ```java 21 | 3 22 | 24 1 23 | 4358 754 24 | 305 794 25 | ``` 26 | 27 | **Output:** : 28 | ```java 29 | 34 30 | 1998 31 | 1 32 | ``` 33 | 34 | 35 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Back to Intermediate Math/IntermediateMath.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class IntermediateMath { 5 | public static void main(String arg[]) throws IOException { 6 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 7 | int n = Integer.parseInt(br.readLine()); 8 | 9 | for(int i=0; i 0){ 27 | goingUp = true; 28 | }else if(goingUp && diff < 0){ 29 | isValid = false; 30 | } 31 | 32 | prev = curr; 33 | count++; 34 | 35 | } 36 | 37 | return isValid; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Increasing Decreasing Sequence/README.md: -------------------------------------------------------------------------------- 1 | # Increasing Decreasing Sequence 2 | 3 | **Problem from Coding Blocks** 4 | 5 | Given an array `S` of size `N` , check if it is possible to split sequence into two sequences - 6 | `s1` to `si` and `si+1` to `sN` such that first sequence is strictly decreasing and second is strictly increasing. 7 | 8 | Print `true`/`false` as output. 9 | 10 | ## Input Format 11 | First line contains a single integer `N` denoting the size of the input. 12 | Next `N` lines contain a single integer each denoting the elements of the array `S`. 13 | 14 | ## Constraints 15 | `0 < N < 1000` Each number in sequence `S > 0 and < 1000000000` 16 | 17 | ## Output Format 18 | Print boolean output - "true" or "false" defining whether the sequence is increasing - decreasing or not. 19 | 20 | ### Example: 21 | **Input** : 22 | ```java 23 | 5 24 | 1 25 | 2 26 | 3 27 | 4 28 | 5 29 | ``` 30 | 31 | **Output:** : `true` 32 | 33 | **Explanation** : Carefully read the conditions to judge which all sequences may be valid. Don't use arrays or lists. 34 | 35 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Jewel-eating Monsters/JewelEatingMonsters.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class JewelEatingMonsters { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | 7 | while(2>1) { 8 | 9 | long x = sc.nextLong(); 10 | long a = sc.nextLong(); 11 | long n = sc.nextLong(); 12 | long c = sc.nextLong(); 13 | 14 | if (n == 0 && a == 0 && x == 0 && c == 0) return; 15 | 16 | long gold = x; 17 | 18 | for (int i = 0; i < n; i++) { 19 | gold = (gold - 1) * a; 20 | gold %= c; 21 | } 22 | 23 | gold = (gold + c) % c; 24 | System.out.println(gold); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Jewel-eating Monsters/README.md: -------------------------------------------------------------------------------- 1 | # Jewel-eating Monsters 2 | 3 | **Problem from ICPC** 4 | 5 | According to ancient legends, deep in the Forest of Walking Trees lies a mystical cave called the Cave of Infinite Wealth. In the middle of a huge cavern there is a lake surrounded by stalactites and stalagmites. The dark, cold water of the lake has magical properties; if anyone tosses a gold coin into the lake at midnight and spends the night in the cave, then he will find that he has more money in the morning than he had in the evening. More precisely, if he had `x` gold coins (after tossing one into the water), then he will have `αx` gold coins in the morning. 6 | 7 | The famous adventurer Gorgon Rattlesnake spent many years finding the cave. As you can imagine,the exact location is a well-guarded secret. Finally, after studying countless old maps, consulting with many famous sages, and making heavy use of GPS technology, he managed to arrive at the entrance 8 | of the cave. Gorgon Rattlesnake spent `n` nights in the cavern, tossing a coin into the lake each night. After `n` nights, he travelled to the bustling city of Tse’padub. In Tse’padub, he visited the jewellery shop, and 9 | bought diamond rings to make transporting his valuables easier. Each diamond ring costs `c` gold coins, and he bought as many diamond rings as he could. 10 | So far he was lucky. But shortly after he left the jewellery shop, he was attacked by jewel-eating monsters. These monsters did not harm him, but they ate all the diamond rings. For this reason, Gorgon Rattlesnake was left with no other valuables than the remaining gold coins. How many gold coins does he have? 11 | 12 | ## Input 13 | The input contains several blocks of test cases. Each case consists of four integers separated by spaces: 14 | - The number `2 ≤ x ≤ 100000000` of coins Gorgon Rattlesnake had when he arrived to the cave. 15 | - The number `2 ≤ α ≤ 100000000` that the gold coins are multiplied by each night. 16 | - The number `1 ≤ n ≤ 100000000` of nights Gorgon Rattlesnake spent in the cave. 17 | - The cost `2 ≤ c ≤ 100000000` of a diamond rings. 18 | It can be assumed (for mysterious reasons) that c is always a prime number. 19 | The input is terminated by a block with `x = α = n = c = 0`. 20 | 21 | Output 22 | For each test case, you have to output a line containing a single integer: the number of gold coins Gorgon Rattlesnake has. 23 | 24 | ### Example: 25 | 26 | **Input** : 27 | ```java 28 | 52 7 1 691 29 | 27 4 56 379 30 | 94 7 63 103 31 | 38 2 88 557 32 | 62 11 86 433 33 | 0 0 0 0 34 | ``` 35 | 36 | **Output** : 37 | ```java 38 | 357 39 | 198 40 | 82 41 | 177 42 | 394 43 | ``` 44 | 45 | 46 | -------------------------------------------------------------------------------- /Practice Problems/Maths/My Sqrt/MySqrt.java: -------------------------------------------------------------------------------- 1 | class MySqrt { 2 | public static void main(String[] args) { 3 | int n = 8; 4 | 5 | System.out.println(mySqrt(n)); 6 | } 7 | 8 | 9 | public static int mySqrt(int x) { 10 | if (x == 0 || x == 1) { 11 | return x; 12 | } 13 | int left = 1; 14 | int right = x; 15 | int ans = 0; 16 | 17 | while (left <= right) { 18 | int mid = left + (right - left) / 2; 19 | 20 | if (mid == x / mid) { 21 | return mid; 22 | } 23 | 24 | if (mid < x / mid) { 25 | left = mid + 1; 26 | ans = mid; 27 | } else { 28 | right = mid - 1; 29 | } 30 | } 31 | return ans; 32 | } 33 | } -------------------------------------------------------------------------------- /Practice Problems/Maths/My Sqrt/README.md: -------------------------------------------------------------------------------- 1 | # My Sqrt 2 | 3 | **Problem from LeetCode** 4 | 5 | Implement int sqrt(int x). 6 | 7 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 8 | 9 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 10 | 11 | ### Example: 12 | 13 | *E.g - 1* 14 | 15 | **Input** : `4` 16 | 17 | **Output:** : `2` 18 | 19 | 20 | *E.g - 2* 21 | 22 | **Input** : `8` 23 | 24 | **Output:** : `2` 25 | 26 | **Explanation** : The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. 27 | 28 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Plus One/PlusOne.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class PlusOne { 4 | public static void main(String[] args) { 5 | 6 | int[] digits = {2, 1, 9}; 7 | 8 | int[] res = plusOne(digits); 9 | 10 | System.out.println(Arrays.toString(res)); 11 | } 12 | 13 | public static int[] plusOne(int[] digits) { 14 | for(int i = digits.length - 1; i >= 0; i--) { 15 | if(digits[i] < 9) { 16 | digits[i]++; 17 | return digits; 18 | } 19 | 20 | digits[i] = 0; 21 | } 22 | 23 | int[] result = new int[digits.length + 1]; 24 | result[0] = 1; 25 | 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Plus One/README.md: -------------------------------------------------------------------------------- 1 | # Plus One 2 | 3 | **Problem from LeetCode** 4 | 5 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 6 | 7 | The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 8 | 9 | You may assume the integer does not contain any leading zero, except the number 0 itself. 10 | 11 | ### Example: 12 | **Input** : `[4,3,2,1]` 13 | 14 | **Output:** : `[4,3,2,2]` 15 | 16 | **Explanation** : The array represents the integer 4321. 17 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Power x To n/PowerxTon.java: -------------------------------------------------------------------------------- 1 | class PowerxTon { 2 | public static void main(String arg[]) { 3 | int x = 2; 4 | int n = 2; 5 | double result = myPow(x, n); 6 | System.out.println(result); 7 | } 8 | 9 | public static double myPow(double x, int n) { 10 | if(n == 0) { 11 | return 1; 12 | } 13 | 14 | if(Double.isInfinite(x)) { 15 | return 0; 16 | } 17 | 18 | if(n < 0) { 19 | n = -n; 20 | x = 1 / x; 21 | } 22 | 23 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 24 | } 25 | } -------------------------------------------------------------------------------- /Practice Problems/Maths/Power x To n/README.md: -------------------------------------------------------------------------------- 1 | # Power x To n 2 | 3 | Implement pow(x, n). 4 | 5 | ### Example: 6 | 7 | **Input** : 8 | ```java 9 | x = 2; 10 | n = 2; 11 | ``` 12 | 13 | **Output** : 14 | ```java 15 | 4 16 | ``` 17 | 18 | 19 | -------------------------------------------------------------------------------- /Practice Problems/Maths/README.md: -------------------------------------------------------------------------------- 1 | # Maths 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Adding Reversed Numbers](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Adding%20Reversed%20Numbers) 6 | - [Back to Intermediate Math](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Back%20to%20Intermediate%20Math) 7 | - [Increasing Decreasing Sequence](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Increasing%20Decreasing%20Sequence) 8 | - [Jewel-eating Monsters](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Jewel-eating%20Monsters) 9 | - [My Sqrt](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/My%20Sqrt) 10 | - [Plus One](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Plus%20One) 11 | - [Power x To n](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Power%20x%20To%20n) 12 | - [Reach A Number](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Reach%20A%20Number) 13 | - [Reduce Substracted Form](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/Reduced%20Subtracted%20Form) 14 | - [The 3n + 1 problem](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/The%203n%20%2B%201%20problem) 15 | - [ZSUM - Just add it](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths/ZSUM%20-%20Just%20add%20it) 16 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Reach A Number/README.md: -------------------------------------------------------------------------------- 1 | # React A Number 2 | 3 | **Problem from PrepBytes** 4 | 5 | Given a number `N`, write a program to find the least number of operations required to reach `N` from **ZERO**, using following opreations only: 6 | - Double the number 7 | - Add one to the number 8 | 9 | ### Example: 10 | **Input** : `6` 11 | 12 | **Output:** : `4` 13 | 14 | **Explanation** : As the input is `6`. 15 | 16 | We start from 0 add one to it than the results is 1 (step 1)
17 | then add one to 1 it that results in 2 (step 2).
18 | then add one to 2 it that results in 3 (step 3).
19 | then we double the number 3 that results in 6 (step 4).
Hence `4` is the answer. 20 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Reach A Number/ReachANumber.java: -------------------------------------------------------------------------------- 1 | class ReachANumber { 2 | public static void main(String[] args) { 3 | 4 | int num = 6; 5 | 6 | int res = reachNumber(num); 7 | 8 | System.out.println(res); 9 | } 10 | 11 | public static int reachNumber(int num) { 12 | // steps = 1 becasue from 0 -> 1 one step 13 | int steps = 1; 14 | 15 | while( num > 1 ) { 16 | 17 | if(num%2 == 1) { 18 | num = num - 1; 19 | steps++; 20 | } 21 | 22 | num /= 2; 23 | steps++; 24 | } 25 | 26 | return steps; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Reduced Subtracted Form/README.md: -------------------------------------------------------------------------------- 1 | # Reduced Subtracted Form 2 | 3 | **Problem from Unknown Source** 4 | 5 | Given a number you are expected to find it's two digit reduced substracted form. 6 | 7 | The Reduced Subtracted Form (RSF) of a number can be found by concatenating the difference between it's adjacent digits. 8 | 9 | To find the two digit reduced substracted form, we need to continue this process till the resultant RSF is not two digit number. 10 | 11 | ### Example: 12 | **Input** : `6928` 13 | 14 | **Output:** : `376` 15 | 16 | **Explanation** : As the input is `6928`. 17 | 18 | The RFS can be found by concatenating the difference between `(6 and 9)`, `(9 and 2)`, and `(2 and 8)` as shown below.
19 | difference between `6` and `9` is `3`
20 | difference between `9` and `2` is `7`
21 | difference between `2` and `8` is `6`
22 | So the RSF of `6923` = 376.
23 | Now continuing the same process we will get the RSF of `376` is `41`.
24 | Hence the result is `41` 25 | 26 | -------------------------------------------------------------------------------- /Practice Problems/Maths/Reduced Subtracted Form/ReducedSubstractionForm.java: -------------------------------------------------------------------------------- 1 | class ReducedSubstractionForm { 2 | public static void main(String[] args) { 3 | int num = 5271; 4 | 5 | int ans = num; 6 | while(ans >= 99) { 7 | ans = reduce(ans); 8 | } 9 | 10 | System.out.println(ans); 11 | } 12 | 13 | public static int reduce(int num) { 14 | int ans = 0; 15 | 16 | int prev = num%10; 17 | num = num/10; 18 | 19 | int i = 0; 20 | 21 | while(num > 0) { 22 | int curr = num%10; 23 | int n = Math.abs(curr - prev); 24 | 25 | ans += n*Math.pow(10, i); 26 | i++; 27 | 28 | num = num/10; 29 | prev = curr; 30 | } 31 | 32 | return ans; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Practice Problems/Maths/The 3n + 1 problem/README.md: -------------------------------------------------------------------------------- 1 | # The 3n + 1 problem 2 | 3 | **Problem from UVA** 4 | 5 | Problems in Computer Science are often classified as belonging to a certain class of problems (e.g. NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs. 6 | 7 | Consider the following algorithm: 8 | ``` java 9 | 1. input n 10 | 2. print n 11 | 3. if n = 1 then STOP 12 | 4. if n is odd then n ←− 3n + 1 13 | 5. else n ←− n/2 14 | 6. GOTO 2 15 | ``` 16 | Given the input `22`, the following sequence of numbers will be printed: 17 | 18 | `22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1` 19 | 20 | It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers `n` such that `0 < n < 1,000,000` (and, in fact, for many more numbers than this.) 21 | 22 | Given an input `n`, it is possible to determine the number of numbers printed before and including the `1` is printed. For a given `n` this is called the cycle-length of `n`. In the example above, the cycle length of `22` is `16`. For any two numbers `i` and `j` you are to determine the maximum cycle length over all numbers between and including both `i` and `j`. 23 | 24 | ## Input 25 | The input will consist of a series of pairs of integers `i` and `j`, one pair of integers per line. All integers will be less than `10,000` and greater than `0`. You should process all pairs of integers and for each pair determine the maximum cycle length over 26 | all integers between and including `i` and `j`. You can assume that no operation overflows a 32-bit integer. 27 | 28 | ## Output 29 | For each pair of input integers `i` and `j` you should output `i`, `j`, and the maximum cycle length for integers between and including `i` and `j`. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers `i` and `j` must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line). 30 | 31 | ### Example: 32 | **Input** : 33 | ```java 34 | 1 10 35 | 100 200 36 | 201 210 37 | 900 1000 38 | ``` 39 | 40 | **Output:** : 41 | ```java 42 | 1 10 20 43 | 100 200 125 44 | 201 210 89 45 | 900 1000 174 46 | ``` 47 | -------------------------------------------------------------------------------- /Practice Problems/Maths/The 3n + 1 problem/The3nplus1.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.util.StringTokenizer; 5 | 6 | class The3nplus1 { 7 | 8 | public static int [] cache=new int [3000000]; 9 | 10 | public static void main(String[] args) throws IOException { 11 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 | String s; 13 | 14 | cache[1]=1; 15 | 16 | while((s = br.readLine()) != null) { 17 | StringTokenizer st = new StringTokenizer(s); 18 | int int1 = Integer.parseInt(st.nextToken()); 19 | int int2 = Integer.parseInt(st.nextToken()); 20 | int min = Math.min(int1, int2); 21 | int max = Math.max(int1, int2); 22 | 23 | int maxCycle = 0; 24 | 25 | for (int i = min; i <= max; i++) { 26 | maxCycle = Math.max(length(i), maxCycle); 27 | } 28 | 29 | System.out.println(int1+" "+int2+" "+maxCycle); 30 | } 31 | } 32 | 33 | public static int length(int n) { 34 | if(n < cache.length) { 35 | if(cache[n] == 0) { 36 | if(n%2 == 0) { 37 | cache[n] = 1 + length(n/2); 38 | } else { 39 | cache[n] = 1 + length(3*n+1); 40 | } 41 | } 42 | 43 | return cache[n]; 44 | } else { 45 | if(n%2 == 0) { 46 | return 1 + length(n/2); 47 | } else { 48 | return 1 + length(3*n+1); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Practice Problems/Maths/ZSUM - Just add it/README.md: -------------------------------------------------------------------------------- 1 | # ZSUM - Just add it 2 | 3 | **Problem from SPOJ** 4 | 5 | For two given integers `n` and `k` find Zn + Zn-1 - 2Zn-2 mod 10000007 , where Zn = Sn + Pn and Sn = 1k + 2k + 3k + … + nk and Pn = 11 + 22 + 33 + … + nn. 6 | 7 | ## Input 8 | There are several test cases (≤ 10000). In each case two space separated positive integers `n` and `k` are given. 9 | For last test case `n` and `k` are given as `0 0`, which is not to be processed. 10 | 11 | ## Constraints 12 | `1 < n < 200000000` 13 | 14 | `0 < k < 1000000` 15 | 16 | Output 17 | For each case print the asked value in separate line. 18 | 19 | ### Example: 20 | 21 | **Input** : 22 | ```java 23 | 10 3 24 | 9 31 25 | 83 17 26 | 5 2 27 | 0 0 28 | ``` 29 | 30 | **Output** : 31 | ```java 32 | 4835897 33 | 2118762 34 | 2285275 35 | 3694 36 | ``` 37 | 38 | 39 | -------------------------------------------------------------------------------- /Practice Problems/Maths/ZSUM - Just add it/Zsum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Zsum { 4 | 5 | static long mod = 10000007; 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | 10 | while(1 == 1) { 11 | long N = sc.nextLong(); 12 | long K = sc.nextLong(); 13 | 14 | if(N ==0 && K == 0) { 15 | return; 16 | } 17 | 18 | long ans = 2 * power(N - 1, K) + power(N, K) + 2 * power(N - 1, N - 1) + power(N, N); 19 | 20 | ans = ans % mod; 21 | System.out.println(ans); 22 | } 23 | } 24 | 25 | static long power (long a, long n) { 26 | long result = 1; 27 | 28 | a %= mod; 29 | 30 | while (n > 0) { 31 | if(n % 2 == 1) 32 | result = (result * a )% mod; 33 | n >>= 1; 34 | a = (a * a) % mod; 35 | 36 | } 37 | return result; 38 | } 39 | } -------------------------------------------------------------------------------- /Practice Problems/Patterns/Diamond/Diamond.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Diamond { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | System.out.println("Enter the number of rows needed to print the pattern "); 7 | int rows = scanner.nextInt(); 8 | 9 | System.out.println("## Printing the pattern ##"); 10 | 11 | for (int i=1; i<=rows; i++) { 12 | for (int j=rows; j>i; j--) { 13 | System.out.print(" "); 14 | } 15 | for (int k=1; k<=(i * 2) -1; k++){ 16 | System.out.print("*"); 17 | } 18 | System.out.println(); 19 | } 20 | for (int i=rows-1; i>=1; i--) { 21 | 22 | for (int j=rows-1; j>=i; j--) { 23 | System.out.print(" "); 24 | } 25 | 26 | for (int k=1; k<=(i * 2) -1; k++) { 27 | System.out.print("*"); 28 | } 29 | 30 | System.out.println(); 31 | } 32 | 33 | scanner.close(); 34 | } 35 | } -------------------------------------------------------------------------------- /Practice Problems/Patterns/Diamond/README.md: -------------------------------------------------------------------------------- 1 | # Diamond 2 | 3 | Given a side `n` print a pattern of Diamond. 4 | 5 | ### Example: 6 | **Input** : `5` 7 | 8 | **Output:** : 9 | 10 | ``` 11 | * 12 | *** 13 | ***** 14 | ******* 15 | ********* 16 | ******* 17 | ***** 18 | *** 19 | * 20 | ``` 21 | -------------------------------------------------------------------------------- /Practice Problems/Patterns/Ganeshas Pattern/GaneshasPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class GaneshasPattern { 3 | public static void main(String[] args) { 4 | Scanner sc=new Scanner(System.in); 5 | int n=sc.nextInt(); 6 | printGaneshasPattern(n); 7 | } 8 | private static void printGaneshasPattern(int n){ 9 | if(n%2==1){ 10 | int first=1, middle=(n+1)/2, last=n; 11 | 12 | for(int row=1; row<=n; row++){ 13 | for(int col=1; col<=n; col++){ 14 | if(rowmiddle) 24 | if (row == first) 25 | System.out.print("*"); 26 | 27 | } else if(row==middle) 28 | System.out.print("*"); 29 | else if (col < middle) 30 | if (row == last) 31 | System.out.print("*"); 32 | else 33 | System.out.print(" "); 34 | 35 | else if (col == middle) 36 | System.out.print("*"); 37 | else if (col == last) 38 | System.out.print("*"); 39 | else 40 | System.out.print(" "); 41 | } 42 | System.out.println(); 43 | } 44 | } else { 45 | System.out.println("Enter odd digit"); 46 | } 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Practice Problems/Patterns/Ganeshas Pattern/README.md: -------------------------------------------------------------------------------- 1 | # Ganeshas Pattern 2 | 3 | **Problem from Hackerearth Practice Problem** 4 | 5 | Given the number of rows `n` print the Ganeshas Pattern. 6 | 7 | ### Example: 8 | **Input** : `7` 9 | 10 | **Output:** : 11 | 12 | * **** 13 | * * 14 | * * 15 | ******* 16 | * * 17 | * * 18 | **** * 19 | -------------------------------------------------------------------------------- /Practice Problems/Patterns/Hollow Rhombus/HollowRhombus.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class HollowRhombus { 4 | public static void printPattern(int rows) { 5 | 6 | 7 | for(int i = 0; i i; j--) { 11 | System.out.print(" "); 12 | } 13 | 14 | for(j=0; j= 0; i--) 29 | { 30 | for (int j=0; j< i ;j++) 31 | { 32 | System.out.print(" "); 33 | } 34 | for (int k=i; k<=numRow-1; k++) 35 | { 36 | System.out.print("* "); 37 | } 38 | System.out.println(""); 39 | } 40 | input.close(); 41 | } 42 | } -------------------------------------------------------------------------------- /Practice Problems/README.md: -------------------------------------------------------------------------------- 1 | # Practice Problems 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Topics 5 | - [Arrays](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Arrays) 6 | - [Backtracking](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Backtracking) 7 | - [BinarySearch](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/BinarySearch) 8 | - [Dynamic Programming](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Dynamic%20Programming) 9 | - [LinkedList](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/LinkedList) 10 | - [Maths](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Maths) 11 | - [Patterns](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Patterns) 12 | - [Stack](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Stack) 13 | - [Strings](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Practice Problems/Stack/Maximum Area Histogram/MaximumAreaHistogram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class MaximumAreaHistogram { 5 | 6 | public static void main(String[] args){ 7 | int hist[] = {2, 1, 4, 5, 1, 3, 3}; 8 | int maximumArea = largestRectangleArea(hist); 9 | System.out.println(maximumArea); 10 | } 11 | 12 | public static int largestRectangleArea(int[] A) { 13 | Stack st = new Stack(); 14 | int ans = 0; 15 | for (int i = 0 ; i < A.length || !st.isEmpty(); ){ 16 | if (i >= A.length){ 17 | ans = Math.max(ans, A[st.pop()] * (st.isEmpty() ? i : i - st.peek() - 1) ); 18 | continue; 19 | } 20 | if (st.isEmpty() || A[st.peek()] <= A[i]){ 21 | st.push(i++); 22 | }else if (A[st.peek()] > A[i]){ 23 | ans = Math.max(ans, A[st.pop()] * (st.isEmpty() ? i : i - st.peek() - 1) ); 24 | } 25 | } 26 | return ans; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Practice Problems/Stack/Maximum Area Histogram/README.md: -------------------------------------------------------------------------------- 1 | # Maximum Area Histogram 2 | 3 | **2003/2004 ACM ICPC University of Ulm Local Contest** 4 | 5 | A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Given, heights of rectangles, calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. 6 | 7 | ### Example: 8 | **Input** : `[2, 1, 4, 5, 1, 3, 3]` 9 | 10 | **Output:** : `8` 11 | -------------------------------------------------------------------------------- /Practice Problems/Stack/Maximum Element/MaximumElement.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class MaximumElement { 5 | 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int n = sc.nextInt(); 9 | Stack maxStack = new Stack<>(); 10 | ArrayDeque stack = new ArrayDeque<>(); 11 | for(int i=0;i=maxStack.peek()){ 19 | maxStack.push(val); 20 | } 21 | break; 22 | 23 | case 2 : int popped = stack.pop(); 24 | if(popped == maxStack.peek()){ 25 | maxStack.pop(); 26 | } 27 | break; 28 | 29 | case 3 : 30 | System.out.println(maxStack.peek()); 31 | break; 32 | 33 | default: break; 34 | } 35 | } 36 | sc.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Practice Problems/Stack/Maximum Element/README.md: -------------------------------------------------------------------------------- 1 | # Maximum Element 2 | **Problem from Hackerrank** 3 | 4 | You have an empty sequence, and you will be given **N** queries. Each query is one of these three types: 5 | 6 | 1. Push the element `x` into the stack. 7 | 2. Delete the element present at the top of the stack. 8 | 3. Print the maximum element in the stack. 9 | 10 | The first line of input contains an integer, `N` . The next `N` lines each contain an above mentioned query. (It is guaranteed that each query is valid.) 11 | 12 | ### **Example** 13 | 14 | **Input**: 15 | 16 | ``` java 17 | 10 18 | 1 97 19 | 2 20 | 1 20 21 | 2 22 | 1 26 23 | 1 20 24 | 2 25 | 3 26 | 1 91 27 | 3 28 | ``` 29 | 30 | **Output:**: 31 | 32 | ``` java 33 | 26 34 | 91 35 | ``` 36 | -------------------------------------------------------------------------------- /Practice Problems/Stack/README.md: -------------------------------------------------------------------------------- 1 | # Stack 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Maximum Area Historgram](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Stack/Maximum%20Area%20Histogram) 6 | - [Sort Stack](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Stack/Sort%20Stack) 7 | -------------------------------------------------------------------------------- /Practice Problems/Stack/Sort Stack/README.md: -------------------------------------------------------------------------------- 1 | # Sort Stack 2 | 3 | **Problem from algorithms.tutorialhorizon** 4 | 5 | Given a stack of integers, write an algorithm to sort the stack using a temporary stack. 6 | 7 | ### Example: 8 | **Input** : `[14, 9, 67, 91, 101, 25]` 9 | 10 | **Output:** : `[9, 14, 25, 67, 91, 101]` -------------------------------------------------------------------------------- /Practice Problems/Stack/Sort Stack/SortStack.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class SortStack { 4 | 5 | public static void main(String args[]) { 6 | 7 | Stack originalStack = new Stack<>(); 8 | 9 | originalStack.add(14); 10 | originalStack.add(9); 11 | originalStack.add(67); 12 | originalStack.add(91); 13 | originalStack.add(101); 14 | originalStack.add(25); 15 | 16 | System.out.println("Original Stack: " + originalStack); 17 | 18 | Stack sortedStack= sorting(originalStack); 19 | 20 | System.out.println("Sorted Stack is: " + sortedStack); 21 | } 22 | 23 | public static Stack sorting(Stack original) { 24 | Stack temporaryStack = new Stack<>(); 25 | 26 | while(!original.isEmpty()) { 27 | 28 | int x = original.pop(); 29 | 30 | while(!temporaryStack.isEmpty() && temporaryStack.peek() > x) { 31 | original.push(temporaryStack.pop()); 32 | } 33 | 34 | temporaryStack.push(x); 35 | } 36 | 37 | return temporaryStack; 38 | } 39 | } -------------------------------------------------------------------------------- /Practice Problems/Strings/Buddy String/BuddyString.java: -------------------------------------------------------------------------------- 1 | // Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: A = "ab", B = "ba" 8 | // Output: true 9 | // Example 2: 10 | 11 | // Input: A = "ab", B = "ab" 12 | // Output: false 13 | // Example 3: 14 | 15 | // Input: A = "aa", B = "aa" 16 | // Output: true 17 | // Example 4: 18 | 19 | // Input: A = "aaaaaaabc", B = "aaaaaaacb" 20 | // Output: true 21 | // Example 5: 22 | 23 | // Input: A = "", B = "aa" 24 | // Output: false 25 | 26 | 27 | // Note: 28 | 29 | // 0 <= A.length <= 20000 30 | // 0 <= B.length <= 20000 31 | // A and B consist only of lowercase letters. 32 | 33 | 34 | class Solution { 35 | public boolean buddyStrings(String A, String B) { 36 | 37 | if(str1.length() != str2.length()) { 38 | return false; 39 | } 40 | 41 | int n = str1.length(); 42 | 43 | int prev = -1; 44 | int next = -1; 45 | int count = 0; 46 | 47 | if(str1.equals(str2)) { 48 | HashSet set = new HashSet<>(); 49 | for (char c : str1.toCharArray()) 50 | { 51 | set.add(c); 52 | } 53 | return set.size() < n; 54 | } 55 | 56 | for(int i=0; i 2) return false; 61 | 62 | prev = next; 63 | next = i; 64 | } 65 | 66 | } 67 | 68 | return count == 2 && str1.charAt(prev) == str2.charAt(next) && str1.charAt(next) == str2.charAt(prev); 69 | 70 | } 71 | } -------------------------------------------------------------------------------- /Practice Problems/Strings/Buddy String/README.md: -------------------------------------------------------------------------------- 1 | # Buddy String 2 | 3 | **Problem from LeetCode** 4 | 5 | Given two strings `A` and `B` of lowercase letters, return true if and only if we can swap two letters in `A` so that the result equals `B`. 6 | 7 | ## Note: 8 | `0 <= A.length <= 20000` 9 | 10 | `0 <= B.length <= 20000` 11 | 12 | `A` and `B` consist only of lowercase letters. 13 | 14 | 15 | ## Examples 16 | 17 | ### 1 18 | ``` 19 | Input: A = "ab", B = "ba" 20 | Output: true 21 | ``` 22 | 23 | ### 2 24 | ``` 25 | Input: A = "ab", B = "ab" 26 | Output: false 27 | ``` 28 | 29 | ### 3 30 | ``` 31 | Input: A = "aa", B = "aa" 32 | Output: true 33 | ``` 34 | 35 | ### 4 36 | ``` 37 | Input: A = "aaaaaaabc", B = "aaaaaaacb" 38 | Output: true 39 | ``` 40 | 41 | ### 5 42 | ``` 43 | Input: A = "", B = "aa" 44 | Output: false 45 | ``` 46 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Hamming Distance/HammingDistance.java: -------------------------------------------------------------------------------- 1 | class HammingDistance { 2 | public static int hammingDist(String str1, String str2) { 3 | int i = 0, distance = 0; 4 | 5 | if(str1.length() != str2.length()) { 6 | System.out.println("Strings length are not equal."); 7 | return -1; 8 | } 9 | 10 | while (i < str1.length()) { 11 | if (str1.charAt(i) != str2.charAt(i)) 12 | distance++; 13 | i++; 14 | } 15 | 16 | return distance; 17 | } 18 | 19 | public static void main(String[] args) { 20 | 21 | String str1 = "karolin"; 22 | String str2 = "kerstin"; 23 | 24 | int dist = hammingDist(str1, str2); 25 | 26 | System.out.println("Hamming Distance = " + dist); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Hamming Distance/README.md: -------------------------------------------------------------------------------- 1 | # Hamming Distance 2 | 3 | The hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. 4 | 5 | ### Example: 6 | **Input** : 7 | 8 | ``` java 9 | str1 = "karolin"; 10 | str2 = "kerstin"; 11 | ``` 12 | 13 | **Output:** : 14 | 15 | ``` java 16 | Hamming Distance = 3 17 | ``` 18 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Help Me Play/HelpMePlay.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class HelpMePlay { 5 | 6 | public static void main(String as[]) throws Exception { 7 | 8 | BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); 9 | 10 | int testCases = Integer.parseInt(bf.readLine()); 11 | 12 | for(int x=0; x=0 && s.indexOf('m')>=0 && s.indexOf('b')>=0) { 17 | if(s.indexOf('k')!=s.lastIndexOf('k')) { 18 | System.out.println("Yes"); 19 | } else { 20 | System.out.println("No"); 21 | } 22 | } else { 23 | System.out.println("No"); 24 | } 25 | 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Help Me Play/README.md: -------------------------------------------------------------------------------- 1 | # Help Me Play 2 | 3 | Everyone is playing IPL (Indian Premier League) but we all know who is not because they are busy creating team names likes making new words from a given string using some or all of its alphabets. 4 | 5 | They can rearrange the alphabets as well to create new words. For instance the only words that they can make from string `ab` are `a`, `b`, `ba`, `ab`. You cannot make anything else from `ab`. This time they are interested in knowing whether they can make **`pkmkb`** from a given string or not. The players can be allowed to play only if they can solve the question. But you being an incredible supporter of IPL is asked to solve this question. 6 | 7 | ### Input: 8 | first line will consist of number of test cases **T**. 9 | The first and only line of each test case consist of the given string. 10 | 11 | ### Output: 12 | For each test print "**Yes**" (without quotes) if it's possible to make `pkmkb` from the string else print "**No**" (without quotes) in new line. 13 | 14 | ### Constraints: 15 | 16 | 1 < *T* < 200000.
17 | 1 < *String length* < 30. 18 | 19 | ### Example: 20 | **Input** : 21 | 2
22 | pkmkb
23 | pmkb
24 | 25 | **Output:** : 26 | Yes 27 | No 28 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Longest Substring without Repeating Char/LongestSubstringWithoutRepeatingChar.java: -------------------------------------------------------------------------------- 1 | public class LongestSubstringWithoutRepeatingChar { 2 | 3 | public static void main(String[] args) { 4 | 5 | //Given String 6 | String input = "abcabcbb"; 7 | 8 | int startIndex = 0, i, j, tempLen = 0, resLen = 1; 9 | char[] inputArray = input.toCharArray(); 10 | 11 | if (inputArray.length == 0) return; 12 | 13 | for (i = 1; i < inputArray.length; i++) { 14 | for (j = startIndex; j < i; j++) { 15 | //We found same character twice 16 | if (inputArray[i] == inputArray[j]) { 17 | //Move our startIndex such that the new substring doesn't contain repeating character 18 | startIndex = j + 1; 19 | break; 20 | } 21 | } 22 | tempLen = i - startIndex + 1; 23 | resLen = max(tempLen, resLen); 24 | } 25 | 26 | //Print the maximum length of the non-repeating subsequence 27 | System.out.println(resLen); 28 | } 29 | 30 | public static int max(int a, int b) { 31 | if (a > b) return a; 32 | else return b; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Longest Substring without Repeating Char/README.md: -------------------------------------------------------------------------------- 1 | # Length of the longest substring without repeating characters 2 | 3 | **Problem from GeeksForGeeks** 4 | 5 | Given a string `input`, find the length of the longest substring without repeating characters. 6 | 7 | ### Example: 8 | 9 | #### 1 10 | 11 | **Input** : 12 | ```java 13 | input = “ABDEFGABEF” 14 | ``` 15 | 16 | **Output:** : 17 | ```java 18 | 6 19 | ``` 20 | **Explaination** : 21 | ```java 22 | For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length `6`. 23 | ``` 24 | 25 | #### 2 26 | 27 | **Input** : 28 | ```java 29 | input = "abcabcbb" 30 | ``` 31 | 32 | **Output:** : 33 | ```java 34 | 3 35 | ``` 36 | 37 | **Explaination** : 38 | ```java 39 | For “abcabcbb”, the longest substring are “abc”, "bca" and "cab", with length `3`. 40 | ``` 41 | -------------------------------------------------------------------------------- /Practice Problems/Strings/README.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | All questions added here are taken from various sites like GeeksForGeeks, LeetCode, Hackerrank, CodeForces, etc. 3 | 4 | ## Problems 5 | - [Buddy String](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Buddy%20String) 6 | - [Hamming Distance](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Hamming%20Distance) 7 | - [Help Me Play](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Help%20Me%20Play) 8 | - [Longest Substring without Repeating Char](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Longest%20Substring%20without%20Repeating%20Char) 9 | - [Reverse In Parentheses](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Reverse%20In%20Parentheses) 10 | - [Valid Palidrome](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Valid%20Palidrome) 11 | - [Vaild Word Abbreviation](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/Valid%20Word%20Abbreviation) 12 | - [ZigZag Conversion](https://github.com/srsandy/Data-Structures-and-Algorithms-in-Java-2nd-Edition-by-Robert-Lafore/tree/master/Practice%20Problems/Strings/ZigZag%20Conversion%20) 13 | 14 | 15 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Reverse In Parentheses/README.md: -------------------------------------------------------------------------------- 1 | # Reverse In Parentheses 2 | 3 | **Problem from CodeSignal** 4 | 5 | Write a function that reverses characters in (possibly nested) parentheses in the input string. 6 | 7 | Input strings will always be well-formed with matching `()` s. 8 | 9 | ### Example: 10 | **Input** : 11 | ```java 12 | s = "foo(bar)baz"; 13 | ``` 14 | 15 | **Output** : 16 | ```java 17 | foorabbaz 18 | ``` -------------------------------------------------------------------------------- /Practice Problems/Strings/Reverse In Parentheses/ReverseInParentheses.java: -------------------------------------------------------------------------------- 1 | import java.lang.StringBuilder; 2 | 3 | class ReverseInParentheses { 4 | public static String reverseInParentheses(String s) { 5 | StringBuilder str = new StringBuilder(""); 6 | 7 | int start = 0; 8 | int end = s.length() - 1; 9 | 10 | if (s.contains("(")) { 11 | start = s.lastIndexOf("("); 12 | end = s.indexOf(")", start); 13 | str.append(s, start+1, end); 14 | return reverseInParentheses(s.substring(0, start) + str.reverse().toString() + s.substring(end+1)); 15 | } 16 | 17 | return s; 18 | } 19 | 20 | public static void main(String[] args) { 21 | 22 | String s = "foo(bar)baz"; 23 | 24 | String solution = reverseInParentheses(s); 25 | 26 | System.out.println(solution); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Valid Palindrome/README.md: -------------------------------------------------------------------------------- 1 | # Valid Palindrome 2 | 3 | **Problem from LeetCode** 4 | 5 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 6 | 7 | ### Example: 8 | **Input** : 9 | 10 | ``` java 11 | str1 = "Red rum, sir, is murder"; 12 | ``` 13 | 14 | **Output:** : 15 | 16 | ``` java 17 | true 18 | ``` 19 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Valid Palindrome/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | class ValidPalindrome { 2 | public static boolean isPalindrome(String s) { 3 | int left = 0; 4 | int right = s.length() - 1; 5 | 6 | while(left < right) { 7 | while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { 8 | left++; 9 | } 10 | 11 | while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { 12 | right--; 13 | } 14 | 15 | if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 16 | return false; 17 | } 18 | 19 | left++; 20 | right--; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | public static void main(String[] args) { 27 | 28 | String str1 = "Red rum, sir, is murder"; 29 | 30 | boolean is = isPalindrome(str1); 31 | 32 | System.out.println(is); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Valid Word Abbreviation/README.md: -------------------------------------------------------------------------------- 1 | # Valid Word Abbreviation 2 | 3 | **Problem from LeetCode** 4 | 5 | Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation. 6 | 7 | A string such as "word" contains only the following valid abbreviations: 8 | 9 | ```java 10 | ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 11 | ``` 12 | 13 | Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word". 14 | 15 | **Note**: Assume s contains only lowercase letters and abbr contains only lowercase letters and digits. 16 | 17 | ### Example: 18 | **Input** : 19 | 20 | ``` java 21 | s = "internationalization"; 22 | abbr = "i12iz4n" 23 | ``` 24 | 25 | **Output:** : 26 | 27 | ``` java 28 | true 29 | ``` 30 | 31 | **Input** : 32 | 33 | ``` java 34 | s = "apple"; 35 | abbr = "a2e"; 36 | ``` 37 | 38 | **Output:** : 39 | 40 | ``` java 41 | false 42 | ``` 43 | -------------------------------------------------------------------------------- /Practice Problems/Strings/Valid Word Abbreviation/ValidWordAbbreviation.java: -------------------------------------------------------------------------------- 1 | class ValidWordAbbreviation { 2 | public static void main(String[] args) { 3 | String s = "internationalization", abbr = "i12iz4n"; 4 | 5 | System.out.println(validWordAbbreviation(s,abbr)); 6 | 7 | } 8 | 9 | public static boolean validWordAbbreviation(String word, String abbr) { 10 | int pos = 0; 11 | int i = 0; 12 | int num = 0; 13 | 14 | while(i= word.length()){ 34 | return false; 35 | } 36 | if(abbr.charAt(i) != word.charAt(pos)){ 37 | return false; 38 | } 39 | pos++; 40 | i++; 41 | } 42 | } 43 | return pos == word.length(); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /Practice Problems/Strings/ZigZag Conversion /README.md: -------------------------------------------------------------------------------- 1 | # ZigZag Conversion 2 | 3 | **Problem from LeetCode** 4 | 5 | The string `PAYPALISHIRING` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 6 | ``` 7 | P A H N 8 | A P L S I I G 9 | Y I R 10 | ``` 11 | 12 | And then read line by line: `PAHNAPLSIIGYIR` 13 | 14 | Write the code that will take a string and make this conversion given a number of rows: 15 | 16 | ### Example: 17 | **Input** : 18 | ```java 19 | s = "PAYPALISHIRING", numRows = 4 20 | ``` 21 | 22 | **Output** : 23 | ```java 24 | PINALSIGYAHRPI 25 | ``` 26 | 27 | **Explanation** : 28 | 29 | ``` 30 | P I N 31 | A L S I G 32 | Y A H R 33 | P I 34 | ``` -------------------------------------------------------------------------------- /Practice Problems/Strings/ZigZag Conversion /ZigZagConversion.java: -------------------------------------------------------------------------------- 1 | class ZigZagConversion { 2 | public static String convert(String s, int numRows) { 3 | StringBuffer[] sb = new StringBuffer[numRows]; 4 | 5 | for(int i = 0; i< numRows; i++) { 6 | sb[i] = new StringBuffer(); 7 | } 8 | 9 | int len = s.length(); 10 | 11 | int i = 0; 12 | 13 | while(i < len) { 14 | for(int j =0; j 0 && i