├── 1 Intro └── notes.txt ├── 10 Sorting ├── 1 2 Duplicates.java ├── 10 3Sum.java ├── 16 17 sort colors.java ├── 27 Merge sort LL.java ├── 28 QuicksortLinkedlist ├── 3 4 5 Most Frequent.java ├── 33 Merge sorted array.java ├── 34 35 36 Nuts and bolts.java ├── 38 Remove Duplicates from Sorted Array.java ├── 39 40 Wiggle sort.java ├── 9 2Sum.java ├── Notes.txt ├── Treesort.java ├── bubblesort.java ├── countingsort.java ├── heapsort.java ├── insertionsort.java ├── mergesort.java ├── quicksort.java └── selectionsort.java ├── 11 Searching ├── 1 2 3 Duplicates.java ├── 13 14 15 16 17 Missingnumber.java ├── 18 24 25 26 Odd.java ├── 27 28 29 30 31 2Sum.java ├── 32 33 SumClosestZero.java ├── 34 35 36 37 38 3Sum.java ├── 39 40 41 45 46 MaxinBitonic.java ├── 4 19 20 21 22 23 findDuplicates.java ├── 42 43 44 Search in a rotated sorted array.java ├── 49 FirstOccurence ├── 5 6 7 8 FrequentElement.java ├── 50 Last Occurence ├── 53 No of occurences ├── 54 Count and Say ├── 57 58 59 60 61 Majority Element.java ├── 65 LocalMinimum.java ├── 66 Search a matrix ├── 70 EvenAndOdd.java ├── 74 MaxDifferenceLargerFirst.java ├── 79 Max_j_i.java ├── 81 PairwiseSorted.java ├── 9 10 11 12 FirstRepeat.java ├── BinarySearch.java ├── InterpolationSearch.java ├── LinearSearch.java └── notes.txt ├── 12 Selection Algorithms ├── 15 16 MedianofTwoSortedArrays.java ├── Ksmallest.java ├── Median of Medians.java ├── Notes.txt └── kthlargestelementinanarray.java ├── 13 Symbol Tables └── notes.txt ├── 14 Hashing ├── Hash Table Implementation └── notes.txt ├── 15 String Algorithms ├── 10 Combinations ├── 11 RemoveAdjacentCharacters ├── 12 Minimum Window Substring ├── 13 Word Search ├── 15 Surrounded Regions ├── 16 Wildcard Matching ├── 17 Combinations ├── 18 Implement Trie ├── 2 Longest Common Substring ├── 3 Longest Palindromic Substring ├── 5 Reverse String ├── 8 Reverse Words in a String ├── 9 Permutations ├── KMP.java └── strStr() ├── 16 Algorithm Design Techniques └── notes.txt ├── 17 Greedy Algorithms ├── 1 2 3 MergeFiles.java ├── 11 CoinChange.java ├── 14 FractionalKnapsack.java ├── 17 19 CustomerCare.java ├── 18 printJobScheduling.java ├── 4 5 6 7 10 IntervalScheduling.java ├── 8 9 15 IntervalPartitioning.java ├── Huffman.java └── Notes.txt ├── 18 Divide and Conquer ├── 11 Find k.java ├── 12 A[i]=i.java ├── 13 14 15 Median of two sorted Arrays.java ├── 16 Get Highest Index.java ├── 18 19 Stock Price.java ├── 20 Unbreakable laptops.java ├── 21 Equal.java ├── 22 Valid Square.java ├── 23 Nuts and Bolts.java ├── 24 25 Closest pair of points.java ├── 25 Shuffle.java ├── 26PowerFunction.java ├── 27 Kadane.java ├── 27Skyline.java └── Notes.txt ├── 19 Dynamic Programming ├── 11 MaxSumSubarraycontinuous3 ├── 13 14 Catalan Numbers ├── 15 Matrix Chain Multiplication ├── 17 Integer KnapSack ├── 18 0-1 KnapSack ├── 19 Coin Change ├── 20 Longest Increasing Subsequnece ├── 23) Box stacking ├── 24 Building Bridges ├── 25 subsetSum.java ├── 26 27 Partition Equal Subset Sum ├── 28 booleanpar.java ├── 29 Floyd Warshall ├── 30 Optimal BST.java ├── 31 OptimalStrategy.java ├── 32 Tiling.java ├── 33 EditDistance.java ├── 34 LongestPalindromicSubsequence.java ├── 35 LongestPalindromicSubstring.java ├── 36 Distinct Subsequences.java ├── 37,38 Optimal Path ├── 39Maxsubmatrixwithall1s.java ├── 4 Maximum Subarray ├── 40Maxsumsubmatrix.java ├── 42 Perfect Squares ├── 43 Min Jumps ├── 43OptimalNumberofJumps.java ├── 45 Partition closest ├── 46 Circus Tower ├── 9 House Robber ├── LCS.java ├── Notes.txt ├── factorial.java └── fibonacci.java ├── 2 Recursion and BackTracking ├── Generate all n bits.java ├── GenerateKary.java ├── TowersOfHanoi.java ├── VerifySort.java └── notes.txt ├── 20 Complexity Cases └── notes.txt ├── 21 Misc ├── 1 Spiral matrix ├── 10 NegandPos.java ├── 12 Swap even and odd ├── 13 Equilibrium Index ├── 14 Plus One ├── 15 Count all set bits.java ├── 2 Shuffle cards ├── 3 Rotate Array ├── 5 StringSpaces.java ├── 7 Move spaces end.java ├── 8 Move Zeroes ├── Number of 1 bits.java ├── ReverseBits.java └── notes.txt ├── 3 LinkedLists ├── 1 Stack using LL.java ├── 12 LL Cycle 2.java ├── 17 Reverse LL.java ├── 18 19 20 21 22 23 24 Intersection of Two Linked Lists.java ├── 2 3 4 5 6 Find nth node from end.java ├── 25 26 27 28 Middle of a LL.java ├── 29 LL from End.java ├── 32 Merge 2 sorted lists.java ├── 34 Reverse Linked List in pairs.java ├── 39 Palindrome Linked List.java ├── 41 Reverse k LL.java ├── 44 Jospheus Circle(Nannaku Prematho sum) ├── 45 Copy List With Random Pointer ├── 50 Median in an infinite steram of integers.java ├── 54 Reorder List ├── 56 Insertion sort ├── 57 Rotate list ├── 58 Add two numbers ├── 59LessandGreaterthank ├── 60 Merge K sorted Lists ├── 66 Remove Duplicates O(n2) ├── 67RemoveDuplicatesinaLL.java ├── 68PrintEvenFirstandOddnext.java ├── 69CommonElementsofASortedList.java ├── 7 8 9 10 11 LL Cycle.java ├── Delete Node in a Linked list └── Notes.txt ├── 4 Stacks ├── 1 Valid Parentheses.java ├── 11 stackReversal.java ├── 12 Queue using Stacks.java ├── 13 Stack using Queues.java ├── 2 Postfix Conversion ├── 22 23 spanfinding.java ├── 24 25 largestrectangleinhistogram.java ├── 26 StackSorting.java ├── 27 Consecutive pairs.java ├── 28 Dynamic Stack.java ├── 28 RecursiveRemoval.java ├── 3 Catalan numbers.java ├── 4 postfixevaluation.java ├── 5 Infix Evaluation.java ├── 6 7 Minstack.java ├── 8 9 10 Stack Palindrome.java ├── ArrayImplementation.java ├── DynamicArrayImplementation.java ├── LinkedListImplementation.java └── Notes.txt ├── 5 Queues ├── 1 Queue Reversal.java ├── 10 reversefirstk.java ├── 2 Implementqueueswithstacks.java ├── 3 Implement Stack using Queues.java ├── 4 Maximum sum sliding window.java ├── 8 consecutivepairs.java ├── 9 interleavingnumbers.java ├── CircularArrayImplementation.java ├── DynamicCircularArray.java ├── LinkedListImplementation.java └── Notes.txt ├── 6 Trees ├── 1 2 Max element in a tree.java ├── 10 11 12 Height of a tree.java ├── 13 minimumdepth.java ├── 14 Deepest node.java ├── 15 Delete an element.java ├── 16 17 18 Leaves, Full and half nodes.java ├── 19 Structurally Identical ├── 20 Diameter.java ├── 21 Width.java ├── 22 Maxsum.java ├── 23 paths.java ├── 24 pathsum.java ├── 25 26 Sum.java ├── 27 Invert.java ├── 28 Mirror.java ├── 29 Preorder Inorder.java ├── 3 4 Search.java ├── 30 Inorder Postorder.java ├── 32 Print All Ancestors.java ├── 33 LCA.java ├── 34 Zigzag.java ├── 35 Vertical order traversal.java ├── 36 53 Unique bst.java ├── 37 Unique BST 2.java ├── 39 40 Right pointers.java ├── 5 Insert in a tree.java ├── 52 Shortest path between two nodes in a bst.java ├── 54 LCA.java ├── 55 56 57 58 Validate BST.java ├── 59 bst to Circular DLL.java ├── 6 7 Size of a binary tree.java ├── 60 62 63 Convert sorted list to binary tree.java ├── 61 Convert sorted array to binary tree.java ├── 64 Kth smallest.java ├── 66 67 68 merge.java ├── 69 70 71 72 RangePrinter.java ├── 73 74 Same.java ├── 8 Delete a tree.java ├── 87 88 connect.java ├── 9 Level order Traversal.java ├── BST.java ├── InorderTraversal.java ├── LevelorderTraversal.java ├── Notes.txt ├── PostorderTraversal.java └── PreorderTraversal.java ├── 7 Priority Queues ├── 22 23 24 Merge K Sorted Lists.java ├── 27 Median in an infinite stream.java ├── Heap.java ├── Notes.txt └── Sliding Window Maximum.java ├── 8 Sets ├── Cycle.java ├── UnionFind.java └── notes.txt ├── 9 Graphs ├── BellmanFord.java ├── Kruskal.java ├── Prim.java ├── bfs_list.java ├── bfs_matrix.java ├── bfstopsort.java ├── dfs_list.java ├── dfs_matrix.java ├── dfstopsort.java ├── dijkstra_adj_list.java └── dijkstra_adj_matrix.java ├── CODE_OF_CONDUCT.md ├── LICENSE └── README.md /1 Intro/notes.txt: -------------------------------------------------------------------------------- 1 | Data Structure: A data structures is a way to store and organize data so that it can be used efficiently 2 | 2 types: Linear: Elements are accessed in a linear order and Non-Linear: Elements are stored and accessed in a non-linear order 3 | ADT: Declaration of data + Declaration of operations 4 | Algorithm: Sequnece of steps for solving a problem 5 | Master Theorem 6 | Subtraction and Conquer 7 | -------------------------------------------------------------------------------- /10 Sorting/1 2 Duplicates.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | //O(n2) and O(1) 3 | public boolean isDuplicates(int[] arr){ 4 | if(arr==null || arr.length==0) return false; 5 | for(int i=0;i set = new HashSet(); 28 | for(int a:arr) 29 | if(!set.add(a)) return true; 30 | return false; 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /10 Sorting/10 3Sum.java: -------------------------------------------------------------------------------- 1 | //Tc:O(n2) 2 | //Sc:O(1) 3 | class Solution { 4 | public List> threeSum(int[] nums) { 5 | List> result = new ArrayList(); 6 | if(nums==null || nums.length<3) return result; 7 | Arrays.sort(nums); 8 | for(int i=0;isum){ 21 | high--; 22 | } 23 | else 24 | low++; 25 | } 26 | } 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /10 Sorting/16 17 sort colors.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space solution 2 | class Solution { 3 | public void sortColors(int[] nums) { 4 | int a=0,b=0,c=0; 5 | for(int num:nums){ 6 | if(num==0) a++; 7 | else if(num==1) b++; 8 | else c++; 9 | } 10 | int index = 0; 11 | while(indexmax){ 15 | max = freq; 16 | ret = A[i]; 17 | } 18 | } 19 | return ret; 20 | } 21 | 22 | //O(nlogn) and O(1) 23 | public static int mostFrequent2(int[] A){ 24 | Arrays.sort(A); 25 | int n = A.length; 26 | int freq = 1, max = 0, ret = A[0]; 27 | for(int i=1;imax){ 33 | max = freq; 34 | ret = A[i-1]; 35 | } 36 | } 37 | } 38 | if(freq>max) return A[n-1]; 39 | return ret; 40 | } 41 | 42 | 43 | //O(n) and O(n) 44 | public static int mostFrequent3(int[] A){ 45 | Map map = new HashMap<>(); 46 | for(int a:A) map.put(a, map.getOrDefault(a,0)+1); 47 | int max = 0, ret = 0; 48 | for(int key:map.keySet()){ 49 | int value = map.get(key); 50 | if(value>max){ 51 | max = value; 52 | ret =key; 53 | } 54 | } 55 | return ret; 56 | } 57 | 58 | public static void main(String[] args) { 59 | int[] arr = {1, 3, 3, 1, 3, 4, 1, 3}; 60 | System.out.println(mostFrequent1(arr)); 61 | System.out.println(mostFrequent2(arr)); 62 | System.out.println(mostFrequent3(arr)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /10 Sorting/33 Merge sorted array.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | class Solution { 3 | public void merge(int[] nums1, int m, int[] nums2, int n) { 4 | int i=m-1,j=n-1,k=m+n-1; 5 | while(j>=0 && i>=0){ 6 | nums1[k--] = (nums1[i]>nums2[j])?nums1[i--]:nums2[j--]; 7 | } 8 | while(j>=0) 9 | nums1[k--] = nums2[j--]; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /10 Sorting/34 35 36 Nuts and bolts.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class NutsandBolts { 4 | 5 | //O(nlogn) time and space 6 | public static void match(char[] nuts, char[] bolts, int low, int high){ 7 | if(low0 && nums[i]==nums[i-1]) continue; 9 | nums[index++] = nums[i]; 10 | } 11 | return index; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /10 Sorting/39 40 Wiggle sort.java: -------------------------------------------------------------------------------- 1 | //O(n) and O(1) 2 | class Solution { 3 | public void wiggleSort(int[] nums) { 4 | boolean less = true; 5 | for (int i = 0; i < nums.length - 1; i++) { 6 | if (less) { 7 | if (nums[i] > nums[i + 1]) { 8 | swap(nums, i, i + 1); 9 | } 10 | } else { 11 | if (nums[i] < nums[i + 1]) { 12 | swap(nums, i, i + 1); 13 | } 14 | } 15 | less = !less; 16 | } 17 | } 18 | public void swap(int[] A, int i, int j){ 19 | int temp = A[i]; 20 | A[i] = A[j]; 21 | A[j] = temp; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /10 Sorting/9 2Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public boolean isSum(int[] a, int k) 4 | { 5 | Arrays.sort(a); 6 | int n = a.length; 7 | int low = 0, high = n-1; 8 | while(low=0;pass--){ 11 | for(int i=0;i<=pass;i++){ 12 | if(A[i]>A[pass]) 13 | swap(A,i,pass); 14 | } 15 | } 16 | } 17 | 18 | public static void swap(int[] A, int a, int b){ 19 | int temp = A[a]; 20 | A[a] = A[b]; 21 | A[b] = temp; 22 | } 23 | 24 | public static void main(String[] args){ 25 | Scanner in = new Scanner(System.in); 26 | System.out.println("Kindly enter the length of the array you want to sort"); 27 | int length = in.nextInt(); 28 | int[] array = new int[length]; 29 | System.out.println("Kindly enter the contents of the array"); 30 | for(int i=0;i=0;j--){ 16 | B[buckets[A[j]]] = A[j]; 17 | buckets[A[j]]--; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /10 Sorting/insertionsort.java: -------------------------------------------------------------------------------- 1 | //TC:O(n2) 2 | //SC:O(1) 3 | package sorting; 4 | import java.util.Scanner; 5 | 6 | public class insertionsort { 7 | 8 | public void insertionsort(int[] A){ 9 | int i=0,j=0; 10 | for(i=1;i0&&A[j-1]>key){ 14 | A[j] = A[j-1]; 15 | j--; 16 | } 17 | A[j] = key; 18 | } 19 | } 20 | 21 | public static void main(String[] args){ 22 | Scanner in = new Scanner(System.in); 23 | System.out.println("Kindly enter the length of the array you want to sort"); 24 | int length = in.nextInt(); 25 | int[] array = new int[length]; 26 | System.out.println("Kindly enter the contents of the array"); 27 | for(int i=0;i set = new HashSet(); 29 | for(int a:arr) 30 | if(!set.add(a)) return true; 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /11 Searching/13 14 15 16 17 Missingnumber.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | class Solution { 3 | public int missingNumber(int[] nums) { 4 | int n = nums.length; 5 | int sum = (n)*(n+1)/2; 6 | for(int num:nums) 7 | sum-=num; 8 | return sum; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /11 Searching/18 24 25 26 Odd.java: -------------------------------------------------------------------------------- 1 | //O(n) and O(1) 2 | public class Solution{ 3 | public int odd(int[] nums){ 4 | int x = 0; 5 | for(int n:nums) x^=n; 6 | return x; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /11 Searching/27 28 29 30 31 2Sum.java: -------------------------------------------------------------------------------- 1 | //O(n) time and Space 2 | class Solution { 3 | public int[] twoSum(int[] nums, int target) { 4 | if(nums==null || nums.length<2) return new int[2]; 5 | Map map = new HashMap(); 6 | int[] result = new int[2]; 7 | for(int i=0;i0){ 16 | min = Math.min(min, sum); 17 | high--; 18 | } 19 | else{ 20 | max = Math.max(sum,max); 21 | low++; 22 | } 23 | } 24 | return Math.min(Math.abs(max), min); 25 | } 26 | 27 | public static void main(String[] args) { 28 | int[] arr = {1, 60, -10, 70, -80, 85}; 29 | System.out.println(method(arr)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /11 Searching/34 35 36 37 38 3Sum.java: -------------------------------------------------------------------------------- 1 | //Tc:O(n2) 2 | //Sc:O(1) 3 | class Solution { 4 | public List> threeSum(int[] nums) { 5 | List> result = new ArrayList(); 6 | if(nums==null || nums.length<3) return result; 7 | Arrays.sort(nums); 8 | for(int i=0;isum){ 21 | high--; 22 | } 23 | else 24 | low++; 25 | } 26 | } 27 | } 28 | return result; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /11 Searching/39 40 41 45 46 MaxinBitonic.java: -------------------------------------------------------------------------------- 1 | package SearchingAlgorithms; 2 | 3 | public class MaxinBitonic { 4 | 5 | //O(logn) and O(1) 6 | public static int findMaximum(int[] arr){ 7 | int n = arr.length; 8 | if(arr.length==1) return arr[0]; 9 | if(arr.length==2) return Math.max(arr[0], arr[1]); 10 | int low = 0, high = n-1; 11 | while(lowarr[mid-1] && arr[mid]>arr[mid+1]) return arr[mid]; 14 | else if(arr[mid]>arr[mid-1] && arr[mid+1]>arr[mid]) low = mid+1; 15 | else high = mid-1; 16 | } 17 | return arr[high]; 18 | } 19 | 20 | public static void main (String[] args) 21 | { 22 | int arr[] = {1, 3, 50, 10, 9, 7, 6}; 23 | System.out.println("The maximum element is "+ 24 | findMaximum(arr)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /11 Searching/4 19 20 21 22 23 findDuplicates.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | class Solution { 3 | public List findDuplicates(int[] nums) { 4 | List list = new ArrayList(); 5 | if(nums==null || nums.length<2) return list; 6 | for(int i=0;inums[high]) 9 | low = mid+1; 10 | else high = mid; 11 | } 12 | //Now low and high has the same value which is equal to the index of the smallest element in the array 13 | int rot = low; 14 | low=0; 15 | high = nums.length-1; 16 | while(low<=high){ 17 | int mid = low+(high-low)/2; 18 | int realmid = (mid+rot)%nums.length; 19 | if(nums[realmid]==target) return realmid; 20 | else if(nums[realmid]>target) high = mid-1; 21 | else low = mid+1; 22 | } 23 | return -1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /11 Searching/49 FirstOccurence: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int getStart(int[] nums, int target){ 4 | int low = 0, high = nums.length-1; 5 | while(low<=high){ 6 | int mid = low+(high-low)/2; 7 | if(((mid==low) && (nums[mid]==target)) || ((nums[mid]==target)&&(nums[mid]!=nums[mid-1]))) 8 | return mid; 9 | else if(nums[mid]>=target) 10 | high = mid-1; 11 | else 12 | low = mid+1; 13 | } 14 | return -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /11 Searching/50 Last Occurence: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int getEnd(int[] nums, int target){ 4 | int low = 0, high = nums.length-1; 5 | while(low<=high){ 6 | int mid = low+(high-low)/2; 7 | if(((mid==high) && (nums[mid]==target)) || ((nums[mid]==target)&&(nums[mid]!=nums[mid+1]))) 8 | return mid; 9 | else if(nums[mid]<=target) 10 | low = mid+1; 11 | else 12 | high = mid-1; 13 | } 14 | return -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /11 Searching/53 No of occurences: -------------------------------------------------------------------------------- 1 | //O(logn) time and O(1) space 2 | class Solution { 3 | public int searchRange(int[] nums, int target) { 4 | int[] result = new int[2]; 5 | result[0] = getStart(nums, target); 6 | result[1] = getEnd(nums, target); 7 | return result[1]-result[0]+1; 8 | } 9 | 10 | public int getStart(int[] nums, int target){ 11 | int low = 0, high = nums.length-1; 12 | while(low<=high){ 13 | int mid = low+(high-low)/2; 14 | if(((mid==low) && (nums[mid]==target)) || ((nums[mid]==target)&&(nums[mid]!=nums[mid-1]))) 15 | return mid; 16 | else if(nums[mid]>=target) 17 | high = mid-1; 18 | else 19 | low = mid+1; 20 | } 21 | return -1; 22 | } 23 | 24 | public int getEnd(int[] nums, int target){ 25 | int low = 0, high = nums.length-1; 26 | while(low<=high){ 27 | int mid = low+(high-low)/2; 28 | if(((mid==high) && (nums[mid]==target)) || ((nums[mid]==target)&&(nums[mid]!=nums[mid+1]))) 29 | return mid; 30 | else if(nums[mid]<=target) 31 | low = mid+1; 32 | else 33 | high = mid-1; 34 | } 35 | return -1; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /11 Searching/54 Count and Say: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public String countAndSay(int n) { 4 | if(n<=0) return new String(); 5 | StringBuffer cur = new StringBuffer("1"); 6 | StringBuffer prev = new StringBuffer(); 7 | char say = '1'; 8 | int count = 0; 9 | for(int i=1;i0 && arr[mid]>arr[mid-1]) high = mid-1; 16 | else low = mid+1; 17 | } 18 | return -1; 19 | } 20 | 21 | public static void main(String[] args){ 22 | Scanner in = new Scanner(System.in); 23 | LocalMinimum s = new LocalMinimum(); 24 | System.out.println("Please enter the length of the array"); 25 | int n = in.nextInt(); 26 | System.out.println("Please enter the contents of the array"); 27 | int[] arr = new int[n]; 28 | for(int i=0;i=0){ 9 | if(matrix[rs][cs]==target) return true; 10 | else if(matrix[rs][cs]>target) cs--; 11 | else rs++; 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /11 Searching/70 EvenAndOdd.java: -------------------------------------------------------------------------------- 1 | package SearchingAlgorithms; 2 | 3 | import java.util.*; 4 | 5 | //Given an array of numbers 6 | //Place all the even numbers before odd numbers 7 | //Preserve the order 8 | public class EvenAndOdd { 9 | 10 | //O(n) and O(1) 11 | public void method(int[] arr){ 12 | if(arr==null || arr.length<2) return; 13 | int n = arr.length; 14 | int odd = 0; 15 | for(int i=0;i A[i] 5 | //If there are no such indices return -1; 6 | public class Max_j_i { 7 | //O(n) and O(n) 8 | private int method(int[] arr){ 9 | if(arr==null || arr.length<2) return -1; 10 | int maxdiff = -1; 11 | int n = arr.length; 12 | //Stores less than or equal to the given element on the left 13 | int[] left = new int[n]; 14 | //Stores greater than or equal to the given element on the right 15 | int[] right = new int[n]; 16 | int min = arr[0]; left[0] = min; 17 | for(int i=1;i=0;i--){ 23 | max = Math.max(max, arr[n-2]); 24 | right[i] = max; 25 | } 26 | int i=0,j=0; 27 | while(iarr[i+1]){ 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | 19 | public static void main(String[] args){ 20 | Scanner in = new Scanner(System.in); 21 | PairwiseSorted s = new PairwiseSorted(); 22 | System.out.println("Please enter the length of the array"); 23 | int n = in.nextInt(); 24 | System.out.println("Please enter the contents of the array"); 25 | int[] arr = new int[n]; 26 | for(int i=0;i map = new HashMap<>(); 22 | for(int n:nums) map.put(n, map.getOrDefault(n,0)+1); 23 | for(int n:nums) if(map.get(n)>1) return n; 24 | return -1; 25 | } 26 | 27 | public static void main(String[] args) { 28 | FirstRepeat f = new FirstRepeat(); 29 | Scanner in = new Scanner(System.in); 30 | System.out.println("Length of the array "); 31 | int n = in.nextInt(); 32 | System.out.println("Contents of the array "); 33 | int[] nums = new int[n]; 34 | for(int i=0;i=val){ 13 | if(arr[low]-arr[high]==0) return (low+high)/2; 14 | int mid = low + (val-arr[low])*(high-low)/(arr[high]-arr[low]); 15 | if(arr[mid]>val) high = mid-1; 16 | else if(arr[mid] A.length - 1) return B[bStart + k - 1]; 11 | if (bStart > B.length - 1) return A[aStart + k - 1]; 12 | if (k == 1) return Math.min(A[aStart], B[bStart]); 13 | 14 | int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE; 15 | if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; 16 | if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1]; 17 | 18 | if (aMid < bMid) 19 | return getkth(A, aStart + k/2, B, bStart, k - k/2);// Check: aRight + bLeft 20 | else 21 | return getkth(A, aStart, B, bStart + k/2, k - k/2);// Check: bRight + aLeft 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /12 Selection Algorithms/Notes.txt: -------------------------------------------------------------------------------- 1 | Selection Algorithms: Find the kth smallest/largest number in an array 2 | 1) You can sort and pick up the kth element in the array. This takes O(logn) for n operations 3 | 2) You can use partition based algorithms(Median of medians) 4 | The worst case time complexity is O(n) and space complexity is O(1) 5 | 6 | -------------------------------------------------------------------------------- /12 Selection Algorithms/kthlargestelementinanarray.java: -------------------------------------------------------------------------------- 1 | //O(nlogk) and O(k) 2 | class Solution { 3 | public int findKthLargest(int[] nums, int k) { 4 | int n = nums.length; 5 | k = n-k; 6 | int low = 0, high = nums.length-1; 7 | while(low combinations(String s){ 7 | List list = new ArrayList<>(); 8 | char[] ch = s.toCharArray(); 9 | Arrays.sort(ch); 10 | s = String.valueOf(ch); 11 | helper(list, new ArrayList<>(), s, 0); 12 | return list; 13 | } 14 | 15 | public void helper(List list, List sublist, String s, int start){ 16 | String result = ""; 17 | for(char c:sublist) result+=c; 18 | list.add(result); 19 | for(int i=start;i list){ 27 | for(String l: list){ 28 | System.out.println("["+l+"]"); 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | Combinations c = new Combinations(); 34 | String s = "abc"; 35 | List list = c.combinations(s); 36 | System.out.println("The possible combinations of the given string are "); 37 | c.display(list); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /15 String Algorithms/11 RemoveAdjacentCharacters: -------------------------------------------------------------------------------- 1 | package StringAlgorithms; 2 | import java.util.*; 3 | public class RemoveAdjacentCharacters { 4 | //O(n) time and space 5 | private String method(String s){ 6 | if(s==null || s.length()<2) return s; 7 | Stack stack = new Stack(); 8 | for(int i=0;i map = new HashMap<>(); 8 | for(char c: t.toCharArray()) 9 | { 10 | map.put(c,map.getOrDefault(c,0)+1); 11 | } 12 | int left=0,count=0,minlength=s.length()+1,minleft=0; 13 | for(int right=0;right=0) count++; 18 | } 19 | while(count==t.length()){ 20 | if(right-left+1 0) count --; 29 | } 30 | left++; 31 | } 32 | } 33 | return (minlength>s.length())?"":s.substring(minleft,minleft+minlength); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /15 String Algorithms/13 Word Search: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean exist(char[][] board, String word) { 3 | char[] w = word.toCharArray(); 4 | for (int y=0; yboard.length-1||j<0||j>board[0].length-1){ 29 | return; 30 | } 31 | if (board[i][j] == 'O') 32 | board[i][j] = '*'; 33 | if (i-1>=0 && board[i-1][j] == 'O') 34 | dfs(board, i-1, j); 35 | if (i+1< board.length && board[i+1][j] == 'O') 36 | dfs(board, i+1, j); 37 | if (j-1 >= 0 && board[i][j-1] == 'O') 38 | dfs(board, i, j-1); 39 | if (j+1 < board[i].length && board[i][j+1] == 'O' ) 40 | dfs(board, i, j+1); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /15 String Algorithms/16 Wildcard Matching: -------------------------------------------------------------------------------- 1 | //O(mn) time and space 2 | class Solution { 3 | public boolean isMatch(String s, String p) { 4 | int m = s.length(); 5 | int n = p.length(); 6 | boolean[][] dp = new boolean[m+1][n+1]; 7 | dp[0][0] = true; 8 | for(int i=1;i<=n;i++){ 9 | if(p.charAt(i-1)=='*') 10 | dp[0][i] = true; 11 | else 12 | break; 13 | } 14 | for(int i=1;i<=m;i++){ 15 | for(int j=1;j<=n;j++){ 16 | if(p.charAt(j-1)!='*'){ 17 | dp[i][j] = (dp[i-1][j-1])&& (s.charAt(i-1)==p.charAt(j-1) || p.charAt(j-1)=='?'); 18 | } 19 | else{ 20 | dp[i][j] = dp[i-1][j] || dp[i][j-1]; 21 | } 22 | } 23 | } 24 | return dp[m][n]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /15 String Algorithms/17 Combinations: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combine(int n, int k) { 3 | List> list = new ArrayList(); 4 | helper(list, new ArrayList<>(),1, n, k); 5 | return list; 6 | } 7 | public void helper(List> list, List sublist, int start, int n, int k){ 8 | if(k==0){ 9 | list.add(new ArrayList(sublist)); 10 | return; 11 | } 12 | for(int i=start;i<=n;i++){ 13 | sublist.add(i); 14 | helper(list,sublist,i+1,n,k-1); 15 | sublist.remove(sublist.size()-1); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /15 String Algorithms/18 Implement Trie: -------------------------------------------------------------------------------- 1 | public class Trie 2 | { 3 | public class TrieNode{ 4 | boolean isEnd; 5 | TrieNode[] children = new TrieNode[26]; 6 | public TrieNode(){ 7 | 8 | } 9 | public TrieNode(char ch){ 10 | TrieNode node = new TrieNode(); 11 | } 12 | } 13 | TrieNode root; 14 | public Trie(){ 15 | root = new TrieNode(); 16 | } 17 | /** Inserts a word into the trie. */ 18 | public void insert(String word) { 19 | TrieNode temp = root; 20 | for(int i=0;i=0;i--){ 9 | for(int j=i;j=0;i--){ 7 | sb.append(words[i]); 8 | if(i!=0) sb.append(" "); 9 | } 10 | return sb.toString(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /15 String Algorithms/9 Permutations: -------------------------------------------------------------------------------- 1 | package StringAlgorithms; 2 | 3 | import java.util.*; 4 | 5 | public class Permutations { 6 | 7 | public List permutations(String s){ 8 | List list = new ArrayList<>(); 9 | char[] ch = s.toCharArray(); 10 | Arrays.sort(ch); 11 | s = String.valueOf(ch); 12 | helper(list, new ArrayList<>(), s, new boolean[s.length()]); 13 | return list; 14 | } 15 | 16 | public void helper(List list, List sublist, String s, boolean[] visited){ 17 | if(sublist.size()==s.length()){ 18 | String result = ""; 19 | for(char c:sublist) result+=c; 20 | list.add(result); 21 | return; 22 | } 23 | for(int i=0;i0 && (s.charAt(i)==s.charAt(i-1)) && !visited[i-1]) ) continue; 25 | visited[i] = true; 26 | sublist.add(s.charAt(i)); 27 | helper(list, sublist, s, visited); 28 | visited[i] = false; 29 | sublist.remove(sublist.size()-1); 30 | } 31 | } 32 | 33 | public void display(List list){ 34 | for(String l: list){ 35 | System.out.println("["+l+"]"); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | Permutations p = new Permutations(); 41 | String s = "aaa"; 42 | List list = p.permutations(s); 43 | System.out.println("The possible permutations of the given string are "); 44 | p.display(list); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /15 String Algorithms/KMP.java: -------------------------------------------------------------------------------- 1 | public class kmp { 2 | static int[] table; 3 | public static void filltable(String s){ 4 | table = new int[s.length()]; 5 | int i=1, j=0; 6 | table[0] = 0; 7 | while(i0){ 14 | j = table[j-1]; 15 | } 16 | else{ 17 | table[i] = 0; 18 | i++; 19 | } 20 | } 21 | } 22 | public static int kmp(String text, String pattern){ 23 | filltable(pattern); 24 | int m = text.length(); 25 | int n = pattern.length(); 26 | int i =0, j =0; 27 | while(i0){ 36 | j = table[j-1]; 37 | } 38 | else{ 39 | i++; 40 | } 41 | } 42 | return -1; 43 | } 44 | public static void main(String[] args){ 45 | String text = "bacbabababacaca"; 46 | String pattern = "ababaca"; 47 | System.out.println(kmp(text,pattern)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /15 String Algorithms/strStr(): -------------------------------------------------------------------------------- 1 | //O(mn) and O(1) 2 | class Solution { 3 | public int strStr(String haystack, String needle) { 4 | for (int i = 0; ; i++) { 5 | for (int j = 0; ; j++) { 6 | if (j == needle.length()) return i; 7 | if (i + j == haystack.length()) return -1; 8 | if (needle.charAt(j) != haystack.charAt(i + j)) break; 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /16 Algorithm Design Techniques/notes.txt: -------------------------------------------------------------------------------- 1 | There are many algorithm design paradigms for solving problems. They can be classified as shown below: 2 | 3 | 1) Classification by Implementation: 4 | 5 | a) Recursion and Iteration 6 | b) Procedural or Non-procedural(We ask for something without implementing it) 7 | c) Serial or parallel or distributed 8 | d) Deterministic or Non-deterministic(guesses the best solution using heuristics) 9 | e) Exact or Approximate 10 | 11 | 2) Classification by Design Method 12 | a) Greedy 13 | b) DP 14 | c) DC 15 | d) Linear programming 16 | e) Reduction 17 | -------------------------------------------------------------------------------- /17 Greedy Algorithms/1 2 3 MergeFiles.java: -------------------------------------------------------------------------------- 1 | package Greedy; 2 | //Given an array 'A' where A[i] indicates the cost of merging the ith file, find the optimal 3 | //way to merge files 4 | import java.util.*; 5 | public class MergeFiles 6 | { 7 | //O(nlogn) time and O(n) space 8 | public int mergefiles(int[] arr){ 9 | if(arr==null || arr.length==0) return 0; 10 | int cost = 0; 11 | //O(nlogn) 12 | Arrays.sort(arr); 13 | //Declaration of a min prioirty queue 14 | PriorityQueue pq = new PriorityQueue(); 15 | //O(n) 16 | for(int i=0;i1){ 21 | int a = pq.poll(); //O(logn) 22 | int b = pq.poll(); //O(logn) 23 | int curcost = a+b; 24 | pq.offer(curcost); 25 | cost+=curcost; 26 | } 27 | return cost; 28 | } 29 | public static void main(String[] args) { 30 | int[] arr = {10,5,100,50,20,15}; 31 | MergeFiles m = new MergeFiles(); 32 | System.out.println("The optimal cost for merging the given array is "+m.mergefiles(arr)); 33 | } 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /17 Greedy Algorithms/11 CoinChange.java: -------------------------------------------------------------------------------- 1 | //O(n) space and O(nk) time 2 | class Solution { 3 | public int coinChange(int[] coins, int n) { 4 | int[] dp = new int[n+1]; 5 | for(int i=1;i<=n;i++){ 6 | dp[i] = n+1; 7 | for(int j=0;j=0){ 9 | dp[i] = Math.min(dp[i], 1+dp[i-coins[j]]); 10 | } 11 | } 12 | } 13 | return dp[n]>n?-1:dp[n]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /17 Greedy Algorithms/14 FractionalKnapsack.java: -------------------------------------------------------------------------------- 1 | package Greedy; 2 | import java.util.*; 3 | //Given an array of weights, values and the capacity of the knapsack 4 | //Imagine you are the thief with this knapsack and you can fill your knapsack 5 | //with any item until it's capacity, find the max amount you can rob 6 | public class FractionalKnapsack { 7 | //O(nlogn) time and O(n) space 8 | public int FractionalKnapsack(int[] v, int[] w, int c){ 9 | int[] f = new int[v.length]; 10 | for(int i=0;i=0) && (c>=0)){ 18 | int curweight = w[i]; 19 | //Take the entire item 20 | if(c-curweight>=0){ 21 | ret+=v[i]; 22 | c-=curweight; 23 | } 24 | else { 25 | int val = (v[i] / w[i]) * c; 26 | ret+=val; 27 | return ret; 28 | } 29 | i--; 30 | } 31 | return ret; 32 | } 33 | public static void main(String[] args) { 34 | FractionalKnapsack f = new FractionalKnapsack(); 35 | int[] values = {60,100,120}; 36 | int[] weights = {10,20,30}; 37 | int capacity = 50; 38 | System.out.println("The max amount is "+f.FractionalKnapsack(values,weights,capacity)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /17 Greedy Algorithms/17 19 CustomerCare.java: -------------------------------------------------------------------------------- 1 | package Greedy; 2 | import java.util.*; 3 | // 4 | ////A server serves customers who are in the queue, rearrange the customers 5 | ////such that the total waiting time of all the customers is minimised 6 | public class CustomerCare { 7 | public int method(int[] arr){ 8 | Arrays.sort(arr); 9 | int result = 0; 10 | int previouswaittime = 0; 11 | for(int i = 0;iK) r = mid-1; 26 | else l = mid+1; 27 | } 28 | return -1; 29 | } 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /18 Divide and Conquer/12 A[i]=i.java: -------------------------------------------------------------------------------- 1 | // Given a sorted array 2 | // Given k, find the index such that A[i] = i; 3 | //Algorithm: 4 | 5 | import java.util.*; 6 | public class Solution 7 | { 8 | public int fixedPoint(int[] nums){ 9 | return findIndex(nums,0,nums.length-1); 10 | } 11 | public int findIndex(int[] a, int l, int r){ 12 | if(l<=r){ 13 | int mid = (low+(high-low)/2); 14 | if(a[mid]==mid) return mid; 15 | else if(a[mid]>mid) 16 | return findIndex(a,low,mid-1); 17 | else 18 | return findIndex(a,mid+1,high); 19 | } 20 | return -1; 21 | } 22 | public static void main(String[] args){ 23 | Scanner in = new Scanner(System.in); 24 | System.out.println("Please enter the length of your array and then the contents of the array"); 25 | int n = in.nextInt(); 26 | int[] nums = new int[n]; 27 | for(int i=0;i nums1.length - 1) return nums2[start2 + k - 1]; 16 | if (start2 > nums2.length - 1) return nums1[start1 + k - 1]; 17 | if(k==1) return Math.min(nums1[start1],nums2[start2]); 18 | int mid1 = Integer.MAX_VALUE; 19 | int mid2 = Integer.MAX_VALUE; 20 | if (start1 + k / 2 - 1 < nums1.length) mid1 = nums1[start1 + k / 2 - 1]; 21 | if (start2 + k / 2 - 1 < nums2.length) mid2 = nums2[start2 + k / 2 - 1]; 22 | if (mid1 < mid2) return helper (nums1, start1 + k / 2, nums2, start2, k - k / 2); //nums1.right + nums2 23 | else return helper(nums1, start1, nums2, start2 + k / 2, k - k / 2); //nums1 + nums2.right 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /18 Divide and Conquer/16 Get Highest Index.java: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int getEnd(int[] nums, int target){ 4 | int low = 0, high = nums.length-1; 5 | while(low<=high){ 6 | int mid = low+(high-low)/2; 7 | if(((mid==high) && (nums[mid]==target)) || ((nums[mid]==target)&&(nums[mid]!=nums[mid+1]))) 8 | return mid; 9 | else if(nums[mid]<=target) 10 | low = mid+1; 11 | else 12 | high = mid-1; 13 | } 14 | return -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /18 Divide and Conquer/18 19 Stock Price.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public int maxProfit(int[] prices) { 4 | if(prices==null || prices.length==0) return 0; 5 | int[] dp = new int[prices.length-1]; 6 | for(int i=1;i0){ 12 | neg = true; 13 | break; 14 | } 15 | } 16 | if(!neg) return 0; 17 | return maxSubArray(dp); 18 | } 19 | public int maxSubArray(int[] nums) { 20 | //Sanity check 21 | if(nums==null || nums.length==0) return 0; 22 | int maxsofar = nums[0], maxendinghere = nums[0]; 23 | for(int i=1;i set = new HashSet(); 28 | for(int a:arr) 29 | if(!set.add(a)) return true; 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /18 Divide and Conquer/22 Valid Square.java: -------------------------------------------------------------------------------- 1 | //O(logn) time and O(1) space 2 | public class Solution { 3 | public boolean isPerfectSquare(int num) { 4 | if(num == 1) return true; 5 | long low = 1, high = num / 2, mid = 0; 6 | long nums = (long)num; 7 | while(low <= high) 8 | { 9 | mid = low + (high - low) / 2; 10 | if((mid * mid) == nums) return true; 11 | else if( (mid * mid) < nums) 12 | low = mid + 1; 13 | else 14 | high = mid - 1; 15 | } 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /18 Divide and Conquer/23 Nuts and Bolts.java: -------------------------------------------------------------------------------- 1 | package DivideandConquer; 2 | import java.util.*; 3 | 4 | public class NutsandBolts { 5 | 6 | //O(nlogn) time and space 7 | public static void match(char[] nuts, char[] bolts, int low, int high){ 8 | if(low0) return half*half*x; 8 | else return half*half/x; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /18 Divide and Conquer/27 Kadane.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Kadane(int[] a){ 3 | int maxendinghere = a[0], maxsofar = a[0]; 4 | for(int i=1;i getSkyline(int[][] buildings) { 3 | List result = new ArrayList(); 4 | List heights = new ArrayList(); 5 | for(int[] b: buildings){ 6 | heights.add(new int[] {b[0],-b[2]}); 7 | heights.add(new int[] {b[1],b[2]}); 8 | } 9 | Collections.sort(heights, (a,b)->{ 10 | if(a[0]!=b[0]) 11 | return a[0]-b[0]; 12 | return a[1]-b[1]; 13 | }); 14 | Queue pq = new PriorityQueue((a,b)->(b-a)); 15 | int prev = 0; 16 | pq.offer(0); 17 | for(int[] h:heights){ 18 | if(h[1]<0){ 19 | pq.offer(-h[1]); 20 | } 21 | else{ 22 | pq.remove(h[1]); 23 | } 24 | int cur = pq.peek(); 25 | if(prev!=cur){ 26 | prev = cur; 27 | result.add(new int[] {h[0],cur}); 28 | } 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /18 Divide and Conquer/Notes.txt: -------------------------------------------------------------------------------- 1 | Divide and conquer is an algorithmic paradigm. It consists of 3 steps: 2 | 3 | a) Divide: Divides the problem into subproblems 4 | b) Conquer: Recursively solves these subproblems. 5 | c) Combine: Combines the solution to these subproblems into solution to the original problem 6 | 7 | Learn Master Theorem 8 | 9 | Applications 10 | 1) Merge sort 11 | 2) Quick sort -------------------------------------------------------------------------------- /19 Dynamic Programming/11 MaxSumSubarraycontinuous3: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | import java.util.*; 3 | 4 | public class MaxSumSubarraycontinuous3 { 5 | 6 | //O(n) time and space 7 | public int method(int[] arr){ 8 | if(arr==null || arr.length==0) return 0; 9 | if(arr.length==1) return arr[0]; 10 | if(arr.length==2) return arr[0]+arr[1]; 11 | int n = arr.length; 12 | int[] dp = new int[n]; 13 | dp[0] = arr[0]; 14 | dp[1] = arr[1]+arr[0]; 15 | dp[2] = Math.max(dp[1], Math.max(arr[2]+dp[0],arr[2]+arr[1])); 16 | for(int i=3;i=0) && (c>=0)){ 18 | int curweight = w[i]; 19 | //Take the entire item 20 | if(c-curweight>=0){ 21 | ret+=v[i]; 22 | c-=curweight; 23 | } 24 | else { 25 | int val = (v[i] / w[i]) * c; 26 | ret+=val; 27 | return ret; 28 | } 29 | i--; 30 | } 31 | return ret; 32 | } 33 | public static void main(String[] args) { 34 | FractionalKnapsack f = new FractionalKnapsack(); 35 | int[] values = {60,100,120}; 36 | int[] weights = {10,20,30}; 37 | int capacity = 50; 38 | System.out.println("The max amount is "+f.FractionalKnapsack(values,weights,capacity)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /19 Dynamic Programming/18 0-1 KnapSack: -------------------------------------------------------------------------------- 1 | 2 | public class knapSack { 3 | public static int knapsack(int[] v, int[] w, int C){ 4 | int[][] K = new int[v.length+1][C+1]; 5 | for(int i=0;i<=v.length;i++){ 6 | for(int j=0;j<=C;j++){ 7 | if(i==0||j==0){ 8 | K[i][j] = 0; 9 | continue; 10 | } 11 | if(j-w[i-1]>=0){ 12 | K[i][j] = Math.max(K[i-1][j], K[i-1][j-w[i-1]]+v[i-1]); 13 | } 14 | else{ 15 | K[i][j] = K[i-1][j]; 16 | } 17 | } 18 | } 19 | return K[v.length][C]; 20 | } 21 | public static void main(String[] args){ 22 | int[] v = {60,100,120}; 23 | int[] w = {10,20,30}; 24 | int C = 50; 25 | System.out.println(knapsack(v,w,C)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /19 Dynamic Programming/19 Coin Change: -------------------------------------------------------------------------------- 1 | //O(n) space and O(nk) time 2 | class Solution { 3 | public int coinChange(int[] coins, int n) { 4 | int[] dp = new int[n+1]; 5 | for(int i=1;i<=n;i++){ 6 | dp[i] = n+1; 7 | for(int j=0;j=0){ 9 | dp[i] = Math.min(dp[i], 1+dp[i-coins[j]]); 10 | } 11 | } 12 | } 13 | return dp[n]>n?-1:dp[n]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /19 Dynamic Programming/20 Longest Increasing Subsequnece: -------------------------------------------------------------------------------- 1 | //O(n2) time and O(n) space 2 | class Solution { 3 | public int lengthOfLIS(int[] nums) { 4 | //Sanity Check 5 | if(nums==null || nums.length==0) return 0; 6 | int[] dp = new int[nums.length]; 7 | for(int i=0;inums[j]){ 11 | dp[i] = Math.max(dp[i],dp[j]+1); 12 | } 13 | } 14 | } 15 | int max = 0; 16 | for(int num:dp){ 17 | System.out.println(num); 18 | max = Math.max(max,num); 19 | } 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /19 Dynamic Programming/25 subsetSum.java: -------------------------------------------------------------------------------- 1 | public class subsetsum { 2 | public static boolean subsetsum(int[] array, int n, int sum){ 3 | boolean[][] dp = new boolean[n+1][sum+1]; 4 | for(int i=0;i<=sum;i++) 5 | dp[0][i] = false; 6 | for(int i=0;i<=n;i++) 7 | dp[i][0] = true; 8 | for(int i=1;i<=n;i++){ 9 | for(int j=1;j<=sum;j++){ 10 | dp[i][j] = dp[i-1][j]; 11 | if(j-array[i-1]>=0) 12 | dp[i][j] = dp[i-1][j] || (dp[i-1][j-array[i-1]]); 13 | } 14 | } 15 | return dp[n][sum]; 16 | } 17 | 18 | public static void main(String[] args){ 19 | int set[] = {3, 34, 4, 12, 5, 2}; 20 | int sum = 9; 21 | int n = set.length; 22 | if (subsetsum(set, n, sum) == true) 23 | System.out.println("Found a subset with given sum"); 24 | else 25 | System.out.println("No subset with given sum"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /19 Dynamic Programming/26 27 Partition Equal Subset Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canPartition(int[] nums) { 3 | //Sanity check 4 | if(nums==null || nums.length==0) return false; 5 | int n = nums.length; 6 | int sum = 0; 7 | for(int num:nums) 8 | sum+=num; 9 | if((sum&1)==1) return false; 10 | sum/=2; 11 | //0-1 Knapsack problem 12 | boolean[][] dp = new boolean[n+1][sum+1]; 13 | for (int i=0;i<=n;i++) dp[i][0] = true; 14 | for(int i=1;i<=n;i++){ 15 | for(int j=1;j<=sum;j++){ 16 | dp[i][j] = dp[i-1][j]; 17 | if (j >= nums[i-1]){ 18 | dp[i][j] = (dp[i][j] || dp[i-1][j-nums[i-1]]); 19 | } 20 | } 21 | } 22 | return dp[n][sum]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /19 Dynamic Programming/30 Optimal BST.java: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | public class Optimal_BST { 4 | 5 | //O(n3) time and O(n2) space 6 | public static int optimalSearchTree(int[] arr){ 7 | if(arr==null || arr.length==0) return 0; 8 | int n = arr.length; 9 | int[][] cost = new int[n+1][n+1]; 10 | for(int i=0;i= freq.length) 29 | continue; 30 | s += freq[k]; 31 | } 32 | return s; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int freq[] = {34, 8, 50}; 37 | System.out.println("Cost of Optimal BST is " + 38 | optimalSearchTree(freq)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /19 Dynamic Programming/31 OptimalStrategy.java: -------------------------------------------------------------------------------- 1 | //O(n2) time and space solution 2 | public class Solution 3 | { 4 | public int OptimalStrategy(int[] array) 5 | { 6 | int n = array.length; 7 | int[][] dp = new int[n][n]; 8 | for(int k=0;k=0;i--){ 9 | dp[i][i] = 1; 10 | for(int j = i+1;j=0;i--){ 10 | for(int j=i;j list = new ArrayList(); 6 | for(int i=1;i*i<=n;i++) 7 | list.add(i*i); 8 | int[] coins = new int[list.size()]; 9 | for(int i=0;in)?-1:dp[n]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /19 Dynamic Programming/43 Min Jumps: -------------------------------------------------------------------------------- 1 | package DynamicProgramming; 2 | 3 | import java.util.Scanner; 4 | 5 | public class MinJumps { 6 | //O(n) and O(1) 7 | public int minjumps(int[] arr){ 8 | int n = arr.length; 9 | int curfar = 0, curmax = 0, jumps = 0; 10 | for(int i=0;i=0){ 17 | dp[i][j] = dp[i-1][j] || dp[i-1][j-arr[i-1]]; 18 | } 19 | else 20 | dp[i][j] = dp[i-1][j]; 21 | } 22 | } 23 | int min = Integer.MAX_VALUE; 24 | for(int j = sum/2; j>=0; j--){ 25 | if(dp[n][j]==true){ 26 | min = Math.min(min, sum-2*j); 27 | break; 28 | } 29 | } 30 | return min; 31 | } 32 | 33 | public static void main(String[] args){ 34 | Scanner in = new Scanner(System.in); 35 | MinDiffernce s = new MinDiffernce(); 36 | System.out.println("Please enter the length of the array"); 37 | int n = in.nextInt(); 38 | System.out.println("Please enter the contents of the array"); 39 | int[] arr = new int[n]; 40 | for(int i=0;i(){ 8 | public int compare(int[] o1, int[] o2){ 9 | if(o1[0]!=o2[0]) 10 | return o1[0]-o2[0]; 11 | else 12 | return o2[1]-o1[1]; 13 | } 14 | }); 15 | int[] dp = new int[m]; 16 | int res = 0; 17 | for(int i=0;ienvelopes[j][0])&&(envelopes[i][1]>envelopes[j][1])) 21 | dp[i] = Math.max(dp[i],1+dp[j]); 22 | } 23 | res = Math.max(dp[i],res); 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /19 Dynamic Programming/9 House Robber: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public int rob(int[] nums) { 4 | if(nums==null || nums.length==0) return 0; 5 | if(nums.length==1) return nums[0]; 6 | if(nums.length==2) return Math.max(nums[0],nums[1]); 7 | int n = nums.length; 8 | int[] dp = new int[n]; 9 | dp[0] = nums[0]; 10 | dp[1] = Math.max(nums[0], nums[1]); 11 | for(int i=2;i list, StringBuilder s, int n){ 5 | if(n<1){ 6 | list.add(new String(s)); 7 | return; 8 | } 9 | s.append(0); 10 | generate(list,s,n-1); 11 | s.deleteCharAt(s.length()-1); 12 | s.append(1); 13 | generate(list,s,n-1); 14 | s.deleteCharAt(s.length()-1); 15 | } 16 | 17 | public static void display(List list){ 18 | for(int i=0;i list = new ArrayList(); 25 | generate(list,new StringBuilder(),n); 26 | display(list); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2 Recursion and BackTracking/GenerateKary.java: -------------------------------------------------------------------------------- 1 | package RecursionandBackTracking; 2 | import java.util.*; 3 | 4 | public class GenerateKary { 5 | public static void helper(List list, StringBuilder s, char[] ch, int n, int k){ 6 | if(s.length()==k){ 7 | list.add(new String(s)); 8 | return; 9 | } 10 | for(int i=0;i list){ 18 | for(int i=0;i list = new ArrayList(); 28 | helper(list, new StringBuilder(), ch, n, k); 29 | display(list); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /2 Recursion and BackTracking/TowersOfHanoi.java: -------------------------------------------------------------------------------- 1 | package RecursionandBackTracking; 2 | 3 | public class TowersOfHanoi { 4 | //O(2pown) time and space 5 | public static void towers(int n, char frompeg, char topeg, char auxpeg){ 6 | //Base case 7 | if(n==1){ 8 | System.out.println("Move disk 1 from "+frompeg+" to "+topeg); 9 | return; 10 | } 11 | towers(n-1, frompeg,auxpeg,topeg); 12 | System.out.println("Move disk "+n+" from "+frompeg+" to "+topeg); 13 | towers(n-1,auxpeg,topeg,frompeg); 14 | } 15 | public static void main(String[] args) { 16 | towers(4, 'A', 'B', 'C'); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /2 Recursion and BackTracking/VerifySort.java: -------------------------------------------------------------------------------- 1 | package RecursionandBackTracking; 2 | 3 | public class VerifySort { 4 | 5 | private static boolean helper(int[] arr, int n){ 6 | if(n==1) return true; 7 | return (arr[n-1] spiralOrder(int[][] matrix) { 4 | List list = new ArrayList(); 5 | if(matrix==null || matrix.length==0) return list; 6 | int row = matrix.length; 7 | int col = matrix[0].length; 8 | int rs=0,re=row-1,cs=0,ce=col-1; 9 | while(rs<=re && cs<=ce){ 10 | //Move right 11 | for(int i=cs;i<=ce;i++){ 12 | list.add(matrix[rs][i]); 13 | } 14 | rs++; 15 | //Move Down 16 | for(int i=rs;i<=re;i++){ 17 | list.add(matrix[i][ce]); 18 | } 19 | ce--; 20 | //Move left 21 | if(rs<=re&&cs<=ce){ 22 | for(int i=ce;i>=cs;i--){ 23 | list.add(matrix[re][i]); 24 | } 25 | re--; 26 | } 27 | //Move up 28 | if(rs<=re&&cs<=ce){ 29 | for(int i=re;i>=rs;i--){ 30 | list.add(matrix[i][cs]); 31 | } 32 | cs++; 33 | } 34 | } 35 | return list; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /21 Misc/10 NegandPos.java: -------------------------------------------------------------------------------- 1 | package Misc; 2 | 3 | public class SeparateNegandPos { 4 | 5 | public static void helper(int[] arr){ 6 | int n = arr.length; 7 | int i = 0; 8 | for(int j=0;j>(1&mask2)); 5 | } 6 | -------------------------------------------------------------------------------- /21 Misc/13 Equilibrium Index: -------------------------------------------------------------------------------- 1 | public int equi(int[] A){ 2 | int sum =0, leftsum = 0; 3 | for(int a:A) 4 | sum+=a; 5 | for(int i=0;i=0;i--){ 6 | if(digits[i]<9){ 7 | digits[i]++; 8 | return digits; 9 | } 10 | digits[i]=0; 11 | } 12 | int[] ret = new int[n+1]; 13 | ret[0] = 1; 14 | return ret; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /21 Misc/15 Count all set bits.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | public int hammingWeight(int n) { 3 | int count = 0; 4 | for(int i=0;i<32;i++){ 5 | if((n&1)==1) 6 | count++; 7 | n>>>=1; 8 | } 9 | return count; 10 | } 11 | public int helper(int n) 12 | { 13 | int result = 0; 14 | for(int i=0;i<=n;i++){ 15 | result += hammingWeight(i); 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /21 Misc/2 Shuffle cards: -------------------------------------------------------------------------------- 1 | //O(n) and O(1) solution 2 | public void shuffle(int[] cards) 3 | { 4 | int n = cards.length; //m=52; 5 | for(int i=0;i=0;j--){ 10 | char c = s.charAt(j); 11 | if(c!=' '){ 12 | swap(ch, i--,j); 13 | } 14 | } 15 | return String.valueOf(ch); 16 | } 17 | 18 | public static void swap(char[] ch, int i, int j){ 19 | char temp = ch[i]; 20 | ch[i] = ch[j]; 21 | ch[j] = temp; 22 | } 23 | 24 | public static void main(String[] args) { 25 | String s = "move these spaces to the beginning"; 26 | System.out.println(helper(s)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /21 Misc/7 Move spaces end.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class movespaces { 4 | public static String move(String s){ 5 | int index = 0; 6 | char[] ch = s.toCharArray(); 7 | for(int i=0;i>>=1; 9 | } 10 | return count; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /21 Misc/ReverseBits.java: -------------------------------------------------------------------------------- 1 | //O(n) and O(1) 2 | public class Solution { 3 | public int reverseBits(int n) { 4 | int result = 0; 5 | for(int i=0;i<32;i++){ 6 | result += n&1; 7 | n>>>=1; 8 | if(i<31) 9 | result<<=1; 10 | } 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /21 Misc/notes.txt: -------------------------------------------------------------------------------- 1 | Bitwise Operations: &,|,~,^,<<,>> 2 | 1) Check whether kth bit is set or not: n&(1<>k = n/2powk 12 | 9) Finding modulo of a number: (n%32) = n&(0x1F) 13 | n%8 = n&(0x7) 14 | 10) Creating mask for Trailing zeroes: n&(-n)-1; 15 | -------------------------------------------------------------------------------- /3 LinkedLists/1 Stack using LL.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.*; 3 | 4 | public class LinkedListImplementation { 5 | ListNode head; 6 | int size; 7 | public static class ListNode{ 8 | int val; 9 | ListNode next; 10 | public ListNode(){ 11 | this.next = null; 12 | } 13 | public ListNode(int val){ 14 | this.val = val; 15 | this.next = null; 16 | } 17 | } 18 | 19 | public LinkedListImplementation(){ 20 | head = new ListNode(); 21 | size = 0; 22 | } 23 | 24 | //O(1) 25 | //Insert at the beginning in a singly linked list 26 | public void push(int x){ 27 | size++; 28 | ListNode newnode = new ListNode(x); 29 | newnode.next = head; 30 | head = newnode; 31 | System.out.println(x+" is pushed onto the stack"); 32 | } 33 | 34 | 35 | //O(1) 36 | //Delete from beginning of a linked list 37 | public int pop(){ 38 | int ret = head.val; 39 | //Delete head 40 | head = head.next; 41 | size--; 42 | System.out.println(ret+"is popped from the stack"); 43 | return ret; 44 | } 45 | 46 | public int peek(){ 47 | return head.val; 48 | } 49 | 50 | public boolean isEmpty(){ 51 | return (size==0); 52 | } 53 | 54 | public int size(){ 55 | return size; 56 | } 57 | 58 | public static void main(String[] args) { 59 | LinkedListImplementation l = new LinkedListImplementation(); 60 | l.push(4); 61 | l.push(5); 62 | System.out.println(l.peek()); 63 | System.out.println(l.pop()); 64 | System.out.println(l.size()); 65 | System.out.println(l.isEmpty()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /3 LinkedLists/12 LL Cycle 2.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | public class Solution { 3 | public ListNode detectCycle(ListNode head) { 4 | ListNode slow = head, fast = head; 5 | while(fast!=null && fast.next!=null){ 6 | slow = slow.next; 7 | fast = fast.next.next; 8 | if(slow==fast){ 9 | fast = head; 10 | while(slow!=fast){ 11 | slow = slow.next; 12 | fast = fast.next; 13 | } 14 | return slow; 15 | } 16 | } 17 | return null; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /3 LinkedLists/17 Reverse LL.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | class Solution { 3 | public ListNode reverseList(ListNode head) { 4 | if(head==null || head.next==null) return head; 5 | ListNode cur = head, prev = null; 6 | while(cur!=null){ 7 | ListNode next = cur.next; 8 | cur.next = prev; 9 | prev = cur; 10 | cur = next; 11 | } 12 | return prev; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /3 LinkedLists/18 19 20 21 22 23 24 Intersection of Two Linked Lists.java: -------------------------------------------------------------------------------- 1 | //O(n) and O(1) 2 | public class Solution { 3 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 4 | //boundary check 5 | if(headA == null || headB == null) return null; 6 | 7 | ListNode a = headA; 8 | ListNode b = headB; 9 | 10 | //if a & b have different len, then we will stop the loop after second iteration 11 | while( a != b){ 12 | //for the end of first iteration, we just reset the pointer to the head of another linkedlist 13 | a = a == null? headB : a.next; 14 | b = b == null? headA : b.next; 15 | } 16 | 17 | return a; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /3 LinkedLists/2 3 4 5 6 Find nth node from end.java: -------------------------------------------------------------------------------- 1 | //One pass O(n) time and O(1) space 2 | class Solution { 3 | public ListNode removeNthFromEnd(ListNode head, int n) { 4 | ListNode slow = head, fast = head; 5 | while(n>0){ 6 | fast = fast.next; 7 | n--; 8 | } 9 | ListNode prev = null; 10 | while(fast!=null){ 11 | prev = slow; 12 | fast = fast.next; 13 | slow = slow.next; 14 | } 15 | return slow; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /3 LinkedLists/25 26 27 28 Middle of a LL.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | public ListNode middle(ListNode head){ 3 | if(head==null || head.next==null) return head; 4 | ListNode slow = head, fast = head; 5 | while(fast!=null && fast.next!=null){ 6 | slow = slow.next; 7 | fast = fast.next.next; 8 | } 9 | return slow; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /3 LinkedLists/29 LL from End.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | public void display(ListNode head) 3 | { 4 | if(head==null) return; 5 | display(head.next); 6 | System.out.print(head.val+"->); 7 | } 8 | -------------------------------------------------------------------------------- /3 LinkedLists/32 Merge 2 sorted lists.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | class Solution { 3 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 4 | ListNode dummy = new ListNode(0); 5 | ListNode iter = dummy; 6 | while(l1!=null && l2!=null){ 7 | if(l1.val 0) { 13 | ListNode tmp = head.next; 14 | head.next = curr; 15 | curr = head; 16 | head = tmp; 17 | } 18 | head = curr; 19 | } 20 | return head; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /3 LinkedLists/45 Copy List With Random Pointer: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | public class Solution { 3 | public RandomListNode copyRandomList(RandomListNode head) { 4 | //Step 1: Create a new node and keep it next to the original nodes 5 | RandomListNode iter = head; 6 | while(iter!=null){ 7 | RandomListNode next = iter.next; 8 | RandomListNode newnode = new RandomListNode(iter.label); 9 | iter.next = newnode; 10 | newnode.next = next; 11 | iter = next; 12 | } 13 | //Step 2: Copy the random nodes to the new nodes 14 | iter = head; 15 | while(iter!=null){ 16 | if(iter.random!=null){ 17 | iter.next.random = iter.random.next; 18 | } 19 | iter = iter.next.next; 20 | } 21 | //Step 3: Extract the original and random list 22 | iter = head; 23 | RandomListNode dummy = new RandomListNode(0); 24 | RandomListNode rand = dummy; 25 | while(iter!=null){ 26 | RandomListNode next = iter.next.next; 27 | rand.next = iter.next; 28 | rand = rand.next; 29 | iter.next = next; 30 | iter = next; 31 | } 32 | return dummy.next; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /3 LinkedLists/50 Median in an infinite steram of integers.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | //Default pq in java is a min pq 3 | PriorityQueue min; 4 | PriorityQueue max; 5 | public MedianFinder() { 6 | min = new PriorityQueue(); 7 | max = new PriorityQueue(); 8 | } 9 | //O(logn) 10 | public void addNum(int num) { 11 | max.offer(-num); 12 | min.offer(-max.poll()); 13 | if(max.size() q = new PriorityQueue(lists.length, new Comparator(){ 9 | public int compare(ListNode l1, ListNode l2) { 10 | return l1.val-l2.val; 11 | } 12 | }); 13 | for(ListNode node:lists){ 14 | if(node!=null) 15 | q.offer(node); 16 | } 17 | while(!q.isEmpty()){ 18 | ListNode temp = q.poll(); 19 | cur.next = temp; 20 | if(temp.next!=null) 21 | q.offer(temp.next); 22 | cur=cur.next; 23 | } 24 | return dummy.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /3 LinkedLists/67RemoveDuplicatesinaLL.java: -------------------------------------------------------------------------------- 1 | //TC:O(n) and SC:O(n) 2 | public class Solution{ 3 | public void RemoveDuplicates(ListNode head){ 4 | Set set = new HashSet(); 5 | ListNode iter = head; 6 | ListNode dummy = new ListNode(0); 7 | ListNode ret = dummy; 8 | while(iter!=null){ 9 | if(!set.contains(iter.val)){ 10 | set.add(iter.val); 11 | dummy.next = iter; 12 | dummy = dummy.next; 13 | } 14 | iter = iter.next; 15 | } 16 | return ret.next; 17 | } 18 | } -------------------------------------------------------------------------------- /3 LinkedLists/68PrintEvenFirstandOddnext.java: -------------------------------------------------------------------------------- 1 | //TC:O(n) and SC:O(1) 2 | public class Solution{ 3 | public void FirstEventhenOdd(ListNode head){ 4 | ListNode evenstart, evenend; 5 | ListNode oddstart, oddend; 6 | ListNode iter = head; 7 | while(iter!=null){ 8 | //If the current node is even and even start is null, then assign this node to even start 9 | if(iter.val%2==0){ 10 | if(evenstart==null){ 11 | evenstart = iter; 12 | evenend = evenstart; 13 | } 14 | else{ 15 | evenend.next = iter; 16 | evenend = evenend.next; 17 | } 18 | } 19 | else{ 20 | if(oddstart==null){ 21 | oddstart = iter; 22 | oddend = oddstart; 23 | } 24 | else{ 25 | oddend.next = iter; 26 | oddend = oddend.next; 27 | } 28 | } 29 | iter = iter.next; 30 | } 31 | if(evenstart==null||oddstart==null) return; 32 | evenend.next = oddstart; 33 | oddend.next = null; 34 | head = evenstart; 35 | } 36 | } -------------------------------------------------------------------------------- /3 LinkedLists/69CommonElementsofASortedList.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | public ListNode printcommon(ListNode l1, ListNode l2){ 3 | ListNode dummy = new ListNode(0); 4 | ListNode ret = dummy; 5 | while(l1!=null&&l2!=null){ 6 | if(l1.data==l2.data){ 7 | ListNode newnode = new ListNode(l1.data); 8 | dummy.next = newnode; 9 | dummy = dummy.next; 10 | l1 = l1.next; 11 | l2 = l2.next; 12 | } 13 | else if(l1.data>l2.data){ 14 | l2 = l2.next; 15 | } 16 | else 17 | l1 = l1.next; 18 | } 19 | return ret.next; 20 | } 21 | } -------------------------------------------------------------------------------- /3 LinkedLists/7 8 9 10 11 LL Cycle.java: -------------------------------------------------------------------------------- 1 | //O(n) time and O(1) space 2 | public class Solution { 3 | public boolean hasCycle(ListNode head) { 4 | //Sanity check 5 | if(head==null || head.next==null) return false; 6 | ListNode slow = head, fast = head; 7 | while(fast!=null && fast.next!=null){ 8 | slow = slow.next; 9 | fast = fast.next.next; 10 | if(slow==fast) return true; 11 | } 12 | return false; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /3 LinkedLists/Delete Node in a Linked list: -------------------------------------------------------------------------------- 1 | /* 2 | Delete Node at a given position in a linked list 3 | head pointer input could be NULL as well for empty list 4 | Node is defined as 5 | class Node { 6 | int data; 7 | Node next; 8 | } 9 | */ 10 | // This is a "method-only" submission. 11 | // You only need to complete this method. 12 | 13 | Node Delete(Node head, int position) { 14 | if(position==0) return head.next; 15 | Node p = head,q=null; 16 | while(position>0){ 17 | q = p; 18 | p = p.next; 19 | position--; 20 | } 21 | q.next = p.next; 22 | return head; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /3 LinkedLists/Notes.txt: -------------------------------------------------------------------------------- 1 | Advantages of LinkedList: 1) Constant time insertion and deletion from head. 2 | 2) No need to specify the size initially as the size grows dynamically 3 | 4 | Disadvantages: 1) No constant time indexing 5 | 2) Wastage of space 6 | 7 | 8 | Circular Linked List applications: 9 | 10 | 1) When sevaral processes are sharing the cpu, round robin algorithm for scheduling 11 | 2) Implementation of Stacks and Queues 12 | -------------------------------------------------------------------------------- /4 Stacks/1 Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | if(s==null||s.length()==0) return true; 4 | Stack stack = new Stack(); 5 | int i=0; 6 | int n =s.length(); 7 | while(i stack){ 8 | if(stack.isEmpty()) return; 9 | int temp = stack.pop(); 10 | reverseStack(stack); 11 | insertAtBottom(stack, temp); 12 | } 13 | public static void insertAtBottom(Stack stack, int temp){ 14 | if(stack.isEmpty()) 15 | { 16 | stack.push(temp); 17 | return; 18 | } 19 | int temp2 = stack.pop(); 20 | insertAtBottom(stack, temp2); 21 | stack.push(temp); 22 | } 23 | public static void main(String[] args){ 24 | Scanner in = new Scanner(System.in); 25 | Stack stack = new Stack(); 26 | System.out.println("Please enter the length of the numbers"); 27 | int n = in.nextInt(); 28 | for(int i=0;i s1; 3 | Stack s2; 4 | /** Initialize your data structure here. */ 5 | public MyQueue() { 6 | s1 = new Stack(); 7 | s2 = new Stack(); 8 | } 9 | //O(1) 10 | /** Push element x to the back of queue. */ 11 | public void push(int x) { 12 | s1.push(x); 13 | } 14 | //O(n) 15 | /** Removes the element from in front of queue and returns that element. */ 16 | public int pop() { 17 | while(!s1.isEmpty()) 18 | s2.push(s1.pop()); 19 | int ret = s2.pop(); 20 | while(!s2.isEmpty()) 21 | s1.push(s2.pop()); 22 | return ret; 23 | } 24 | 25 | //O(n) 26 | /** Get the front element. */ 27 | public int peek() { 28 | while(!s1.isEmpty()) 29 | s2.push(s1.pop()); 30 | int ret = s2.peek(); 31 | while(!s2.isEmpty()) 32 | s1.push(s2.pop()); 33 | return ret; 34 | } 35 | 36 | //O(1) 37 | /** Returns whether the queue is empty. */ 38 | public boolean empty() { 39 | return s1.isEmpty(); 40 | } 41 | } 42 | 43 | /** 44 | * Your MyQueue object will be instantiated and called as such: 45 | * MyQueue obj = new MyQueue(); 46 | * obj.push(x); 47 | * int param_2 = obj.pop(); 48 | * int param_3 = obj.peek(); 49 | * boolean param_4 = obj.empty(); 50 | */ 51 | -------------------------------------------------------------------------------- /4 Stacks/13 Stack using Queues.java: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | 3 | Queue q1; 4 | Queue q2; 5 | public MyStack() { 6 | q1 = new LinkedList(); 7 | q2 = new LinkedList(); 8 | } 9 | 10 | //O(1) 11 | /** Push element x onto stack. */ 12 | public void push(int x) { 13 | q1.offer(x); 14 | } 15 | 16 | //O(n) 17 | /** Removes the element on top of the stack and returns that element. */ 18 | public int pop() { 19 | while(q1.size()>1) 20 | q2.offer(q1.poll()); 21 | int ret = q1.poll(); 22 | while(!q2.isEmpty()) 23 | q1.offer(q2.poll()); 24 | return ret; 25 | } 26 | //O(n) 27 | /** Get the top element. */ 28 | public int top() { 29 | while(q1.size()>1) 30 | q2.offer(q1.poll()); 31 | int ret = q1.poll(); 32 | while(!q2.isEmpty()) 33 | q1.offer(q2.poll()); 34 | q1.offer(ret); 35 | return ret; 36 | } 37 | 38 | //O(1) 39 | /** Returns whether the stack is empty. */ 40 | public boolean empty() { 41 | return q1.isEmpty(); 42 | } 43 | } 44 | 45 | /** 46 | * Your MyStack object will be instantiated and called as such: 47 | * MyStack obj = new MyStack(); 48 | * obj.push(x); 49 | * int param_2 = obj.pop(); 50 | * int param_3 = obj.top(); 51 | * boolean param_4 = obj.empty(); 52 | */ 53 | -------------------------------------------------------------------------------- /4 Stacks/22 23 spanfinding.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | public class spanfinding { 7 | public static int[] spanfinding(int[] input){ 8 | if(input==null || input.length == 0) return new int[0]; 9 | int n = input.length; 10 | Stack stack = new Stack(); 11 | int[] spans = new int[n]; 12 | spans[0] = 1; 13 | stack.push(0); 14 | for(int i=1;i stack = new Stack(); 5 | int n = heights.length; 6 | int area = 0; 7 | for(int i=0;i<=n;i++){ 8 | int h = i==n?0:heights[i]; 9 | if(stack.isEmpty() || h>=heights[stack.peek()]) 10 | stack.push(i); 11 | else{ 12 | int tp = stack.pop(); 13 | area = Math.max(area, heights[tp]*(stack.isEmpty()?i:i-stack.peek()-1)); 14 | i--; 15 | } 16 | } 17 | return area; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /4 Stacks/26 StackSorting.java: -------------------------------------------------------------------------------- 1 | //O(n2) and O(n) 2 | public class Solution{ 3 | public Stack sort(Stack stk){ 4 | Stack rstk = new Stack(); 5 | while(!stk.isEmpty()){ 6 | int tmp = stk.pop(); 7 | while(!rstk.isEmpty()&&rstk.peek()>tmp) 8 | stk.push(rstk.pop()); 9 | rstk.push(tmp); 10 | } 11 | return rstk; 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /4 Stacks/27 Consecutive pairs.java: -------------------------------------------------------------------------------- 1 | package queues; 2 | import java.util.*; 3 | 4 | public class consecutivepairs { 5 | 6 | public static boolean consecutivepairs(Stack stack){ 7 | if(stack.isEmpty()) return true; 8 | Queue queue = new LinkedList(); 9 | //Reversing stack contents to satisfy the single number at the top requirement 10 | while(!stack.isEmpty()) 11 | queue.add(stack.pop()); 12 | while(!queue.isEmpty()) 13 | stack.push(queue.poll()); 14 | while(!stack.isEmpty()){ 15 | int m = stack.pop(); 16 | if(!stack.isEmpty()){ 17 | int n = stack.pop(); 18 | if(Math.abs(m-n)!=1) return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | public static void main(String[] args){ 25 | Scanner in = new Scanner(System.in); 26 | Stack stack = new Stack(); 27 | System.out.println("Please enter your input numbers length"); 28 | int n = in.nextInt(); 29 | System.out.println("Please enter your inputs now"); 30 | for(int i=0;i stack = new Stack(); 10 | int i = 0; 11 | while(i stack){ 27 | Stack temp = new Stack<>(); 28 | while(!stack.isEmpty()) temp.push(stack.pop()); 29 | while(!temp.isEmpty()) System.out.println(temp.pop()); 30 | } 31 | 32 | public static void main(String[] args) { 33 | int[] arr = {1,9,6,8,8,8,0,1,1,0,6,5}; 34 | RecursiveRemoval(arr); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /4 Stacks/3 Catalan numbers.java: -------------------------------------------------------------------------------- 1 | //F(n,i) = summation:i=1 to n(F(i-1))*(F(n-i)) 2 | class Solution { 3 | public int numTrees(int n) { 4 | if(n<0) return 0; 5 | int[] dp = new int[n+1]; 6 | dp[0] = 1; 7 | dp[1] = 1; 8 | for(int i=2;i<=n;i++){ 9 | for(int j=1;j<=i;j++) 10 | dp[i]= dp[i] + (dp[j-1]*dp[i-j]); 11 | } 12 | return dp[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /4 Stacks/4 postfixevaluation.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class postfixevaluation { 6 | public static int postfixevaluation(String s){ 7 | Stack stack = new Stack(); 8 | for(char c:s.toCharArray()){ 9 | if(c=='+'){ 10 | int a = stack.pop(); 11 | int b = stack.pop(); 12 | stack.push(a+b); 13 | } 14 | else if(c=='-'){ 15 | int a = stack.pop(); 16 | int b = stack.pop(); 17 | stack.push(b-a); 18 | } 19 | else if(c=='*'){ 20 | int a = stack.pop(); 21 | int b = stack.pop(); 22 | stack.push(a*b); 23 | } 24 | else if(c=='/'){ 25 | int a = stack.pop(); 26 | int b = stack.pop(); 27 | stack.push(b/a); 28 | } 29 | else{ 30 | stack.push(Character.getNumericValue(c)); 31 | } 32 | } 33 | return stack.pop(); 34 | } 35 | private static boolean isOperator(char c) 36 | { 37 | return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' 38 | || c == '(' || c == ')'; 39 | } 40 | public static void main(String[] args){ 41 | System.out.println(postfixevaluation("123*+5-")); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /4 Stacks/6 7 Minstack.java: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | Stack stack; 3 | Stack minstack; 4 | public MinStack() { 5 | stack = new Stack(); 6 | minstack = new Stack(); 7 | } 8 | 9 | public void push(int x) { 10 | stack.push(x); 11 | if(minstack.isEmpty() || minstack.peek()>x){ 12 | minstack.push(x); 13 | } 14 | else 15 | minstack.push(minstack.peek()); 16 | } 17 | 18 | public void pop() { 19 | stack.pop(); 20 | minstack.pop(); 21 | } 22 | 23 | public int top() { 24 | return stack.peek(); 25 | } 26 | 27 | public int getMin() { 28 | return minstack.peek(); 29 | } 30 | } 31 | 32 | /** 33 | * Your MinStack object will be instantiated and called as such: 34 | * MinStack obj = new MinStack(); 35 | * obj.push(x); 36 | * obj.pop(); 37 | * int param_3 = obj.top(); 38 | * int param_4 = obj.getMin(); 39 | */ 40 | -------------------------------------------------------------------------------- /4 Stacks/8 9 10 Stack Palindrome.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.*; 3 | public class StackPalindrome { 4 | //O(n) time and space 5 | private boolean isP(String s){ 6 | if(s==null || s.length()==0) return true; 7 | int n = s.length(); 8 | Stack stack = new Stack<>(); 9 | int i = 0; 10 | while(s.charAt(i)!='X') stack.push(s.charAt(i++)); 11 | i++; 12 | while(!stack.isEmpty()){ 13 | if(stack.pop()!=s.charAt(i++)) return false; 14 | } 15 | return true; 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner in = new Scanner(System.in); 20 | System.out.println("Please enter your input string"); 21 | String s = in.nextLine(); 22 | StackPalindrome sp = new StackPalindrome(); 23 | System.out.println("Is the given string a palindrome "+sp.isP(s)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /4 Stacks/ArrayImplementation.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | 3 | public class ArrayImplementation { 4 | int[] arr; 5 | int capacity; 6 | int top; 7 | 8 | public ArrayImplementation(int capacity){ 9 | this.capacity = capacity; 10 | arr = new int[capacity]; 11 | top = -1; 12 | } 13 | 14 | //O(1) 15 | //Insert at the beginning in a singly linked list 16 | public void push(int x){ 17 | if(top == capacity-1) { 18 | System.out.println("Stack capacity reached and this element cannot be pushed "); 19 | return; 20 | } 21 | arr[++top] = x; 22 | System.out.println(x+" is pushed onto the stack"); 23 | } 24 | 25 | //O(1) 26 | //Delete from beginning of a linked list 27 | public int pop(){ 28 | if(top==-1){ 29 | System.out.println("Stack is Empty"); 30 | return -1; 31 | } 32 | int ret = arr[top--]; 33 | System.out.println(ret+" is popped from the stack"); 34 | return ret; 35 | } 36 | 37 | public int peek(){ 38 | return arr[top]; 39 | } 40 | 41 | public boolean isEmpty(){ 42 | return (top==-1); 43 | } 44 | 45 | public int size(){ 46 | return top+1; 47 | } 48 | 49 | public static void main(String[] args) { 50 | ArrayImplementation l = new ArrayImplementation(10); 51 | l.push(4); 52 | l.push(5); 53 | System.out.println(l.peek()); 54 | System.out.println(l.pop()); 55 | System.out.println(l.size()); 56 | System.out.println(l.isEmpty()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /4 Stacks/LinkedListImplementation.java: -------------------------------------------------------------------------------- 1 | package Stacks; 2 | import java.util.*; 3 | 4 | public class LinkedListImplementation { 5 | ListNode head; 6 | int size; 7 | public static class ListNode{ 8 | int val; 9 | ListNode next; 10 | public ListNode(){ 11 | this.next = null; 12 | } 13 | public ListNode(int val){ 14 | this.val = val; 15 | this.next = null; 16 | } 17 | } 18 | 19 | public LinkedListImplementation(){ 20 | head = new ListNode(); 21 | size = 0; 22 | } 23 | 24 | //O(1) 25 | //Insert at the beginning in a singly linked list 26 | public void push(int x){ 27 | size++; 28 | ListNode newnode = new ListNode(x); 29 | newnode.next = head; 30 | head = newnode; 31 | System.out.println(x+" is pushed onto the stack"); 32 | } 33 | 34 | //O(1) 35 | //Delete from beginning of a linked list 36 | public int pop(){ 37 | int ret = head.val; 38 | //Delete head 39 | head = head.next; 40 | size--; 41 | System.out.println(ret+"is popped from the stack"); 42 | return ret; 43 | } 44 | 45 | public int peek(){ 46 | return head.val; 47 | } 48 | 49 | public boolean isEmpty(){ 50 | return (size==0); 51 | } 52 | 53 | public int size(){ 54 | return size; 55 | } 56 | 57 | public static void main(String[] args) { 58 | LinkedListImplementation l = new LinkedListImplementation(); 59 | l.push(4); 60 | l.push(5); 61 | System.out.println(l.peek()); 62 | System.out.println(l.pop()); 63 | System.out.println(l.size()); 64 | System.out.println(l.isEmpty()); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /4 Stacks/Notes.txt: -------------------------------------------------------------------------------- 1 | Stack: Filo or Lifo 2 | 1) Operations on a stack: 3 | Push, pop, peek, isEmpty, size 4 | 5 | 2) Underflow and Overflow 6 | 7 | 3) Applications of a stack: 8 | a) Postfix conversion and evaluation 9 | b) balancing the symbols 10 | c) Function calls 11 | d) Undo 12 | e) Back button in browser 13 | 14 | 4) Implementation of stacks: 15 | a) Fixed array 16 | b) Dynamic array 17 | c) LinkedList implementation 18 | -------------------------------------------------------------------------------- /5 Queues/1 Queue Reversal.java: -------------------------------------------------------------------------------- 1 | package Queues; 2 | import java.util.*; 3 | import java.util.Scanner; 4 | 5 | public class QueueRevrsal { 6 | 7 | //O(n) time and space 8 | public void reverse(Queue queue){ 9 | Stack stack = new Stack<>(); 10 | while(!queue.isEmpty()) 11 | stack.push(queue.poll()); 12 | while(!stack.isEmpty()) 13 | queue.offer(stack.pop()); 14 | } 15 | 16 | public void display(Queue queue){ 17 | Queue temp = new LinkedList<>(queue); 18 | for(int i=queue.size()-1;i>=0;i--) 19 | System.out.print(temp.poll()+" "); 20 | System.out.println(" "); 21 | } 22 | 23 | public static void main(String[] args) { 24 | QueueRevrsal q = new QueueRevrsal(); 25 | Scanner in = new Scanner(System.in); 26 | System.out.println("Please enter the size of the queue and the elements into the queue"); 27 | Queue queue = new LinkedList<>(); 28 | int n = in.nextInt(); 29 | for(int i=0;i q = new LinkedList(); 11 | for(int inp:input) 12 | q.add(inp); 13 | Stack s = new Stack(); 14 | for(int i=0;i s1 = new Stack(); 5 | Stack s2 = new Stack(); 6 | public void enqueue(int a){ 7 | s1.push(a); 8 | } 9 | public int dequeue(){ 10 | while(!s1.isEmpty()){ 11 | s2.push(s1.pop()); 12 | } 13 | int ret = s2.pop(); 14 | while(!s2.isEmpty()) 15 | s1.push(s2.pop()); 16 | return ret; 17 | } 18 | public static void main(String[] args){ 19 | Implementqueueswithstacks i = new Implementqueueswithstacks(); 20 | i.enqueue(5); 21 | i.enqueue(6); 22 | System.out.println(i.dequeue()); 23 | System.out.println(i.dequeue()); 24 | i.enqueue(7); 25 | i.enqueue(8); 26 | System.out.println(i.dequeue()); 27 | System.out.println(i.dequeue()); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /5 Queues/3 Implement Stack using Queues.java: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | 3 | Queue q1; 4 | Queue q2; 5 | public MyStack() { 6 | q1 = new LinkedList(); 7 | q2 = new LinkedList(); 8 | } 9 | 10 | /** Push element x onto stack. */ 11 | public void push(int x) { 12 | q1.offer(x); 13 | } 14 | 15 | /** Removes the element on top of the stack and returns that element. */ 16 | public int pop() { 17 | int size = q1.size(); 18 | int index = 0; 19 | while(index q = new ArrayDeque(); 10 | for(int i=0;iq.peek()) 12 | q.poll(); 13 | //Remove items from the end 14 | while(!q.isEmpty() && nums[i]>nums[q.peekLast()]) 15 | q.pollLast(); 16 | q.offer(i); 17 | if(i>=k-1) 18 | result[index++] = nums[q.peek()]; 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /5 Queues/8 consecutivepairs.java: -------------------------------------------------------------------------------- 1 | package queues; 2 | import java.util.*; 3 | 4 | public class consecutivepairs { 5 | 6 | public static boolean consecutivepairs(Stack stack){ 7 | if(stack.isEmpty()) return true; 8 | Queue queue = new LinkedList(); 9 | //Reversing stack contents to satisfy the single number at the top requirement 10 | while(!stack.isEmpty()) 11 | queue.add(stack.pop()); 12 | while(!queue.isEmpty()) 13 | stack.push(queue.poll()); 14 | while(!stack.isEmpty()){ 15 | int m = stack.pop(); 16 | if(!stack.isEmpty()){ 17 | int n = stack.pop(); 18 | if(Math.abs(m-n)!=1) return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | public static void main(String[] args){ 25 | Scanner in = new Scanner(System.in); 26 | Stack stack = new Stack(); 27 | System.out.println("Please enter your input numbers length"); 28 | int n = in.nextInt(); 29 | System.out.println("Please enter your inputs now"); 30 | for(int i=0;i q = new LinkedList(); 9 | for(int inp:input) 10 | q.add(inp); 11 | Stack s = new Stack(); 12 | int half = input.length/2; 13 | //Step 1 14 | //11 12 13 14 -> 13 14 12 11 15 | for(int i=0;i 12 11 13 14 22 | for(int i=0;i queue.offer(int value), queue.poll(), queue.size(), queue.isEmpty(), queue.peek() 11 | 12 | 5) Applications of a queue: 13 | a) Scheduling jobs in operating systems 14 | b) Simulating real-time queue scenarios 15 | 16 | 6) Implementation of queues: 17 | a) Fixed size Circular Array implementation 18 | b) Dynamic circular Array implementation 19 | c) LinkedList implementation 20 | -------------------------------------------------------------------------------- /6 Trees/1 2 Max element in a tree.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public int max(TreeNode root){ 3 | int max = Integer.MIN_VALUE; 4 | if(root==null) return max; 5 | Queue q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | for(int i=0;i q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | count++; 10 | for(int i=0;i queue = new LinkedList(); 5 | int depth = 0; 6 | queue.offer(root); 7 | while(!queue.isEmpty()){ 8 | int level = queue.size(); 9 | for(int i=0;i q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | for(int i=0;i q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | max = Math.max(max, level); 10 | for(int i=0;i q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | int sum = 0; 10 | for(int i=0;i binaryTreePaths(TreeNode root) { 4 | List list = new ArrayList(); 5 | if(root==null) return list; 6 | helper(list,"",root); 7 | return list; 8 | } 9 | public void helper(List list, String s, TreeNode root){ 10 | if(root.left==null && root.right==null){ 11 | list.add(s+root.val+""); 12 | return; 13 | } 14 | s+=root.val+"->"; 15 | if(root.left!=null){ 16 | helper(list,s,root.left); 17 | } 18 | if(root.right!=null){ 19 | helper(list,s,root.right); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /6 Trees/24 pathsum.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public boolean hasPathSum(TreeNode root, int sum) { 4 | return helper(root,sum); 5 | } 6 | public boolean helper(TreeNode root, int sum){ 7 | if(root==null) return false; 8 | if(root.val==sum && (root.left==null && root.right==null)) return true; 9 | return (helper(root.left,sum-root.val) || helper(root.right,sum-root.val)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /6 Trees/25 26 Sum.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public int size(TreeNode root, int val){ 3 | if(root==null) return 0; 4 | int sum = 0; 5 | Queue q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | for(int i=0;ipe || is>ie) return null; 8 | TreeNode root = new TreeNode(preorder[ps]); 9 | //Find the index of preorder[ps] in inorder 10 | int offset = is; 11 | for(;offset<=ie;offset++){ 12 | if(inorder[offset]==preorder[ps]) 13 | break; 14 | } 15 | root.left = helper(preorder, ps+1,ps+offset-is,inorder, is, offset-1); 16 | root.right = helper(preorder, ps+offset-is+1, pe, inorder,offset+1,ie); 17 | return root; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /6 Trees/3 4 Search.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public boolean search(TreeNode root, int val){ 3 | if(root==null) return false; 4 | Queue q = new LinkedList(); 5 | q.offer(root); 6 | while(!q.isEmpty()){ 7 | int level = q.size(); 8 | for(int i=0;ipostend||instart>inend) return null; 9 | int data = postorder[postend]; 10 | TreeNode curr = new TreeNode(data); 11 | int offset = instart; 12 | for(;offset> zigzagLevelOrder(TreeNode root) { 4 | List> list = new ArrayList(); 5 | if(root==null) return list; 6 | Queue q = new LinkedList(); 7 | q.offer(root); 8 | boolean z = false; 9 | while(!q.isEmpty()){ 10 | int level = q.size(); 11 | List sublist = new ArrayList(); 12 | for(int i=0;i> verticalOrder(TreeNode root) { 4 | List> list = new ArrayList(); 5 | if(root==null) return list; 6 | Map> map = new HashMap(); 7 | Queue q = new LinkedList(); 8 | Queue columns = new LinkedList(); 9 | q.offer(root); 10 | columns.offer(0); 11 | int min = 0, max = 0; 12 | while(!q.isEmpty()){ 13 | TreeNode node = q.poll(); 14 | int line = columns.poll(); 15 | if(map.get(line)==null){ 16 | map.put(line, new ArrayList()); 17 | } 18 | map.get(line).add(node.val); 19 | if(node.left!=null){ 20 | q.offer(node.left); 21 | columns.add(line-1); 22 | min = Math.min(min, line-1); 23 | } 24 | if(node.right!=null){ 25 | q.offer(node.right); 26 | columns.add(line+1); 27 | max = Math.max(max, line+1); 28 | } 29 | } 30 | for(int i=min;i<=max;i++){ 31 | list.add(map.get(i)); 32 | } 33 | return list; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /6 Trees/36 53 Unique bst.java: -------------------------------------------------------------------------------- 1 | //F(n,i) = summation:i=1 to n(F(i-1))*(F(n-i)) 2 | class Solution { 3 | public int numTrees(int n) { 4 | if(n<0) return 0; 5 | int[] dp = new int[n+1]; 6 | dp[0] = 1; 7 | dp[1] = 1; 8 | for(int i=2;i<=n;i++){ 9 | for(int j=1;j<=i;j++) 10 | dp[i]= dp[i] + (dp[j-1]*dp[i-j]); 11 | } 12 | return dp[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /6 Trees/37 Unique BST 2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List generateTrees(int n) { 3 | if(n<=0) return new ArrayList(); 4 | return helper(1,n); 5 | } 6 | public List helper(int start, int end){ 7 | List list = new ArrayList(); 8 | if(start>end){ 9 | list.add(null); 10 | return list; 11 | } 12 | if(start==end){ 13 | list.add(new TreeNode(start)); 14 | return list; 15 | } 16 | List left, right; 17 | for(int i=start;i<=end;i++){ 18 | left = helper(start,i-1); 19 | right = helper(i+1,end); 20 | for(TreeNode l: left){ 21 | for(TreeNode r:right){ 22 | TreeNode root = new TreeNode(i); 23 | root.left = l; 24 | root.right = r; 25 | list.add(root); 26 | } 27 | } 28 | } 29 | return list; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /6 Trees/39 40 Right pointers.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | public class Solution { 3 | public void connect(TreeLinkNode root) { 4 | if(root==null) return; 5 | Queue q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | TreeLinkNode prev = null; 10 | for(int i=0;i q = new LinkedList(); 5 | q.offer(root); 6 | while(!q.isEmpty()){ 7 | int level = q.size(); 8 | for(int i=0;i list = inorderTraversal(root); 5 | for(int i=1;i inorderTraversal(TreeNode root) { 11 | List list = new ArrayList(); 12 | if(root==null) return list; 13 | Stack stack = new Stack(); 14 | boolean done = false; 15 | TreeNode cur = root; 16 | while(!done){ 17 | if(cur!=null){ 18 | stack.push(cur); 19 | cur = cur.left; 20 | } 21 | else{ 22 | if(stack.isEmpty()) 23 | done = true; 24 | else{ 25 | cur = stack.pop(); 26 | list.add(cur.val); 27 | cur = cur.right; 28 | } 29 | } 30 | } 31 | return list; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /6 Trees/59 bst to Circular DLL.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | //Given a bst root, convert these elements into a circular dll 4 | //The order of the elements must be in inorder 5 | public class bsttoCircularDLL { 6 | public static class TreeNode{ 7 | int val; 8 | TreeNode left, right; 9 | public TreeNode(int val){ 10 | this.val = val; 11 | this.left = null; 12 | this.right = null; 13 | } 14 | } 15 | public static class DLNode{ 16 | int val; 17 | DLNode prev, next; 18 | 19 | public DLNode(int val){ 20 | this.val = val; 21 | this.prev = null; 22 | this.next = null; 23 | } 24 | } 25 | 26 | public DLNode convert(TreeNode root){ 27 | if(root==null) return null; 28 | DLNode left = convert(root.left); 29 | DLNode right = convert(root.right); 30 | DLNode head = new DLNode(root.val); 31 | head.prev = head.next = head; 32 | return concatenate(concatenate(left,head),right); 33 | } 34 | 35 | public DLNode concatenate(DLNode leftList,DLNode rightList) 36 | { 37 | if (leftList == null) 38 | return rightList; 39 | if (rightList == null) 40 | return leftList; 41 | DLNode leftLast = leftList.prev; 42 | DLNode rightLast = rightList.prev; 43 | leftLast.next = rightList; 44 | rightList.prev = leftLast; 45 | leftList.prev = rightLast; 46 | rightLast.next = leftList; 47 | return leftList; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /6 Trees/6 7 Size of a binary tree.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public int size(TreeNode root, int val){ 3 | if(root==null) return 0; 4 | int count = 0; 5 | Queue q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | for(int i=0;iend) return null; 9 | int mid = (start+end)/2; 10 | TreeNode root = new TreeNode(nums[mid]); 11 | root.left = helper(nums,start,mid-1); 12 | root.right = helper(nums,mid+1,end); 13 | return root; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /6 Trees/64 Kth smallest.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public int kthSmallest(TreeNode root, int k) { 4 | List list = inorderTraversal(root); 5 | return list.get(k-1); 6 | } 7 | public List inorderTraversal(TreeNode root) { 8 | List list = new ArrayList(); 9 | if(root==null) return list; 10 | Stack stack = new Stack(); 11 | boolean done = false; 12 | TreeNode cur = root; 13 | while(!done){ 14 | if(cur!=null){ 15 | stack.push(cur); 16 | cur = cur.left; 17 | } 18 | else{ 19 | if(stack.isEmpty()) 20 | done = true; 21 | else{ 22 | cur = stack.pop(); 23 | list.add(cur.val); 24 | cur = cur.right; 25 | } 26 | } 27 | } 28 | return list; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /6 Trees/66 67 68 merge.java: -------------------------------------------------------------------------------- 1 | //Convert both bsts into sorted DLL 2 | //Merge sorted DLL 3 | //Convert this sorted DLL into BST 4 | //O(m+n) and O(1) 5 | -------------------------------------------------------------------------------- /6 Trees/69 70 71 72 RangePrinter.java: -------------------------------------------------------------------------------- 1 | //Perform inorder traversal to get the list in sorted order 2 | //now just print the elements from k1 to k2 in the sorted list 3 | //O(n) time and space solution 4 | -------------------------------------------------------------------------------- /6 Trees/73 74 Same.java: -------------------------------------------------------------------------------- 1 | //Perform inorder traversals to get two lists 2 | //If contents of two lists are same, return true 3 | //Else return false 4 | //O(max(m,n)) time and space 5 | -------------------------------------------------------------------------------- /6 Trees/8 Delete a tree.java: -------------------------------------------------------------------------------- 1 | public void delete(TreeNode root){ 2 | root = null; 3 | } 4 | -------------------------------------------------------------------------------- /6 Trees/87 88 connect.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | public class Solution { 3 | public void connect(TreeLinkNode root) { 4 | if(root==null) return; 5 | Queue q = new LinkedList(); 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int level = q.size(); 9 | TreeLinkNode prev = null; 10 | for(int i=0;i> levelOrder(TreeNode root) { 4 | List> list = new ArrayList(); 5 | if(root==null) return list; 6 | Queue q = new LinkedList(); 7 | q.offer(root); 8 | while(!q.isEmpty()){ 9 | int level = q.size(); 10 | List sublist = new ArrayList(); 11 | for(int i=0;i Inorder(TreeNode root){ 10 | List result = new ArrayList(); 11 | if(root==null) return result; 12 | Stack stack = new Stack(); 13 | TreeNode cur = root; 14 | boolean done = false; 15 | while(!done){ 16 | if(cur!=null){ 17 | stack.push(cur); 18 | cur = cur.left; 19 | } 20 | else{ 21 | if(stack.isEmpty()) 22 | done = true; 23 | else{ 24 | cur = stack.pop(); 25 | result.add(cur.val); 26 | cur = cur.right; 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | -------------------------------------------------------------------------------- /6 Trees/LevelorderTraversal.java: -------------------------------------------------------------------------------- 1 | public List> levelOrder(TreeNode root) { 2 | List> list = new ArrayList(); 3 | if(root==null) return list; 4 | Queue queue = new LinkedList(); 5 | queue.offer(root); 6 | while(!queue.isEmpty()){ 7 | int level = queue.size(); 8 | List sublist = new ArrayList(); 9 | for(int i=0;i Postorder(TreeNode root){ 10 | List result = new ArrayList(); 11 | if(root==null) return result; 12 | Stack stack = new Stack(); 13 | stack.push(root); 14 | TreeNode prev = null; 15 | while(!stack.isEmpty()){ 16 | //Check if traversing down 17 | TreeNode cur = stack.peek(); 18 | if(prev==null || prev.left==cur || prev.right==cur){ 19 | if(cur.left!=null) 20 | stack.push(cur.left); 21 | else if(cur.right!=null) 22 | stack.push(cur.right); 23 | } 24 | else if(cur.left==prev){ 25 | if(cur.right!=null) 26 | stack.push(cur.right); 27 | } 28 | else{ 29 | result.add(cur.val); 30 | stack.pop(); 31 | } 32 | prev = cur; 33 | } 34 | return result; 35 | } 36 | -------------------------------------------------------------------------------- /6 Trees/PreorderTraversal.java: -------------------------------------------------------------------------------- 1 | public void recPreorder(TreeNode root){ 2 | if(root!=null){ 3 | System.out.println(root.val); 4 | recPreorder(root.left); 5 | recPreorder(root.right); 6 | } 7 | } 8 | 9 | public List Preorder(TreeNode root){ 10 | List result = new ArrayList(); 11 | if(root==null) return result; 12 | Stack stack = new Stack(); 13 | stack.push(root); 14 | while(!stack.isEmpty()){ 15 | TreeNode temp = stack.pop(); 16 | result.add(temp.val); 17 | if(temp.right!=null) 18 | stack.push(temp.right); 19 | if(temp.left!=null) 20 | stack.push(temp.left); 21 | } 22 | return result; 23 | } 24 | -------------------------------------------------------------------------------- /7 Priority Queues/22 23 24 Merge K Sorted Lists.java: -------------------------------------------------------------------------------- 1 | //O(nlogk) time and O(k) space 2 | class Solution { 3 | public ListNode mergeKLists(ListNode[] lists) { 4 | //Sanity check 5 | if(lists==null || lists.length==0) return null; 6 | PriorityQueue pq = new PriorityQueue(lists.length, new Comparator(){ 7 | public int compare(ListNode l1, ListNode l2) { 8 | return l1.val-l2.val; 9 | } 10 | }); 11 | for(ListNode l: lists){ 12 | if(l!=null) 13 | { 14 | pq.offer(l); 15 | } 16 | } 17 | ListNode dummy = new ListNode(0); 18 | ListNode iter = dummy; 19 | while(!pq.isEmpty()){ 20 | ListNode temp = pq.poll(); 21 | iter.next = temp; 22 | iter = iter.next; 23 | if(temp.next!=null) pq.offer(temp.next); 24 | } 25 | return dummy.next; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /7 Priority Queues/27 Median in an infinite stream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | //Default pq in java is a min pq 3 | PriorityQueue min; 4 | PriorityQueue max; 5 | public MedianFinder() { 6 | min = new PriorityQueue(); 7 | max = new PriorityQueue(); 8 | } 9 | //O(logn) 10 | public void addNum(int num) { 11 | max.offer(-num); 12 | min.offer(-max.poll()); 13 | if(max.size()= or <= it's children 12 | 2) All leaves must be at h or h-1 where h is the max depth of the tree 13 | 14 | Binary Heap: Each node has atmost two children 15 | 16 | Mergeable heaps: Binary heaps are not efficient at merging one heap with another 17 | For this purpose, mergeable heaps are used. Union operation is efficient in mergeable heap. 18 | ADT Operations: 19 | 1) Insert(H,x,k) 20 | 2) DeleteMin(H) 21 | 3) GetMin(H) 22 | 4) Create() 23 | 5) Union(H1,H2) 24 | 25 | Two mergeable heaps are: 26 | 1) Binomial Heap and 2) Fibonacci heap 27 | They also support the below operations: 28 | 1) Decrease-Key(H,X,K) 29 | 2) Delete(H,X) 30 | 31 | Binomial Heap: Binomial Heap consists of multiple trees unlike normal heaps which contain only one tree. 32 | B0 is a single node tree. Bk is formed recursively by merging two Bk-1's such that one tree is the root and the other is the left child of the root. 33 | 34 | Fibonacci Heap: Fibinacci heap contains multiple trees to. Unlike binomial heaps, there is no restriction on the number of trees and height of trees. Eventhough worst case performance is O(n), amortised cost is O(1) 35 | 36 | -------------------------------------------------------------------------------- /7 Priority Queues/Sliding Window Maximum.java: -------------------------------------------------------------------------------- 1 | //O(n) time and space 2 | class Solution { 3 | public int[] maxSlidingWindow(int[] nums, int k) { 4 | //Sanity check 5 | if(nums==null || nums.length==0 || k<=0) return new int[0]; 6 | int n = nums.length; 7 | int[] result = new int[n-k+1]; 8 | int index = 0; 9 | Deque q = new ArrayDeque(); 10 | for(int i=0;iq.peek()) 12 | q.poll(); 13 | //Remove items from the end 14 | while(!q.isEmpty() && nums[i]>nums[q.peekLast()]) 15 | q.pollLast(); 16 | q.offer(i); 17 | if(i>=k-1) 18 | result[index++] = nums[q.peek()]; 19 | } 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /8 Sets/notes.txt: -------------------------------------------------------------------------------- 1 | Disjoint Sets: Unordered set in which elements are stored in no particular order 2 | This data structure is used in Kruskal's algorithm 3 | 4 | A relation on a set 's' means that for every element a,b which belongs to set 's', aRb is either true or false. 5 | 6 | Equivalence relation: A relation is equivalent if it satisfies the following three properties 7 | 1) Reflexive 8 | 2) Symmetric 9 | 3) Transitive 10 | 11 | Eg: Rail connectivity is an equivalence relation 12 | 13 | Disjoint set operations: 1) MakeSet(X): Create a new set with element x 14 | 2) Union(X,Y): Creates a new set containing with elements x and y and removes all other sets containing both of these elements 15 | 3) Find(x): Returns the name of the set with element x 16 | 17 | Fast find can be implemented by storing the set names in the array value and the element name as array index. Union takes O(n). 18 | 19 | 20 | Fast Union: It can be implemented in 3 ways 21 | 1) Slow Find 22 | 2) Quick Find 23 | 3) Path Compression 24 | 25 | Slow find: Use trees 26 | O(1) union and O(mn) find 27 | 28 | Fast Find 29 | 1) Union by size: Instead of storing the same element, save the negative of the size 30 | 2) Union by Height: store the negative of the height 31 | O(1) union and O(mlogn) find 32 | 33 | Path Compression: On its path to find the parent, create direct pointers between children and parents 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /9 Graphs/dfstopsort.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | import java.util.*; 3 | 4 | public class dfstopsort { 5 | public class graph { 6 | int vertexcount; 7 | ArrayList[] adjlist; 8 | public graph(int v){ 9 | vertexcount = v; 10 | adjlist = new ArrayList[v]; 11 | for(int i=0;i stack, int s){ 20 | visited[s] = true; 21 | ArrayList[] adjlist = g.adjlist; 22 | Iterator iter = adjlist[s].listIterator(); 23 | while(iter.hasNext()){ 24 | Integer v = (Integer) iter.next(); 25 | if(!visited[v]) 26 | helper(g, visited, stack, v); 27 | } 28 | stack.push(s); 29 | } 30 | public void topologicalsort(graph g){ 31 | int v = g.vertexcount; 32 | boolean[] visited = new boolean[v]; 33 | Stack stack = new Stack(); 34 | for(int i=0;i stack){ 41 | while(!stack.isEmpty()){ 42 | int v = stack.pop(); 43 | if(!stack.isEmpty()) 44 | System.out.print(v+"->"); 45 | else 46 | System.out.print(v); 47 | } 48 | 49 | } 50 | public static void main(String[] args){ 51 | dfstopsort d = new dfstopsort(); 52 | graph g = new graph(6); 53 | g.addEdge(5,0); 54 | g.addEdge(4,0); 55 | g.addEdge(4,1); 56 | g.addEdge(3,1); 57 | g.addEdge(2,3); 58 | g.addEdge(5,2); 59 | d.topologicalsort(g); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Venkata Jaya Krishna Thota 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms-and-Data-Structures 2 | My Solutions to standard Algorithms and Data Structures. All programs are written in Java. 3 | --------------------------------------------------------------------------------