├── README.md └── src └── com └── practice ├── CommonData.java ├── DynamicProgramming.java ├── Reflections.java ├── arrays ├── GeeksForGeeks.java ├── Numbers.java ├── README.md └── Strings.java ├── graphs ├── Dijkstra.java ├── Edge.java ├── Graph.java ├── MST.java ├── Vertex.java └── edges.txt ├── hashing └── MyMap.java ├── list ├── DNode.java ├── Main.java └── Node.java ├── misc └── Threads.java ├── search ├── BinarySearch.java └── Search.java ├── sort ├── HeapSort.java ├── InsertionSort.java ├── MergeSort.java ├── QuickSort.java └── Solution.java ├── stack └── Stack.java └── tree ├── BST.java ├── Node.java └── Tree.java /README.md: -------------------------------------------------------------------------------- 1 | # Java - My cheatsheet 2 | 3 | #### Table of Contents 4 | 1. [OOP concepts](#oop-concepts) 5 | 2. [Data Structures](#data-structures) 6 | - [StringBuffer, StringBuilder and String](#string) 7 | - [ArrayList v/s LinkedList](#listcomp) 8 | - [Stack v/s Heap](#stackheap) 9 | - [HashSet v/s TreeSet](#set) 10 | 3. [Access Modifiers](#access-modifiers) 11 | 4. [Comparable v/s Comparator](#comp) 12 | 5. [Abstract class v/s Interface](#absIn) 13 | 6. [final, finally, finalize](#final) 14 | 7. [Threads](#thread) 15 | 16 | 17 | 18 | #### OOP concepts 19 | 20 | | | | 21 | | ------------- |:-------------| 22 | | Encapsulation | Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. | 23 | | Abstraction | Abstraction refers to the act of representing essential features without including the background details or explanations. Showing the functionality but hiding the implementation. | 24 | | Polymorphism | "one interface, many implementations." | 25 | |Inheritance|extending the properties of a parent class.| 26 | 27 | 28 | 29 | #### Data Structures 30 | 31 | | | | 32 | | ------------- |:-------------| 33 | |HashMap|There can only be one null key in HashMap. Buckets stored as linked list. What if when two different keys have the same hashcode ? If there are more than one object mapped to the same hash value, we traverse through linked list, comparing keys in each entries using keys.equals() until it return true. Then the corresponding entry object Value is returned. In case we have to do a deep comparison of the fields, we override equals method.| 34 | |HashSet|Uses hashmap internally to maintain the uniqueness. Override equals method to do a deep comparison of each of the attributes.| 35 | |Vector|Used when you don’t know what type of objects will be inserted. Initial capacity and increment factor when resized upward.| 36 | |String/StringBuffer/StringBuilder| ![Image of String](http://s31.postimg.org/cywme34wr/string.png)| 37 | |ArrayList v/s LinkedList|![List Implementations](http://s31.postimg.org/xjksltokb/list.png)| 38 | |**Stack**|**Heap**| 39 | |stores temporary variables by each function. On function exit, values are popped out and memory is freed|stores objects created during runtime. When the function exits, reference is lost but the memory is not freed yet. Garbage collector does the work| 40 | |Fast access as stored sequentially.|Slow access because have to follow links.| 41 | |Has size limits. Might cause stackoverflow error when the function goes into infinite recursion.|No size limits, but sometimes might run out of Heapspace if no memory is free to be allocated.| 42 | |Memory automatically managed|Not managed automatically. | 43 | |**Hashset**|**Treeset**| 44 | |Not ordered|Ordered| 45 | |Null value allowed|Null value not allowed| 46 | |Performance - O(1)|Performance- log(n)| 47 | |Implements Hashmap|Implements Treemap| 48 | 49 | 50 | 51 | 52 | 53 | #### Access Modifiers 54 | 55 | ![Access Modifiers](http://s31.postimg.org/h9hrgg7mj/accessmodi.png) 56 | 57 | 58 | 59 | #### Comparable and Comparator 60 | 61 | ![CompAndComp](http://img.ctrlv.in/img/16/04/24/571c5a979542c.png) 62 | 63 | 64 | 65 | #### Abstract Class v/s Interface 66 | 67 | ![Abstract Class v/s Interface](http://s31.postimg.org/5p6yojue3/abstract_Interface.png) 68 | 69 | 70 | 71 | #### final, finally and finalize 72 | 73 | **final** - to make an object immutable, to prevent a method from being overridden, to prevent a class from being inherited. 74 | 75 | **finally** - always called after try catch 76 | 77 | **finalize** - called before freeing the object by garbage collector. 78 | 79 | 80 | 81 | 82 | #### Threads 83 | ![Thread](http://s31.postimg.org/bvn5qt2u3/thread.png) 84 | 85 | References: 86 | 87 | 1. http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html 88 | 2. http://stackoverflow.com/questions/215497/difference-among-public-default-protected-and-private 89 | 3. http://www.java2blog.com/2013/02/difference-between-comparator-and.html 90 | 91 | Useful links: 92 | 93 | 1. http://bigocheatsheet.com/ 94 | 2. http://www.buggybread.com/2015/01/java-interview-questions-and-answers.html 95 | 3. http://www.buggybread.com/2013/09/java-online-practice-tests.html 96 | 4. https://sites.google.com/site/steveyegge2/five-essential-phone-screen-questions 97 | -------------------------------------------------------------------------------- /src/com/practice/CommonData.java: -------------------------------------------------------------------------------- 1 | package com.practice; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * Created by shruthi on 29/11/15. 7 | */ 8 | public class CommonData { 9 | public static int[] array = { 1, 2, 3, 4, 6, 7, 8, 9, 10 }; 10 | public static int[] unsorted = { 2, 3, 1, 4, 11, 453, 464, 234, 13, 7, 14, 11 | 9, 10 }; 12 | 13 | public static int[] getUnsortedArray(int size) { 14 | Random rand = new Random(); 15 | unsorted = new int[size]; 16 | for (int i = 0; i < size; i++) { 17 | unsorted[i] = rand.nextInt(100); 18 | } 19 | return unsorted; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/practice/DynamicProgramming.java: -------------------------------------------------------------------------------- 1 | package com.practice; 2 | 3 | public class DynamicProgramming { 4 | 5 | public static void main(String[] args) { 6 | int[] ints = {1, 3, 2}; 7 | System.out.println(shortestPathToSum(ints, 8+1)); 8 | } 9 | 10 | public static int findCloserSum(int[] a, int k) { 11 | int min = minimum(a); 12 | int[] M = new int[k]; 13 | for (int i = 0; i < min; i++) { 14 | M[i] = 0; 15 | } 16 | for (int sum = min; sum < k; sum++) { 17 | int max = Integer.MIN_VALUE; 18 | for (int i : a) { 19 | if (i <= sum) { 20 | int s = i + M[sum - i]; 21 | if (s > max) 22 | max = s; 23 | if (max == sum) { 24 | break; 25 | } 26 | } 27 | } 28 | M[sum] = max; 29 | } 30 | return M[k - 1]; 31 | } 32 | 33 | public static int shortestPathToSum(int[] a, int k) { 34 | int min = minimum(a); 35 | if (k < min) 36 | return -1; 37 | int[] SP = new int[k]; 38 | for (int i = 0; i < k; i++) { 39 | SP[i] = 999; 40 | } 41 | for (int i = 0; i < a.length; i++) { 42 | if (a[i] < k) 43 | SP[a[i]] = 1; 44 | } 45 | for (int sum = min; sum < k; sum++) { 46 | for (int i : a) { 47 | if (i <= sum) { 48 | if (SP[sum - i] != 999) { 49 | if (SP[sum - i] + SP[i] < SP[sum]) { 50 | SP[sum] = SP[sum - i] + SP[i]; 51 | } 52 | } 53 | } 54 | } 55 | } 56 | return SP[k - 1]; 57 | } 58 | 59 | public static int minimum(int[] a) { 60 | int min = Integer.MAX_VALUE; 61 | for (int i : a) 62 | if (i < min) 63 | min = i; 64 | return min; 65 | } 66 | 67 | public static int coinChange(int[] a, int k) { 68 | int min = minimum(a); 69 | int[] W = new int[k]; 70 | for (int i = 0; i < min; i++) 71 | W[i] = 0; 72 | 73 | for (int sum = min; sum < k; sum++) { 74 | for (int i : a) { 75 | if (i == sum) { 76 | W[sum] += 1; 77 | continue; 78 | } 79 | if (i < sum && W[sum - i] != 0) { 80 | W[sum] += 1 + W[i]; 81 | } 82 | } 83 | } 84 | return W[k - 1]; 85 | } 86 | 87 | 88 | } -------------------------------------------------------------------------------- /src/com/practice/Reflections.java: -------------------------------------------------------------------------------- 1 | package com.practice; 2 | 3 | import com.practice.arrays.GeeksForGeeks; 4 | import com.practice.tree.Tree; 5 | 6 | import java.lang.reflect.Method; 7 | import java.lang.reflect.Parameter; 8 | 9 | /** 10 | * Created by shruthi on 11/4/16. 11 | */ 12 | public class Reflections { 13 | public static void main(String[] args) throws ClassNotFoundException { 14 | Method[] declaredMethods = Tree.class.getDeclaredMethods(); 15 | System.out.println("###Tree"); 16 | for (Method m : declaredMethods) { 17 | System.out.println("#####"+m.getName()); 18 | Parameter[] parameters = m.getParameters(); 19 | System.out.print("\t"); 20 | for (Parameter p : parameters) { 21 | String type; 22 | if(p.getType().toString().contains("class")){ 23 | type = Class.forName(p.getType().toString().split(" ")[1]).getTypeName(); 24 | } else{ 25 | type = p.getType().getName(); 26 | } 27 | System.out.print(type + " " + p.getName() + ", "); 28 | } 29 | System.out.println(); 30 | System.out.println(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/practice/arrays/GeeksForGeeks.java: -------------------------------------------------------------------------------- 1 | package com.practice.arrays; 2 | 3 | import com.practice.CommonData; 4 | 5 | import java.util.*; 6 | 7 | public class GeeksForGeeks { 8 | 9 | static int[] array = CommonData.array; 10 | static int[] d; 11 | 12 | public static void main(String[] args) { 13 | /*int[][] a = {{1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1}}; 14 | System.out.println(friendCircle(a));*/ 15 | getSpecialPageNumbers(new int[]{4, 2, 6, 1, 10}, 5, 3); 16 | } 17 | 18 | public static void getSpecialPageNumbers(int[] problems, int n, int k) { 19 | int pageNumber = 1; 20 | int chap = 1; 21 | int special = 0; 22 | while (chap <= n) { 23 | int end = 1; 24 | int start = 1; 25 | 26 | while (end < problems[chap - 1]) { 27 | start = end; 28 | if (end + k - 1 <= problems[chap - 1]) { 29 | end = end + k - 1; 30 | } else { 31 | end = problems[chap - 1]; 32 | } 33 | if (pageNumber >= start && pageNumber <= end) { 34 | special++; 35 | } 36 | pageNumber++; 37 | } 38 | chap++; 39 | } 40 | System.out.println(special); 41 | } 42 | 43 | public static int friendCircle(int[][] matrix) { 44 | boolean[] visited = new boolean[matrix.length]; 45 | int circles = 0; 46 | 47 | for (int i = 0; i < matrix.length; i++) { 48 | if (!visited[i]) { 49 | circles++; 50 | int j = i + 1; 51 | while (j < matrix[0].length && matrix[i][j] == 1) { 52 | visited[j] = true; 53 | i = j; 54 | j++; 55 | } 56 | } 57 | } 58 | 59 | return circles; 60 | } 61 | 62 | public static int nCents(int n) { 63 | if (d[n] != 0) 64 | return d[n]; 65 | 66 | int tf = 0, ten = 0, five = 0, one = 0; 67 | tf = n - 25 >= 0 ? nCents(n - 25) : 0; 68 | ten = n - 10 >= 0 ? nCents(n - 10) : 0; 69 | five = n - 5 >= 0 ? nCents(n - 5) : 0; 70 | one = n - 1 >= 0 ? nCents(n - 1) : 0; 71 | System.out.println(one + ", " + five + ", " + ten + ", " + tf); 72 | d[n] = one + five + ten + tf; 73 | return d[n]; 74 | } 75 | 76 | /** 77 | * Implement an algorithm to print all valid (e.g., properly opened and closed) 78 | * combinations of n-pairs of parentheses. 79 | * 80 | * @param n 81 | * @return 82 | */ 83 | public static List parenthesize(int n) { 84 | List temp = new ArrayList<>(); 85 | if (n == 1) { 86 | temp.add("()"); 87 | return temp; 88 | } 89 | List parenthesize = parenthesize(n - 1); 90 | 91 | for (String i : parenthesize) { 92 | temp.add("(" + i + ")"); 93 | if (!("()" + i).equals(i + "()")) 94 | temp.add("()" + i); 95 | temp.add(i + "()"); 96 | } 97 | return temp; 98 | } 99 | 100 | /** 101 | * Write a method to compute all permutations of a string 102 | * 103 | * @param index 104 | * @param s 105 | * @return 106 | */ 107 | public static List permutationsOfString(int index, String s) { 108 | List temp = new ArrayList<>(); 109 | if (s.length() - index == 1) { 110 | temp.add(s.substring(index)); 111 | return temp; 112 | } 113 | String current = s.charAt(index) + ""; 114 | List permutation = permutationsOfString(index + 1, s); 115 | List master = new ArrayList<>(); 116 | master.add(current); 117 | for (String p : permutation) { 118 | master.add(p); 119 | master.add(p + current); 120 | master.add(current + p); 121 | } 122 | return master; 123 | } 124 | 125 | /** 126 | * Write a method that returns all subsets of a set. 127 | * 128 | * @param index 129 | * @param set 130 | * @return Returns all the subsets of a set. 131 | */ 132 | public static List subset(int index, List set) { 133 | List temp = new ArrayList<>(); 134 | if (set.size() - index == 1) { //until one element is left in the subset 135 | List letssee = new ArrayList<>(); 136 | temp.add(set.get(index)); 137 | letssee.add(temp); 138 | return letssee; 139 | } 140 | int i = set.get(index); //get the current number. Find the smaller subsets and then add i to all the subsets 141 | List subsets = subset(index + 1, set); 142 | List allSub = new ArrayList<>(); 143 | temp.add(i); 144 | allSub.add(temp); 145 | for (List l : subsets) { 146 | allSub.add(l); 147 | temp = new ArrayList<>(); 148 | temp.addAll(l); 149 | temp.add(i); 150 | allSub.add(temp); 151 | } 152 | 153 | return allSub; 154 | } 155 | 156 | /** 157 | * Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can 158 | * only move in two directions: right and down. How many possible paths are there for 159 | * the robot? 160 | * 161 | * @param row 162 | * @param col 163 | * @param gridSize 164 | * @return 165 | */ 166 | static int totalPaths(int row, int col, int gridSize) { 167 | if (row == gridSize && col == gridSize) 168 | return 1; 169 | int right = 0, down = 0; 170 | if (col + 1 <= gridSize) { 171 | right = totalPaths(row, col + 1, gridSize); 172 | } 173 | if (row + 1 <= gridSize) { 174 | down = totalPaths(row + 1, col, gridSize); 175 | } 176 | return right + down; 177 | } 178 | 179 | /** 180 | * Write a method to generate the nth Fibonacci number. 181 | * 182 | * @param n 183 | * @return 184 | */ 185 | static int fib(int n) { 186 | if (n == 0) 187 | return 0; 188 | if (n == 1) 189 | return 1; 190 | int prev2 = 0; 191 | int prev1 = 1; 192 | int i = 2; 193 | while (i != n) { 194 | int result = prev2 + prev1; 195 | prev2 = prev1; 196 | prev1 = result; 197 | i++; 198 | } 199 | return prev1 + prev2; 200 | } 201 | 202 | /** 203 | * Comparator 204 | * 205 | * @param listToSortAlphabetically 206 | */ 207 | public static void writingComparator(List listToSortAlphabetically) { 208 | System.out.println(listToSortAlphabetically.toString()); 209 | Comparator sortAlphabetically = new Comparator() { 210 | 211 | @Override 212 | public int compare(String o1, String o2) { 213 | int i = 0; 214 | 215 | System.out.println(o1 + "," + o2); 216 | o1 = o1.toLowerCase(); 217 | o2 = o2.toLowerCase(); 218 | int maxlen = o1.length() > o2.length() ? o2.length() : o1 219 | .length(); 220 | while ((o1.charAt(i) == o2.charAt(i)) && i < maxlen - 1) { 221 | i++; 222 | } 223 | return o1.charAt(i) >= o2.charAt(i) ? 1 : -1; 224 | } 225 | }; 226 | 227 | Collections.sort(listToSortAlphabetically, sortAlphabetically); 228 | System.out.println(listToSortAlphabetically.toString()); 229 | } 230 | 231 | /** 232 | * From intArray given integer array values, find if intArray Total value is possible 233 | * or not? The numbers in the array can be used more than once. 234 | * 235 | * @param intArray 236 | * @param sum 237 | * @return 238 | */ 239 | public static boolean isTotalPossible(int[] intArray, int sum) { 240 | 241 | int i = 0; 242 | int min = 999; 243 | for (int s : intArray) { 244 | if (s < min) { 245 | min = s; 246 | } 247 | if (s == sum) { 248 | return true; 249 | } 250 | } 251 | while (i != intArray.length) { 252 | if (sum - intArray[i] == 0) { 253 | return true; 254 | } 255 | if (sum - intArray[i] >= min) { 256 | System.out.println(intArray[i] + ", " + (sum - intArray[i])); 257 | return isTotalPossible(intArray, sum - intArray[i]); 258 | } else { 259 | i++; 260 | } 261 | } 262 | return false; 263 | } 264 | 265 | public static void dotProductOfSparseVectors(String[] input) { 266 | int m = Integer.parseInt(input[0].split(" ")[0]); 267 | int n = Integer.parseInt(input[0].split(" ")[1]); 268 | int sum = 0; 269 | HashMap dotproduct = new HashMap<>(); 270 | for (int i = 1; i <= m; i++) { 271 | String g = input[i]; 272 | dotproduct.put(Integer.parseInt(g.split(" ")[0]), 273 | Integer.parseInt(g.split(" ")[1])); 274 | } 275 | for (int i = m + 1; i <= m + n; i++) { 276 | String g = input[i]; 277 | int l = Integer.parseInt(g.split(" ")[0]); 278 | int k = Integer.parseInt(g.split(" ")[1]); 279 | if (dotproduct.containsKey(l)) { 280 | sum += dotproduct.get(l) * k; 281 | } 282 | 283 | } 284 | System.out.println("Dotproduct: " + sum); 285 | } 286 | 287 | /** 288 | * You have an array with words. Print them by anagrams groups 289 | * 290 | * @param words 291 | */ 292 | public static void groupByAnagrams(String[] words) { 293 | HashMap> anagrams = new HashMap<>(); 294 | for (String i : words) { 295 | char[] c = i.toCharArray(); 296 | Arrays.sort(c); 297 | String key = new String(c); 298 | if (anagrams.containsKey(key)) { 299 | anagrams.get(key).add(i); 300 | } else 301 | anagrams.put(key, new ArrayList<>(Arrays.asList(i))); 302 | } 303 | for (String i : anagrams.keySet()) { 304 | System.out.println("i: " + i); 305 | 306 | for (String j : anagrams.get(i)) 307 | System.out.print(": " + j); 308 | 309 | System.out.println(); 310 | } 311 | } 312 | 313 | /** 314 | * distinct pairs that add up to kSum 315 | * 316 | * @param intArray 317 | * @param kSum 318 | */ 319 | public static void distinctPairsToK(int[] intArray, int kSum) { 320 | HashSet set = new HashSet<>(); 321 | for (int i : intArray) { 322 | set.add(i); 323 | } 324 | Iterator iterator = set.iterator(); 325 | while (iterator.hasNext()) { 326 | Integer i = iterator.next(); 327 | if (set.contains(kSum - i)) { 328 | System.out.println(i + "," + (kSum - i)); 329 | iterator.remove(); 330 | } 331 | } 332 | 333 | } 334 | 335 | /** 336 | * @param a 337 | */ 338 | public static void largestContiguousSubArray(int[] a) { 339 | int prevMax = 0; 340 | int sum = 0; 341 | int startIndex = -1; 342 | int start = -1; 343 | int endIndex = -1; 344 | for (int i = 0; i < a.length; i++) { 345 | if (sum + a[i] < 0) { //reset the sum to zero if negative encountered 346 | sum = 0; 347 | startIndex = i + 1; 348 | } else { 349 | sum = sum + a[i]; //else sum it up 350 | if (sum > prevMax) { 351 | start = startIndex; 352 | prevMax = sum; 353 | endIndex = i; 354 | } 355 | } 356 | } 357 | System.out.println(start + ":" + endIndex); 358 | } 359 | 360 | public static void findMissingNumber(int[] a) { 361 | int n = a.length + 1; 362 | int sum = n * (n + 1) / 2; 363 | for (int i : a) { 364 | sum = sum - i; 365 | } 366 | System.out.println("Missing number: " + sum); 367 | } 368 | 369 | 370 | // Find subarray with given sum 371 | public static void subArraySum(int[] a, int k) { 372 | int first = a[0]; 373 | int start = 0; 374 | int sum = first; 375 | int end = 0; 376 | for (int i = 1; i < a.length; i++) { 377 | end = i; 378 | 379 | if (sum == k) { 380 | System.out.println(start + ":" + end); 381 | break; 382 | } else if (sum > k) { 383 | sum = sum - first; 384 | start = start + 1; 385 | first = a[start]; 386 | } else 387 | sum = sum + a[i]; 388 | } 389 | } 390 | 391 | public static int kthLargest(int[] array, int k) { 392 | int p = 0; 393 | int r = array.length - 1; 394 | int q = -1; 395 | while (k != 0) { 396 | q = partition(p, r); 397 | System.out.println(k + ":" + q); 398 | if (k == q) 399 | return array[k]; 400 | else if (k < q) { 401 | r = q - 1; 402 | } else if (k > q) { 403 | k = k - (q - p + 1); 404 | p = q + 1; 405 | } 406 | } 407 | return array[q]; 408 | } 409 | 410 | public static int partition(int p, int r) { 411 | Random rand = new Random(); 412 | 413 | int index = rand.nextInt(r); 414 | swap(index, r); 415 | int pivot = array[r]; 416 | int i = p - 1; 417 | int j = 0; 418 | while (j != r) { 419 | if (array[j] < pivot) { 420 | i += 1; 421 | swap(i, j); 422 | } 423 | j++; 424 | } 425 | swap(i + 1, array[r]); 426 | return i + 1; 427 | } 428 | 429 | public static void swap(int i, int j) { 430 | int temp = array[i]; 431 | array[i] = array[j]; 432 | array[j] = temp; 433 | } 434 | 435 | /** 436 | * https://www.interviewcake.com/question/python/stock-price 437 | * 438 | * @param stockPrices 439 | * @return 440 | */ 441 | public static int maximumProfit(int[] stockPrices) { 442 | int sum = 0; 443 | int maxSum = -999; 444 | int j = 1; 445 | int len = stockPrices.length; 446 | while (j < len) { 447 | sum = sum + (stockPrices[j] - stockPrices[j - 1]); 448 | if (sum < 0) { 449 | sum = 0; 450 | } else if (sum > maxSum) { 451 | maxSum = sum; 452 | } 453 | j++; 454 | } 455 | if (maxSum < 0) 456 | return 0; 457 | return maxSum; 458 | } 459 | } 460 | -------------------------------------------------------------------------------- /src/com/practice/arrays/Numbers.java: -------------------------------------------------------------------------------- 1 | package com.practice.arrays; 2 | 3 | import java.util.HashMap; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | public class Numbers { 8 | 9 | static int distributeCandy(int[] score) { 10 | // https://www.hackerrank.com/challenges/candies 11 | 12 | int[] candy = new int[score.length]; 13 | int count = 1; 14 | candy[0] = 1; 15 | for (int i = 1; i < score.length; i++) { 16 | if (score[i] > score[i - 1]) 17 | candy[i] = candy[i - 1] + 1; 18 | else if (score[i] <= score[i - 1]) 19 | candy[i] = 1; 20 | } 21 | for (int i = score.length - 1; i > 0; i--) { 22 | if (score[i] < score[i - 1] && candy[i] >= candy[i - 1]) 23 | candy[i - 1] = candy[i] + 1; 24 | } 25 | int sum = 0; 26 | for (int i = 0; i < candy.length; i++) 27 | sum += candy[i]; 28 | return sum; 29 | } 30 | 31 | enum Color { 32 | Red("Red", 255, 0, 0), 33 | Green("Green", 0, 255, 0), 34 | Blue("Blue", 0, 0, 255), 35 | Black("Black", 0, 0, 0), 36 | White("White", 255, 255, 255); 37 | 38 | String color; 39 | int r; 40 | int g; 41 | int b; 42 | 43 | Color(String color, int r, int g, int b) { 44 | this.color = color; 45 | this.r = r; 46 | this.g = g; 47 | this.b = b; 48 | } 49 | 50 | } 51 | 52 | public static void main(String[] args) { 53 | String[] s = {"0000000011111111111111111"}; 54 | ClosestColor(s); 55 | } 56 | static String[] ClosestColor(String[] hexcodes) { 57 | String[] output = new String[hexcodes.length]; 58 | int count=0; 59 | for(String hexCode: hexcodes){ 60 | int r = Integer.parseInt(hexCode.substring(0, 8), 2); 61 | int g = Integer.parseInt(hexCode.substring(8, 16), 2); 62 | int b = Integer.parseInt(hexCode.substring(16, 24), 2); 63 | int[] array = {r,g,b}; 64 | output[count++] = euclidean(array); 65 | } 66 | System.out.println(isMatches("000.255.244.54")); 67 | return output; 68 | } 69 | 70 | static String euclidean(int[] color) { 71 | HashMap list = new HashMap<>(); 72 | Color[] values = Color.values(); 73 | double min = Integer.MAX_VALUE; 74 | Color fi = null; 75 | for (Color arr : values) { 76 | double sum = 0; 77 | sum += Math.pow((color[0] - arr.r), 2); 78 | sum += Math.pow((color[1] - arr.g), 2); 79 | sum += Math.pow((color[2] - arr.b), 2); 80 | sum = Math.sqrt(sum); 81 | if(!list.containsKey((int)sum)){ 82 | list.put((int)sum, 0); 83 | } 84 | list.put((int)sum, list.get((int)sum)+1); 85 | 86 | if (sum < min) { 87 | fi = arr; 88 | min = sum; 89 | } 90 | } 91 | 92 | if(list.get((int)min)>1) 93 | return "Ambiguous"; 94 | return fi.color; 95 | } 96 | 97 | static boolean isMatches(String ip){ 98 | String IPADDRESS_PATTERN = 99 | "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 100 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 101 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + 102 | "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; 103 | Pattern pattern = Pattern.compile(IPADDRESS_PATTERN); 104 | Matcher matcher = pattern.matcher(ip); 105 | return matcher.matches(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/com/practice/arrays/README.md: -------------------------------------------------------------------------------- 1 | ###GeeksForGeeks 2 | #####writingComparator 3 | java.util.List listToSortAlphabetically, 4 | 5 | #####totalPaths 6 | int row, int col, int gridSize, 7 | 8 | #####fib 9 | int n, 10 | 11 | #####isTotalPossible 12 | int[] intArray, int sum, 13 | 14 | #####dotProductOfSparseVectors 15 | java.lang.String[] input, 16 | 17 | #####groupByAnagrams 18 | java.lang.String[] words, 19 | 20 | #####distinctPairsToK 21 | int[] intArray, int kSum, 22 | 23 | #####largestContiguousSubArray 24 | int[] a, 25 | 26 | #####findMissingNumber 27 | int[] a, 28 | 29 | #####subArraySum 30 | int[] a, int k, 31 | 32 | #####kthLargest 33 | int[] array, int k, 34 | 35 | #####partition 36 | int p, int r, 37 | 38 | #####maximumProfit 39 | int[] stockPrices, 40 | 41 | #####swap 42 | int i, int j, 43 | -------------------------------------------------------------------------------- /src/com/practice/arrays/Strings.java: -------------------------------------------------------------------------------- 1 | package com.practice.arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | 6 | public class Strings { 7 | public static void main(String[] args) { 8 | System.out.println(isPalindromeAvailable("aaabbbb")); 9 | } 10 | 11 | public static String isPalindromeAvailable(String s) { 12 | char[] chars = s.toCharArray(); 13 | Arrays.sort(chars); 14 | StringBuilder sb = new StringBuilder(); 15 | int index = 0; 16 | char prev = chars[0]; 17 | for (char i : chars) { 18 | if (i == prev) { 19 | sb.insert(index++, i); 20 | continue; 21 | } 22 | prev = i; 23 | index = sb.length() / 2; 24 | sb.insert(index, i); 25 | } 26 | return sb.toString(); 27 | } 28 | 29 | public static boolean canAPalindromeMade(String s) { 30 | HashMap h = new HashMap(); 31 | for (char c : s.toCharArray()) { 32 | if (h.containsKey(c)) { 33 | h.put(c, h.get(c) + 1); 34 | } else 35 | h.put(c, 1); 36 | 37 | } 38 | boolean oneFound = false; 39 | if (s.length() % 2 == 0) { 40 | for (char i : h.keySet()) { 41 | if (h.get(i) % 2 != 0) { 42 | if (!oneFound) { 43 | oneFound = true; 44 | } else { 45 | return false; 46 | } 47 | } 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | //Sliding window 54 | public static String longestUniqueSubstring(String s) { 55 | //abcae 56 | String result = ""; 57 | HashMap map = new HashMap<>(); 58 | int i = 0, j = 0, n = s.length(); 59 | String temp = ""; 60 | while (j != n) { 61 | char key = s.charAt(j); 62 | if (map.containsKey(key)) { 63 | i = map.get(key) + 1; 64 | } 65 | if (j + 1 > n) 66 | temp = s.substring(i); 67 | else 68 | temp = s.substring(i, j + 1); 69 | if (temp.length() > result.length()) 70 | result = temp; 71 | map.put(key, j); 72 | j++; 73 | } 74 | 75 | return result; 76 | } 77 | 78 | public static int deletion(String s) { 79 | int deletions = 0; 80 | int i = 0; 81 | int len = s.length(); 82 | char prev = s.charAt(i); 83 | i++; 84 | while (i < len) { 85 | 86 | if (s.charAt(i) == prev) { 87 | deletions++; 88 | i++; 89 | continue; 90 | } 91 | prev = s.charAt(i); 92 | i++; 93 | 94 | } 95 | return deletions; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/com/practice/graphs/Dijkstra.java: -------------------------------------------------------------------------------- 1 | package com.practice.graphs; 2 | 3 | /** 4 | * Created by shruthi on 15/4/16. 5 | */ 6 | public class Dijkstra { 7 | int[] distance; 8 | boolean[] visited; 9 | 10 | 11 | public void shortestPath(int[][] adj, int src) { 12 | 13 | for (int v = 0; v < adj.length; v++) { 14 | distance[v] = Integer.MAX_VALUE; 15 | visited[v] = false; 16 | } 17 | distance[src] = 0; 18 | 19 | for (int v = 0; v < adj.length; v++) { 20 | int minVertex = minimum(); 21 | visited[minVertex] = true; 22 | for (int u = 0; u < adj[0].length; u++) { 23 | if (!visited[u] && adj[v][u] != 0 && distance[v] + adj[v][u] < distance[u]) { 24 | distance[u] = distance[v] + adj[v][u]; 25 | } 26 | } 27 | } 28 | } 29 | 30 | public int minimum() { 31 | int min = Integer.MAX_VALUE; 32 | int minVertex = -1; 33 | for (int v = 0; v < visited.length; v++) { 34 | if (!visited[v] && distance[v] < min) { 35 | min = distance[v]; 36 | minVertex = v; 37 | } 38 | } 39 | return minVertex; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/com/practice/graphs/Edge.java: -------------------------------------------------------------------------------- 1 | package com.practice.graphs; 2 | 3 | /** 4 | * Created by shruthi on 2/4/16. 5 | */ 6 | public class Edge { 7 | Vertex to; 8 | Vertex from; 9 | int weight; 10 | 11 | public Edge(Vertex u, Vertex v) { 12 | this.from = u; 13 | this.to = v; 14 | } 15 | 16 | public Vertex otherEnd(Vertex u) { 17 | if (from == u) { 18 | return to; 19 | } else { 20 | return from; 21 | } 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return String.format("(%s, %s)",from.data, to.data); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/practice/graphs/Graph.java: -------------------------------------------------------------------------------- 1 | package com.practice.graphs; 2 | 3 | import java.util.*; 4 | 5 | public class Graph { 6 | int numberOfNodes = 0; 7 | public List verts; 8 | 9 | Graph(int size) { 10 | numberOfNodes = size; 11 | verts = new ArrayList<>(size + 1); 12 | verts.add(0, new Vertex(0)); 13 | for (int i = 1; i <= size; i++) 14 | verts.add(i, new Vertex(i)); 15 | } 16 | 17 | private static void DFS(Vertex v, Stack s, Stack output) { 18 | s.push(v); 19 | v.visited = true; 20 | 21 | for (Edge e : v.links) { 22 | Vertex u = e.otherEnd(v); 23 | if (!u.visited) { 24 | DFS(u, s, output); 25 | } 26 | } 27 | Vertex u = s.pop(); 28 | u.visited = true; 29 | if (u.data != 0) 30 | output.push(u); 31 | 32 | } 33 | 34 | /*public static int BFS(Graph g, Queue verQueue) { 35 | int count = 0; 36 | while (!verQueue.isEmpty()) { 37 | Vertex u = verQueue.remove(); 38 | System.out.print(u.data + ", "); 39 | count++; 40 | for (Edge e : u.links) { 41 | Vertex v = e.otherEnd(u); 42 | if (!v.visited) { 43 | v.visited = true; 44 | verQueue.add(v); 45 | } 46 | } 47 | } 48 | System.out.println(); 49 | return 0; 50 | }*/ 51 | 52 | void addEdge(int a, int b, int weight) { 53 | Vertex u = verts.get(a); 54 | Vertex v = verts.get(b); 55 | Edge e = new Edge(u, v); 56 | e.weight = weight; 57 | System.out.print(e.toString() + "; "); 58 | u.links.add(e); 59 | v.links.add(e); 60 | u.degree++; 61 | v.degree++; 62 | } 63 | 64 | public static Graph createGraph(Scanner in) { 65 | int n = in.nextInt(); // number of vertices in the graph 66 | int m = in.nextInt(); // number of edges in the graph 67 | Graph g = new Graph(n); 68 | System.out.println("Vertices: " + g.toString()); 69 | System.out.println("Edges: "); 70 | for (int i = 0; i < m; i++) { 71 | int u = in.nextInt(); // tail 72 | int v = in.nextInt(); // head 73 | int w = in.nextInt(); //weight 74 | g.addEdge(u, v, w); 75 | } 76 | in.close(); 77 | return g; 78 | } 79 | 80 | @Override 81 | public String toString() { 82 | StringBuilder sb = new StringBuilder(); 83 | for (Vertex v : verts) { 84 | if (v.data != 0) 85 | sb.append(v.data + ", "); 86 | } 87 | return sb.toString(); 88 | } 89 | 90 | void resetParentNull() { 91 | for (Vertex v : verts) { 92 | v.parent = null; 93 | } 94 | } 95 | 96 | void resetVisited() { 97 | for (Vertex v : verts) { 98 | v.visited = false; 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/com/practice/graphs/MST.java: -------------------------------------------------------------------------------- 1 | package com.practice.graphs; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.util.*; 6 | 7 | /** 8 | * Created by shruthi on 10/4/16. 9 | */ 10 | public class MST { 11 | 12 | public static void main(String[] args) throws FileNotFoundException { 13 | Graph g = Graph.createGraph(new Scanner(new File("src/com/practice/graphs/edges.txt"))); 14 | Vertex src = g.verts.get(new Random().nextInt(g.verts.size())); 15 | System.out.println(); 16 | System.out.println("Source: "+src.data); 17 | MSTUsingPrims(g, src); 18 | 19 | } 20 | 21 | public static int MSTUsingPrims(Graph g, Vertex src) { 22 | int wmst = 0; 23 | g.resetVisited(); 24 | g.resetParentNull(); 25 | src.visited = true; 26 | src.distance = 0; 27 | int size = src.links.size(); 28 | PriorityQueue pq = new PriorityQueue<>(new Comparator() { 29 | @Override 30 | public int compare(Edge e1, Edge e2) { 31 | 32 | return e1.weight - e2.weight; 33 | } 34 | }); 35 | 36 | for (int i = 0; i < size; i++) { 37 | pq.add(src.links.get(i)); 38 | } 39 | 40 | ArrayList mstE = new ArrayList<>(); 41 | 42 | while (!pq.isEmpty() && mstE.size() != (g.verts.size() - 2)) { 43 | Edge e = pq.remove(); 44 | if (e != null) { 45 | Vertex u = e.from.visited ? e.to : e.from; 46 | if (!u.visited) { 47 | mstE.add(e); 48 | u.visited = true; 49 | u.parent = e.otherEnd(u); 50 | wmst = wmst + e.weight; 51 | 52 | for (Edge ed : u.links) { 53 | if (!ed.otherEnd(u).visited) 54 | pq.add(ed); 55 | } 56 | } 57 | } 58 | } 59 | 60 | System.out.println("MST weight: " + wmst); 61 | for(Edge e: mstE){ 62 | System.out.println(e.toString()); 63 | } 64 | return wmst; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/com/practice/graphs/Vertex.java: -------------------------------------------------------------------------------- 1 | package com.practice.graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Vertex { 7 | int data; 8 | List links = new ArrayList(); 9 | boolean visited; 10 | int degree; 11 | public int distance; 12 | public Vertex parent; 13 | 14 | public Vertex(int d){ 15 | data = d; 16 | visited = false; 17 | } 18 | public Vertex(){ 19 | 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/com/practice/graphs/edges.txt: -------------------------------------------------------------------------------- 1 | 10 16 2 | 1 2 8 3 | 1 8 4 4 | 1 6 10 5 | 2 6 7 6 | 2 3 4 7 | 2 8 9 8 | 3 6 3 9 | 3 4 3 10 | 4 7 2 11 | 4 5 25 12 | 4 6 18 13 | 5 6 2 14 | 5 7 7 15 | 7 8 3 16 | 9 7 1 17 | 9 10 1 18 | 19 | //Used for BFS and DFS 20 | 20 40 21 | 7 13 22 | 12 10 23 | 17 15 24 | 15 18 25 | 17 3 26 | 8 7 27 | 9 4 28 | 14 5 29 | 2 18 30 | 15 18 31 | 20 10 32 | 1 19 33 | 8 18 34 | 19 19 35 | 2 6 36 | 6 8 37 | 18 13 38 | 20 4 39 | 5 14 40 | 7 20 41 | 18 17 42 | 3 3 43 | 8 15 44 | 18 8 45 | 14 9 46 | 20 13 47 | 4 6 48 | 7 15 49 | 19 1 50 | 11 3 51 | 4 3 52 | 2 1 53 | 3 2 54 | 16 11 55 | 1 3 56 | 6 9 57 | 18 7 58 | 13 17 59 | 7 12 60 | 7 16 -------------------------------------------------------------------------------- /src/com/practice/hashing/MyMap.java: -------------------------------------------------------------------------------- 1 | package com.practice.hashing; 2 | 3 | import java.util.HashSet; 4 | import java.util.LinkedList; 5 | import java.util.Set; 6 | 7 | public class MyMap { 8 | float loadFactor = 0.75f; 9 | int tableSize = 30; 10 | double k; 11 | LinkedList[] keys; 12 | LinkedList[] values; 13 | Set keySet; 14 | int collisions = 0; 15 | 16 | MyMap() { 17 | init(tableSize); 18 | } 19 | 20 | MyMap(int tableSize) { 21 | this.tableSize = tableSize; 22 | init(tableSize); 23 | } 24 | 25 | public static void main(String[] args) { 26 | MyMap map = new MyMap(); 27 | String[] randomStrings = new String[]{ 28 | "yjUpRL2blq", "9xzQmsSHtm", "LoPBmuVtRZ", "Rp4yHa1tM3", "fOeZvFFUHD", "gn9m3FmV9j", "XKzuVYGtoi", "LoSi4ct40w", "d34rDrvyYL", "k19z2qROfj", "eac04pca8x", "URvxQz5hGW", "dNA42EYjlY", "19gLawNvOE", "jTkMmz8fq5", "hZeYJ6QCA3", "eSDw82pmUQ", "ZeTrpw3sqz", "ltJwvScj4N", "Rkme67RkYm"}; 29 | for (String i : randomStrings) { 30 | map.put(i, ""); 31 | } 32 | System.out.println("Number of collisions of a map with table size " + map.tableSize + " is " + map.collisions); 33 | map.print(); 34 | } 35 | 36 | protected void init(int tableSize) { 37 | this.k = 0; 38 | this.keys = new LinkedList[tableSize]; 39 | this.values = new LinkedList[tableSize]; 40 | for (int i = 0; i < tableSize; i++) { 41 | this.keys[i] = new LinkedList<>(); 42 | this.values[i] = new LinkedList<>(); 43 | } 44 | keySet = keySet(); 45 | } 46 | 47 | protected void resize() { 48 | MyMap newTable = new MyMap(tableSize * 2); 49 | Set keyS = keySet(); 50 | for (String key : keyS) { 51 | newTable.put(key, get(key)); 52 | } 53 | tableSize = tableSize * 2; 54 | keys = newTable.keys; 55 | values = newTable.values; 56 | keySet = keySet(); 57 | } 58 | 59 | public int hashFunction(String obj) { 60 | int key = 17 * 31 + obj.hashCode(); 61 | if (key < 0) 62 | key = ~key; 63 | return (key % tableSize); 64 | } 65 | 66 | public void put(String key, Object value) { 67 | int index = hashFunction(key); 68 | insert(key, value, index); 69 | } 70 | 71 | protected void insert(String key, Object value, int index) { 72 | 73 | if (!find(key)) { 74 | if (isResizeNecessary()) { 75 | resize(); 76 | } 77 | keys[index].add(key); 78 | if (keys[index].size() > 1) { 79 | collisions++; 80 | } 81 | values[index].add(keys[index].size() - 1, value); 82 | k++; 83 | keySet.add(key); 84 | } else { 85 | int indexList = keys[index].indexOf(key); 86 | values[index].set(indexList, value); 87 | } 88 | } 89 | 90 | 91 | public Object get(String key) { 92 | if (find(key)) { 93 | int index = hashFunction(key); 94 | int indexInList = keys[index].indexOf(key); 95 | return values[index].get(indexInList); 96 | } else return null; 97 | 98 | } 99 | 100 | public Set keySet() { 101 | if (keySet == null) { 102 | keySet = new HashSet<>(); 103 | for (LinkedList keyList : keys) { 104 | keySet.addAll(keyList); 105 | } 106 | } 107 | return keySet; 108 | } 109 | 110 | boolean find(String obj) { 111 | int i = hashFunction(obj); 112 | return keys[i] != null && keys[i].contains(obj); 113 | } 114 | 115 | 116 | public boolean isResizeNecessary() { 117 | double v = k / tableSize; 118 | return v > loadFactor; 119 | } 120 | 121 | public void print() { 122 | for (int j = 0; j < keys.length; j++) { 123 | LinkedList i = keys[j]; 124 | System.out.print(j + ": "); 125 | for (int index = 0; index < i.size(); index++) { 126 | System.out.print(i.get(index) + ", "); 127 | } 128 | System.out.println(); 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /src/com/practice/list/DNode.java: -------------------------------------------------------------------------------- 1 | package com.practice.list; 2 | 3 | class DNode { 4 | int data; 5 | DNode next; 6 | DNode prev; 7 | 8 | static DNode SortedInsert(DNode head, int data) { 9 | 10 | if (head == null) { 11 | head = new DNode(); 12 | head.data = data; 13 | return head; 14 | } 15 | DNode temp = head; 16 | DNode prev = null; 17 | while (temp != null && temp.data < data){ 18 | prev = temp; 19 | temp = temp.next; 20 | 21 | } 22 | DNode n = new DNode(); 23 | n.data = data; 24 | 25 | if(temp==null){ 26 | prev.next = n; 27 | n.prev = prev; 28 | return head; 29 | } 30 | 31 | if(temp.prev==null){ 32 | n.next = temp; 33 | temp.prev = n; 34 | return n; 35 | } 36 | 37 | prev.next = n; 38 | n.prev = prev; 39 | n.next = temp; 40 | temp.prev = n; 41 | 42 | return head; 43 | 44 | } 45 | 46 | public static void print(DNode h) { 47 | DNode temp = h; 48 | while (temp != null) { 49 | System.out.print(temp.data+" "); 50 | temp = temp.next; 51 | } 52 | } 53 | 54 | static DNode Reverse(DNode head) { 55 | if(head == null) 56 | return null; 57 | if(head.next==null) 58 | return head; 59 | 60 | while(head.next!=null){ 61 | head = head.next; 62 | DNode temp = head.prev; 63 | head.prev = head.next; 64 | head.next = temp; 65 | 66 | } 67 | 68 | return head; 69 | } 70 | } -------------------------------------------------------------------------------- /src/com/practice/list/Main.java: -------------------------------------------------------------------------------- 1 | package com.practice.list; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | 9 | //forward case addition of linked list 10 | //partition on x 11 | 12 | public class Main { 13 | // static int[] data = { 2, 2, 2, 3, 2, 12, 4, 6, 2, 2, 3}; 14 | static int[] data = {1, 8, 6, 3, 2, 12, 4, 5, 7, 9}; 15 | static Node head = linkedListDemo(data); 16 | 17 | public static void main(String[] args) { 18 | DNode head1 = null; 19 | for(int i: data){ 20 | head1 = DNode.SortedInsert(head1, i); 21 | } 22 | 23 | DNode.print(head1); 24 | int[] arr = {3,1,2,6,5,12}; 25 | // addLinkedLists(); 26 | // initiateDelete(3); 27 | // detectLoopStartPoint(head); 28 | //reverseLinkedList(head); 29 | // listPalindrome(linkedListDemo(a)); 30 | //traverseRecursive(head); 31 | //findMiddleNode(head.next.next, head); 32 | // head.printList(head); 33 | // Node temp = head.deleteFromList(head, 2); 34 | // head.printList(temp); 35 | } 36 | private static int numberOfComponents(int[] arr, Node head){ 37 | int conn=0; 38 | 39 | return conn; 40 | } 41 | 42 | private static void findMiddleNode(Node fast, Node slow){ 43 | if(fast.next==null){ 44 | slow = slow.next; 45 | System.out.println(slow.data); 46 | return; 47 | } 48 | else{ 49 | fast=fast.next.next; 50 | slow=slow.next; 51 | findMiddleNode(fast, slow); 52 | } 53 | } 54 | 55 | private static void traverseRecursive(Node head){ 56 | if(head==null){ 57 | return; 58 | } 59 | System.out.print(head.data+", "); 60 | traverseRecursive(head.next); 61 | } 62 | 63 | public static void kthElementFromEnd(Node head, int k) { 64 | Node node = head; 65 | while (node != null && k != 0) { 66 | node = node.next; 67 | k--; 68 | } 69 | Node n = head; 70 | while (node != null) { 71 | node = node.next; 72 | n = n.next; 73 | } 74 | System.out.println(n.data); 75 | } 76 | 77 | private static void initiateDelete(int n) { 78 | Node nodeTBD = head; 79 | while (n != 0) { 80 | n--; 81 | nodeTBD = nodeTBD.next; 82 | } 83 | nodeTBD.printList(head); 84 | deleteWithOnlyReference(nodeTBD); 85 | } 86 | 87 | private static Node result; 88 | 89 | static Node linkedListDemo(int[] a) { 90 | Node head = new Node(); 91 | for (int d : a) { 92 | head.appendToTail(d); 93 | } 94 | //head.next.printList(head); 95 | return head.next; 96 | } 97 | 98 | private static int add(Node h, Node j) { 99 | if (h.next == null) { 100 | return h.data + j.data; 101 | } else { 102 | Node n = new Node(add(h.next, j.next)); 103 | int sum = (h.data + j.data); 104 | Node x = new Node(sum); 105 | x.next = n; 106 | result = x; 107 | return 0; 108 | } 109 | } 110 | 111 | // Implement an algorithm to delete a node c only when access is given to it. 112 | private static void deleteWithOnlyReference(Node nodeTBD) { 113 | System.out.println("After deleting " + nodeTBD.data); 114 | Node nextPtr = nodeTBD.next; 115 | nodeTBD.data = nextPtr.data; 116 | nodeTBD.next = nextPtr.next; 117 | head.printList(head); 118 | } 119 | 120 | // detect beginning of a loop in a linked list 121 | private static void detectLoopStartPoint(Node head) { 122 | Node p = head; 123 | Node q = head.next.next; 124 | while (p != q) { 125 | p = p.next; 126 | q = q.next.next; 127 | } 128 | System.out.println("Detected a loop: Merge point at " + p.data); 129 | p = head; 130 | while (p.next != q) { 131 | p = p.next; 132 | q = q.next.next; 133 | } 134 | p.next = null; 135 | System.out.println("Beginning of the loop is " + p.data); 136 | } 137 | 138 | private static Node reverseLinkedList(Node head1) { 139 | Node temp = head1; //one 140 | head1 = head1.next; //two 141 | temp.next = null; 142 | System.out.println(head1.data); 143 | Node an = head1.next; //three 144 | while (head1.next != null) { 145 | head1.next = temp; //two.next = one; 146 | temp = head1;//one = two 147 | head1 = an; //two = three 148 | an = head1.next; //three = three.next 149 | temp.printList(temp); 150 | } 151 | head1.next = temp; 152 | temp = head1; 153 | temp.printList(temp); 154 | return temp; 155 | } 156 | 157 | // To check if a list is palindrome 158 | private static void listPalindrome(Node head) { 159 | int size = 0; 160 | Node temp = head; 161 | while (temp != null) { 162 | size++; 163 | temp = temp.next; 164 | } 165 | int mid = size / 2; 166 | temp = head; 167 | int i = 0; 168 | while (i != mid) { 169 | temp = temp.next; 170 | i++; 171 | } 172 | Node temp2 = reverseLinkedList(temp); 173 | temp2.printList(temp2); 174 | temp = head; 175 | head.printList(head); 176 | while (temp2 != null) { 177 | if (temp2.data != temp.data) { 178 | System.out.println("Not a palindrome"); 179 | return; 180 | } 181 | temp = temp.next; 182 | temp2 = temp2.next; 183 | } 184 | System.out.println("Yayy! A palindrome."); 185 | } 186 | 187 | } 188 | -------------------------------------------------------------------------------- /src/com/practice/list/Node.java: -------------------------------------------------------------------------------- 1 | package com.practice.list; 2 | 3 | public class Node { 4 | Node next = null; 5 | int data; 6 | 7 | public Node(int d) { 8 | data = d; 9 | } 10 | 11 | public Node() { 12 | 13 | } 14 | 15 | Node appendToTail(int d) { 16 | Node end = new Node(d); 17 | Node n = this; 18 | while (n.next != null) { 19 | n = n.next; 20 | } 21 | n.next = end; 22 | return end; 23 | } 24 | 25 | Node deleteFromList(Node head, int d) { 26 | Node pointer = head; 27 | 28 | while (pointer != null) { 29 | 30 | if (pointer.data != d) { 31 | pointer = pointer.next; 32 | continue; 33 | } else{ 34 | if(pointer==head){ 35 | head = head.next; 36 | pointer = pointer.next; 37 | } 38 | else pointer = pointer.next.next; 39 | } 40 | 41 | } 42 | return head; 43 | } 44 | 45 | void printList(Node head) { 46 | Node pointer = head; 47 | while (pointer != null) { 48 | System.out.print(pointer.data + "->"); 49 | pointer = pointer.next; 50 | } 51 | System.out.println(); 52 | } 53 | 54 | Node InsertNth(Node head, int data, int position) { 55 | 56 | Node newNode = new Node(data); 57 | 58 | if (head == null) { 59 | return newNode; 60 | } 61 | Node temp = head; 62 | Node prev = null; 63 | for (int find = 0; find < position; find++) { 64 | prev = temp; 65 | temp = temp.next; 66 | if (temp == null) { 67 | break; 68 | } 69 | } 70 | if (position == 0) { 71 | newNode.next = head; 72 | head = newNode; 73 | return head; 74 | } else if (temp == null) { 75 | prev.next = newNode; 76 | return head; 77 | } else { 78 | newNode.next = temp; 79 | prev.next = newNode; 80 | return head; 81 | } 82 | 83 | } 84 | 85 | Node Delete(Node head, int position) { 86 | // Complete this method 87 | if (head == null) { 88 | return null; 89 | } 90 | if (position == 0) { 91 | return head.next; 92 | } 93 | Node temp = head; 94 | Node prev = null; 95 | for (int i = 0; i < position; i++) { 96 | prev = temp; 97 | temp = temp.next; 98 | if (temp == null) { 99 | return null; 100 | } 101 | } 102 | prev.next = temp.next; 103 | return head; 104 | } 105 | 106 | int HasCycle(Node head) { 107 | Node one = head; 108 | Node two = head; 109 | while (one != null && two != null && two.next != null) { 110 | one = one.next; 111 | two = two.next.next; 112 | if (one == two) { 113 | return 1; 114 | } 115 | } 116 | return 0; 117 | } 118 | 119 | int FindMergeNode(Node headA, Node headB) { 120 | // Complete this function 121 | // Do not write the main method. 122 | int countA = 0; 123 | int countB = 0; 124 | Node tempA = headA; 125 | Node tempB = headB; 126 | while (tempA != null) { 127 | tempA = tempA.next; 128 | countA++; 129 | } 130 | while (tempB != null) { 131 | tempB = tempB.next; 132 | countB++; 133 | } 134 | int k = Math.abs(countA - countB); 135 | tempA = headA; 136 | tempB = headB; 137 | if (countA >= countB) { 138 | while (k != 0) { 139 | tempA = tempA.next; 140 | k--; 141 | } 142 | } else { 143 | while (k != 0) { 144 | tempB = tempB.next; 145 | k--; 146 | } 147 | } 148 | 149 | while (tempA != null) { 150 | if (tempA == tempB) { 151 | return tempA.data; 152 | } 153 | tempA = tempA.next; 154 | tempB = tempB.next; 155 | } 156 | return -1; 157 | 158 | } 159 | 160 | void ReversePrint(Node head) { 161 | 162 | if (head == null) { 163 | return; 164 | } 165 | ReversePrint(head.next); 166 | System.out.println(head.data); 167 | return; 168 | 169 | } 170 | 171 | int CompareLists(Node headA, Node headB) { 172 | 173 | while (headA != null && headB != null) { 174 | if (headA.data != headB.data) { 175 | return 0; 176 | } 177 | headA = headA.next; 178 | headB = headB.next; 179 | } 180 | boolean f = headA == null && headB != null; 181 | boolean g = headB == null && headA != null; 182 | 183 | if (f || g) 184 | return 0; 185 | return 1; 186 | 187 | } 188 | 189 | Node MergeLists(Node l1, Node l2) { 190 | Node p1 = l1; 191 | Node p2 = l2; 192 | 193 | Node fakeHead = new Node(0); 194 | Node p = fakeHead; 195 | 196 | while (p1 != null && p2 != null) { 197 | if (p1.data <= p2.data) { 198 | p.next = p1; 199 | p1 = p1.next; 200 | } else { 201 | p.next = p2; 202 | p2 = p2.next; 203 | } 204 | 205 | p = p.next; 206 | } 207 | 208 | if (p1 != null) 209 | p.next = p1; 210 | if (p2 != null) 211 | p.next = p2; 212 | 213 | return fakeHead.next; 214 | 215 | } 216 | 217 | int getNodeFromTail(Node head, int n) { 218 | 219 | Node one = head; 220 | Node two = head; 221 | while (two != null && n != 0) { 222 | two = two.next; 223 | n--; 224 | } 225 | while (two.next != null) { 226 | one = one.next; 227 | two = two.next; 228 | } 229 | return one.data; 230 | 231 | } 232 | 233 | Node RemoveDuplicates(Node head) { 234 | Node prev = head; 235 | Node nex = head; 236 | while (nex != null) { 237 | if (nex.data == prev.data) { 238 | nex = nex.next; 239 | prev.next = null; 240 | } else { 241 | prev.next = nex; 242 | prev = prev.next; 243 | } 244 | } 245 | return head; 246 | } 247 | 248 | } 249 | -------------------------------------------------------------------------------- /src/com/practice/misc/Threads.java: -------------------------------------------------------------------------------- 1 | package com.practice.misc; 2 | 3 | public class Threads implements Runnable{ 4 | private Thread t; 5 | private Thread name; 6 | 7 | @Override 8 | public void run() { 9 | System.out.println("Running thread - "+ name); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/practice/search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.practice.search; 2 | 3 | import com.practice.CommonData; 4 | 5 | import java.util.Arrays; 6 | import java.util.Stack; 7 | 8 | /** 9 | * Created by shruthi on 29/11/15. 10 | */ 11 | public class BinarySearch { 12 | static int[] a = CommonData.array; 13 | 14 | public static void main(String[] args) { 15 | binarySearch(a, a[3]); 16 | binaryRecursive(a, 0, a.length, a[3]); 17 | } 18 | 19 | public static void binarySearch(int[] a, int key) { 20 | int s = 0; 21 | int e = a.length; 22 | int mid = (s + e) / 2; 23 | System.out.println(Arrays.toString(a)); 24 | 25 | while (s <= e) { 26 | 27 | if (a[mid] == key) { 28 | System.out.println("NonRecursive - Index: " + mid); 29 | return; 30 | } else if (a[mid] > key) { 31 | e = mid - 1; 32 | } else { 33 | s = mid + 1; 34 | } 35 | 36 | mid = (s + e) / 2; 37 | } 38 | System.out.println("NonRecursive - Not found"); 39 | 40 | } 41 | 42 | public static void binaryRecursive(int[] a, int s, int e, int key) { 43 | if (s <= e) { 44 | int mid = (s + e) / 2; 45 | if (a[mid] == key) { 46 | System.out.println("Recursive - Index: " + mid); 47 | return; 48 | } else if (key < a[mid]) { 49 | binaryRecursive(a, s, mid - 1, key); 50 | } else { 51 | binaryRecursive(a, mid + 1, e, key); 52 | } 53 | } else { 54 | System.out.println("Recursive - Not Found"); 55 | return; 56 | } 57 | } 58 | 59 | /* 60 | * Complete the function below. 61 | */ 62 | 63 | /* 64 | * Complete the function below. 65 | */ 66 | 67 | /* 68 | * Complete the function below. 69 | */ 70 | 71 | static String[] Braces(String[] values) { 72 | 73 | String[] output = new String[values.length]; 74 | int count = 0; 75 | Stack stack = new Stack(); 76 | for (String str : values) { 77 | boolean yes = true; 78 | 79 | if (str.isEmpty()) { 80 | yes = true; 81 | } else { 82 | 83 | stack = new Stack(); 84 | for (int i = 0; i < str.length(); i++) { 85 | char current = str.charAt(i); 86 | if (current == '{' || current == '(' || current == '[') { 87 | stack.push(current); 88 | } 89 | 90 | if (current == '}' || current == ')' || current == ']') { 91 | if (stack.isEmpty()) { 92 | yes = false; 93 | break; 94 | } 95 | 96 | char last = stack.peek(); 97 | if (current == '}' && last == '{' || current == ')' 98 | && last == '(' || current == ']' && last == '[') 99 | stack.pop(); 100 | else { 101 | yes = false; 102 | break; 103 | } 104 | } 105 | 106 | } 107 | } 108 | if (yes && stack.isEmpty()) { 109 | output[count] = "YES"; 110 | } else 111 | output[count] = "NO"; 112 | count++; 113 | } 114 | return output; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/com/practice/search/Search.java: -------------------------------------------------------------------------------- 1 | package com.practice.search; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Search { 6 | /*public static void main(String[] args) { 7 | //int[] a = {846930887,1681692778,1714636916,1957747794,424238336,719885387,1649760493,596516650,1189641422,1025202363,1350490028,783368691,1102520060,2044897764,1967513927,1365180541,1540383427,304089173,1303455737,35005212,521595369,294702568,1726956430,336465783,861021531,278722863,233665124,2145174068,468703136,1101513930,1801979803,1315634023,635723059,1369133070,1125898168,1059961394,2089018457,628175012,1656478043,1131176230,1653377374,859484422,1914544920,608413785,756898538,1734575199,1973594325,149798316,2038664371,1129566414}; 8 | int[] a = {3,2,9,9,5,1}; 9 | maxModSum(a, 7); 10 | }*/ 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int n = in.nextInt(); 15 | //String grid[] = new String[n]; 16 | String[][] grid = new String[n][n]; 17 | for(int i=0; i < n; i++){ 18 | String x = in.next(); 19 | int j=0; 20 | for(char c: x.toCharArray()){ 21 | grid[i][j] = c+""; 22 | j++; 23 | } 24 | } 25 | int x = 1; 26 | int y = n-2; 27 | 28 | for(int i=x;i rs) { 48 | y--; 49 | rs += a[y]; //add one more element 50 | } else { 51 | x++; 52 | ls += a[x]; 53 | } 54 | } 55 | if (ls == rs) { 56 | System.out.println("YES"); 57 | } else { 58 | System.out.println("NO"); 59 | } 60 | } 61 | 62 | public static void maxModSum(int[] a, int mod){ 63 | int modSum = 0; 64 | int n = a.length; 65 | int x = 0; 66 | int y = x; 67 | int sum = 0; 68 | sum = sum + a[y]; 69 | 70 | while(y!=n-1){ 71 | if(sum%mod > modSum){ 72 | modSum = sum%mod; 73 | y++; 74 | sum = sum + a[y]; 75 | 76 | } else{ 77 | sum = sum-a[x]; 78 | x++; 79 | } 80 | if(x==y){ 81 | y++; 82 | } 83 | } 84 | System.out.println(modSum); 85 | } 86 | 87 | public static boolean isCavity(String[][] grid, int i, int j){ 88 | System.out.println("x: "+i+"y: "+j+" "+grid[1][1]); 89 | int ele = Integer.parseInt(grid[i][j]); 90 | for(int x=i-1;xele) 94 | return false; 95 | } 96 | } 97 | return true; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/com/practice/sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | package com.practice.sort; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HeapSort { 6 | int[] pq; 7 | int size; 8 | 9 | public static void main(String[] args) { 10 | int[] a = new int[] { 99, 68, 94, 47, 52, 23, 64, 87, 97, 12, 93, 99, 11 | 52, 32, 44, 34, 53, 58, 95, 70 }; 12 | HeapSort heap = new HeapSort(a); 13 | heap.print(); 14 | int n = 0; 15 | Scanner read = new Scanner(System.in); 16 | while (n != 4) { 17 | System.out.println("Enter a number to insert: "); 18 | int number = read.nextInt(); 19 | heap.add(number); 20 | heap.print(); 21 | System.out.println("The number deleted is: " + heap.remove()); 22 | heap.print(); 23 | n++; 24 | } 25 | read.close(); 26 | System.out.println("-EOP-"); 27 | } 28 | 29 | HeapSort(int n) { 30 | pq = new int[n]; 31 | } 32 | 33 | public HeapSort(int[] q) { 34 | pq = q; 35 | buildHeap(); 36 | } 37 | 38 | void buildHeap() { 39 | 40 | for (int i = 1; i < pq.length; i++) { 41 | size++; 42 | percolateUp(i); 43 | } 44 | 45 | } 46 | 47 | void percolateDown(int i) { 48 | int x = pq[i]; 49 | while (2 * i < size) { 50 | int lchild = pq[2 * i]; 51 | int rchild = -1; 52 | if ((2 * i + 1) < size) { 53 | rchild = pq[2 * i + 1]; 54 | } 55 | int index; 56 | if (rchild != -1) { 57 | index = lchild < rchild ? 2 * i : 2 * i + 1; 58 | } else { 59 | index = 2 * i; 60 | } 61 | if (x > pq[index]) { 62 | swap(i, index); 63 | i = index; 64 | } else { 65 | break; 66 | } 67 | 68 | } 69 | pq[i] = x; 70 | } 71 | 72 | protected void swap(int i, int j) { 73 | int temp = pq[i]; 74 | pq[i] = pq[j]; 75 | pq[j] = temp; 76 | } 77 | 78 | public void percolateUp(int i) { 79 | pq[0] = pq[i]; // first copy the element to be percolated into another 80 | // space thereby making pq[i] as the hole. 81 | while (pq[i / 2] > pq[0]) { // compare the element to its parent 82 | swap(i, i / 2); 83 | i = i / 2; 84 | } 85 | pq[i] = pq[0]; 86 | } 87 | 88 | public void print() { 89 | for (int i = 1; i <= size; i++) { 90 | System.out.println(pq[i]); 91 | } 92 | } 93 | 94 | public void add(int x) { 95 | if (size == pq.length - 1) { 96 | resize(); 97 | } 98 | size++; 99 | pq[size] = x; 100 | percolateUp(size); 101 | } 102 | 103 | public int remove() { 104 | if (size > 0) { 105 | int top = pq[1]; 106 | pq[1] = pq[size--]; 107 | percolateDown(1); 108 | return top; 109 | } 110 | return -1; 111 | } 112 | 113 | public void resize() { 114 | HeapSort newPq = new HeapSort(size * 2); 115 | int i = 0; 116 | for (int element : pq) { 117 | newPq.pq[i++] = element; 118 | } 119 | pq = newPq.pq; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/com/practice/sort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package com.practice.sort; 2 | 3 | /** 4 | * Created by shruthi on 29/11/15. 5 | */ 6 | public class InsertionSort { 7 | } 8 | -------------------------------------------------------------------------------- /src/com/practice/sort/MergeSort.java: -------------------------------------------------------------------------------- 1 | package com.practice.sort; 2 | 3 | import com.practice.CommonData; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by shruthi on 29/11/15. 9 | */ 10 | public class MergeSort { 11 | static int[] array = CommonData.getUnsortedArray(20); 12 | static int[] tempMergArr = new int[array.length]; 13 | public static void main(String[] args){ 14 | System.out.println(Arrays.toString(array)); 15 | doMergeSort(0, array.length-1); 16 | System.out.println(Arrays.toString(array)); 17 | } 18 | private static void doMergeSort(int lowerIndex, int higherIndex) { 19 | 20 | if (lowerIndex < higherIndex) { 21 | int middle = lowerIndex + (higherIndex - lowerIndex) / 2; 22 | // Below step sorts the left side of the array 23 | doMergeSort(lowerIndex, middle); 24 | // Below step sorts the right side of the array 25 | doMergeSort(middle + 1, higherIndex); 26 | // Now merge both sides 27 | mergeParts(lowerIndex, middle, higherIndex); 28 | } 29 | } 30 | 31 | private static void mergeParts(int lowerIndex, int middle, int higherIndex) { 32 | 33 | for (int i = lowerIndex; i <= higherIndex; i++) { 34 | tempMergArr[i] = array[i]; 35 | } 36 | int i = lowerIndex; 37 | int j = middle + 1; 38 | int k = lowerIndex; 39 | while (i <= middle && j <= higherIndex) { 40 | if (tempMergArr[i] <= tempMergArr[j]) { 41 | array[k] = tempMergArr[i]; 42 | i++; 43 | } else { 44 | array[k] = tempMergArr[j]; 45 | j++; 46 | } 47 | k++; 48 | } 49 | while (i <= middle) { 50 | array[k] = tempMergArr[i]; 51 | k++; 52 | i++; 53 | } 54 | while (j <= higherIndex) { 55 | array[k] = tempMergArr[j]; 56 | k++; 57 | j++; 58 | } 59 | 60 | } 61 | public static void mergeSort(int[] a, int s, int e) { 62 | 63 | if (s <= e) { 64 | int mid = (s + e) / 2; 65 | mergeSort(a, s, mid - 1); 66 | mergeSort(a, mid + 1, e); 67 | merge(a, s, mid, e); 68 | } 69 | } 70 | 71 | public static int[] merge(int[] a, int s, int mid, int e) { 72 | 73 | int m = mid - s + 1; 74 | int n = e - mid + 1; 75 | int[] c = new int[m]; 76 | int[] d = new int[n]; 77 | int[] b = new int[m + n]; 78 | int i = s, j=mid+1, k=0; 79 | while (i < mid && j < e) { 80 | if (a[i] <= a[j]) { 81 | b[k] = a[i]; 82 | i++; 83 | } else { 84 | b[k] = a[j]; 85 | j++; 86 | } 87 | k++; 88 | } 89 | 90 | while (i < mid) { 91 | b[k] = a[i]; 92 | i++; 93 | k++; 94 | } 95 | while (j < e) { 96 | b[k] = a[j]; 97 | k++; 98 | j++; 99 | } 100 | System.out.println(Arrays.toString(b)); 101 | return b; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/com/practice/sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | package com.practice.sort; 2 | 3 | public class QuickSort { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/com/practice/sort/Solution.java: -------------------------------------------------------------------------------- 1 | package com.practice.sort; 2 | 3 | 4 | import java.util.Scanner; 5 | 6 | class Student { 7 | private int token; 8 | private String fname; 9 | private double cgpa; 10 | 11 | public Student(int id, String fname, double cgpa) { 12 | super(); 13 | this.token = id; 14 | this.fname = fname; 15 | this.cgpa = cgpa; 16 | } 17 | 18 | public int getToken() { 19 | return token; 20 | } 21 | 22 | public String getFname() { 23 | return fname; 24 | } 25 | 26 | public double getCgpa() { 27 | return cgpa; 28 | } 29 | 30 | public void print(){ 31 | System.out.println(fname); 32 | } 33 | public int equals(Student s) { 34 | if (s.cgpa < this.cgpa) 35 | return 1; 36 | else if (s.cgpa > this.cgpa) 37 | return -1; 38 | else if (this.fname.compareTo(s.fname) == 1) { 39 | return 1; 40 | } else if (this.fname.compareTo(s.fname) == -1) 41 | return -1; 42 | else if (this.token < s.token) { 43 | return 1; 44 | } else 45 | return -1; 46 | } 47 | } 48 | 49 | public class Solution { 50 | Student[] pq; 51 | int size; 52 | 53 | public static void main(String[] args) { 54 | Scanner in = new Scanner(System.in); 55 | int totalEvents = Integer.parseInt(in.nextLine()); 56 | Solution s = new Solution(5); 57 | while (totalEvents > 0) { 58 | String event = in.nextLine(); 59 | //ENTER Maria 3.6 46 60 | System.out.println(event); 61 | String[] a = event.split(" "); 62 | if(a[0].equals("ENTER")){ 63 | //System.out.println(a[1]+":"+ Double.parseDouble(a[2])); 64 | s.add(new Student(totalEvents, a[1], Double.parseDouble(a[2]))); 65 | } else{ 66 | s.remove(); 67 | } 68 | 69 | // Complete your code 70 | while(s.size!=0){ 71 | s.remove().print(); 72 | } 73 | totalEvents--; 74 | } 75 | 76 | } 77 | Solution(int n) { 78 | pq = new Student[n]; 79 | } 80 | public Solution(Student[] q) { 81 | pq = q; 82 | buildHeap(); 83 | } 84 | 85 | void buildHeap() { 86 | 87 | size = pq.length / 2; 88 | for (int i = pq.length / 2 - 1; i >= 1; i--) { 89 | size++; 90 | percolateDown(i); 91 | } 92 | } 93 | 94 | void percolateDown(int i) { 95 | 96 | Student x = pq[i]; 97 | while (2 * i < size) { 98 | Student lchild = pq[2 * i]; 99 | Student rchild = null; 100 | if ((2 * i + 1) < size) { 101 | rchild = pq[2 * i + 1]; 102 | } 103 | int index; 104 | if (rchild != null) { 105 | index = lchild.equals(rchild) > 0 ? 2 * i : 2 * i + 1; 106 | } else { 107 | index = 2 * i; 108 | } 109 | if (x.equals(pq[index]) < 0) { 110 | swap(i, index); 111 | i = index; 112 | } else { 113 | break; 114 | } 115 | 116 | } 117 | pq[i] = x; 118 | } 119 | 120 | protected void swap(int i, int j) { 121 | Student temp = pq[i]; 122 | pq[i] = pq[j]; 123 | pq[j] = temp; 124 | } 125 | 126 | public void add(Student x) { 127 | if (size == pq.length - 1) { 128 | resize(); 129 | } 130 | size++; 131 | pq[size] = x; 132 | percolateUp(size); 133 | } 134 | 135 | public Student remove() { 136 | if (size > 0) { 137 | Student top = pq[1]; 138 | pq[1] = pq[size--]; 139 | percolateDown(1); 140 | return top; 141 | } 142 | return null; 143 | } 144 | 145 | public void resize() { 146 | Solution newPq = new Solution(size * 2); 147 | int i = 0; 148 | for (Student element : pq) { 149 | newPq.pq[i++] = element; 150 | } 151 | pq = newPq.pq; 152 | } 153 | public void percolateUp(int i) { 154 | pq[0] = pq[i]; // first copy the element to be percolated into another 155 | // space thereby making pq[i] as the hole. 156 | while (pq[i / 2].equals(pq[0])==1) { // compare the element to its parent 157 | swap(i, i / 2); 158 | i = i / 2; 159 | } 160 | pq[i] = pq[0]; 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/com/practice/stack/Stack.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.practice.stack; 3 | 4 | 5 | import com.practice.list.Node; 6 | 7 | public class Stack { 8 | Node top = null; 9 | 10 | void push(int d){ 11 | Node n = new Node(d); 12 | n.next=top; 13 | top=n; 14 | } 15 | void pop(){ 16 | System.out.println("Popped item is "+top.data); 17 | if(top.next!=null) 18 | top=top.next; 19 | else top = null; 20 | } 21 | void printStack(){ 22 | Node pointer = top; 23 | while(pointer!=null){ 24 | System.out.print(pointer.data+"->"); 25 | pointer=pointer.next; 26 | } 27 | } 28 | } 29 | */ 30 | -------------------------------------------------------------------------------- /src/com/practice/tree/BST.java: -------------------------------------------------------------------------------- 1 | package com.practice.tree; 2 | 3 | import java.util.Stack; 4 | 5 | public class BST { 6 | 7 | public static void main(String[] args) { 8 | BST tree = new BST(); 9 | Node root = null; 10 | for (int i = 90; i > 50; i -= 3) 11 | root = tree.insert(root, i); 12 | System.out.println("Inorder traversal of the tree after insertion."); 13 | tree.inorder(root); 14 | System.out.println("Deleting 72..."); 15 | root = tree.delete(root, 72); 16 | System.out.println("Deleting 57..."); 17 | root = tree.delete(root, 57); 18 | 19 | System.out.println("Inorder traversal of the tree after deletion."); 20 | tree.inorder(root); 21 | System.out.println("Preoder traversal of a tree"); 22 | tree.iterativePreOrder(root); 23 | } 24 | 25 | private Node delete(Node root, int toDelete) { 26 | if (root == null) { 27 | System.out.println("Cannot delete. Tree is empty"); 28 | return root; 29 | } else if (toDelete < root.data) 30 | root.left = delete(root.left, toDelete); 31 | else if (toDelete > root.data) 32 | root.right = delete(root.right, toDelete); 33 | else { 34 | if (root.left == null) 35 | return root.right; 36 | else if (root.right == null) 37 | return root.left; 38 | else { 39 | root.data = root.left.data; 40 | root.left = delete(root.left, root.data); 41 | } 42 | } 43 | return root; 44 | } 45 | 46 | Node insert(Node root, int value) { 47 | Node n = new Node(); 48 | n.data = value; 49 | if (root == null) { 50 | return n; 51 | } 52 | if (value > root.data) { 53 | if (root.right == null) { 54 | root.right = n; 55 | } else { 56 | insert(root.right, value); 57 | } 58 | } 59 | 60 | if (value < root.data) { 61 | if (root.left == null) { 62 | root.left = n; 63 | } else { 64 | insert(root.left, value); 65 | } 66 | } 67 | return root; 68 | } 69 | 70 | void inorder(Node root) { 71 | if (root.left != null) { 72 | inorder(root.left); 73 | } 74 | System.out.print(root.data + ", "); 75 | if (root.right != null) { 76 | inorder(root.right); 77 | } 78 | } 79 | 80 | public class Node { 81 | Node left = null; 82 | Node right = null; 83 | boolean visited; 84 | int data; 85 | 86 | public Node(int d) { 87 | this.data = d; 88 | } 89 | 90 | public Node() { 91 | 92 | } 93 | 94 | void print() { 95 | System.out.print(data + ":" + left != null ? left.data : "" + ", " + right != null ? right.data : ""+"; "); 96 | } 97 | } 98 | 99 | void iterativePreOrder(Node root) { 100 | if (root == null) { 101 | return; 102 | } 103 | System.out.println(); 104 | Stack s = new Stack<>(); 105 | s.push(root); 106 | System.out.println(root.data); 107 | while (!s.isEmpty()) { 108 | Node top = s.peek(); 109 | if (!top.visited) { 110 | 111 | System.out.print(top.data+", "); 112 | top.visited = true; 113 | } 114 | if (top.left != null && !top.left.visited) { 115 | s.push(top.left); 116 | } else if (top.right != null && !top.right.visited) { 117 | s.push(top.right); 118 | } else { 119 | s.pop(); 120 | } 121 | } 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/com/practice/tree/Node.java: -------------------------------------------------------------------------------- 1 | package com.practice.tree; 2 | 3 | public class Node { 4 | Node left = null; 5 | Node right = null; 6 | int data; 7 | int level; 8 | 9 | public Node(int d){ 10 | this.data=d; 11 | } 12 | 13 | public Node() { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/practice/tree/Tree.java: -------------------------------------------------------------------------------- 1 | package com.practice.tree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | //Insertion 8 | //Deletion 9 | //Searching 10 | //kth smallest/greatest element 11 | //range of numbers in a BST 12 | //Given 2 arrays, check if they make the same BST 13 | //Largest BST in a Tree 14 | //DLL for a tree 15 | //http://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/ 16 | // Floor and Ceil from a BST 17 | //Find a pair with given sum in a Balanced BST 18 | public class Tree { 19 | 20 | private static boolean found = false; 21 | private static int k = 3; 22 | 23 | public static void main(String[] args) { 24 | int[] a = {20, 30, 40, 4353, 532, 535, 50, 10, 80, 60}; 25 | Arrays.sort(a); 26 | Node root = constructionNormal(a, 0, a.length); 27 | levelOrder(root); 28 | int[] b = {20, 30, 40, 532, 535, 50, 80, 60}; 29 | Node root2 = constructionNormal(b, 0, b.length); 30 | System.out.println(); 31 | System.out.println(findClosest(root, 533)); 32 | 33 | kthGreatestOrSmallest(false, root, 1); 34 | System.out.println("After"); 35 | Tree.inorder(root); 36 | kthGreatestOrSmallestIterative(false, 0, root); 37 | System.out.println(); 38 | preorder(root); 39 | System.out.println(); 40 | preorder(root2); 41 | System.out.println(isIdentical(root2, root2)); 42 | 43 | } 44 | 45 | public static int findClosest(Node root, int number) { 46 | if (root == null) { 47 | return Integer.MAX_VALUE; 48 | } 49 | if (root.data == number) 50 | return root.data; 51 | 52 | if (root.left == null && root.right == null) { 53 | return root.data; 54 | } else { 55 | 56 | int left = findClosest(root.left, number); 57 | int right = findClosest(root.right, number); 58 | int l = Math.abs(left - number); 59 | int r = Math.abs(right - number); 60 | int d = Math.abs(root.data - number); 61 | if (l < r) { 62 | if (l < d) 63 | return left; 64 | } else if (r < d) { 65 | return right; 66 | } 67 | return root.data; 68 | 69 | } 70 | } 71 | 72 | public static int maxPathSum(Node head, int max) { 73 | if (head.left == null) { 74 | return 0; 75 | } 76 | if (head.right == null) { 77 | return 0; 78 | } 79 | int rightSum = maxPathSum(head.left, max); 80 | int leftSum = maxPathSum(head.right, max); 81 | int sum = Math.max(head.data + Math.max(rightSum, leftSum), head.data); 82 | int maxtop = Math.max(sum, rightSum + leftSum + head.data); 83 | max = Math.max(max, maxtop); 84 | return sum; 85 | } 86 | 87 | public static boolean isABST(Node root) { 88 | if (root.left != null) { 89 | if (root.left.data > root.data) 90 | return false; 91 | else 92 | isABST(root.left); 93 | } 94 | if (root.right != null) { 95 | if (root.right.data < root.data) 96 | return false; 97 | else 98 | isABST(root.right); 99 | } 100 | return true; 101 | } 102 | 103 | public static int heightOfBinaryTree(Node root) { 104 | if (root == null) { 105 | return 0; 106 | } else { 107 | int a = heightOfBinaryTree(root.left); 108 | int b = heightOfBinaryTree(root.right); 109 | return 1 + (Math.max(a, b)); 110 | } 111 | } 112 | 113 | public static void kthGreatestOrSmallest(boolean small, Node root, int k) { 114 | 115 | if (small) { 116 | if (root.left != null) { 117 | kthGreatestOrSmallest(true, root.left, k); 118 | } 119 | k = k - 1; 120 | if (k == 0) { 121 | System.out.println(root.data); 122 | } 123 | if (root.right != null) { 124 | kthGreatestOrSmallest(true, root.right, k); 125 | } 126 | } else { 127 | if (root.right != null) { 128 | kthGreatestOrSmallest(false, root.right, k); 129 | } 130 | k = k - 1; 131 | if (k == 0) { 132 | System.out.println(root.data); 133 | } 134 | if (root.left != null) { 135 | kthGreatestOrSmallest(true, root.left, k); 136 | } 137 | 138 | } 139 | 140 | } 141 | 142 | public static void kthGreatestOrSmallestIterative(boolean small, int k, Node root) { 143 | Node temp = root; 144 | if (small) { 145 | while (k != 0) { 146 | if (temp.left != null) { 147 | temp = temp.left; 148 | } 149 | k = k - 1; 150 | if (k == 0) { 151 | System.out.println(temp.data); 152 | break; 153 | } 154 | if (temp.right != null) { 155 | temp = temp.right; 156 | } 157 | } 158 | } else { 159 | while (k != 0) { 160 | if (temp.right != null) { 161 | temp = temp.right; 162 | } 163 | k = k - 1; 164 | if (k == 0) { 165 | System.out.println(temp.data); 166 | break; 167 | } 168 | if (temp.left != null) { 169 | temp = temp.left; 170 | } 171 | } 172 | 173 | } 174 | 175 | } 176 | 177 | public static void inorder(Node root) { 178 | if (root.left != null) { 179 | inorder(root.left); 180 | } 181 | System.out.println(root.data); 182 | if (root.right != null) { 183 | inorder(root.right); 184 | } 185 | } 186 | 187 | public static void preorder(Node root) { 188 | System.out.println(root.data); 189 | if (root.left != null) { 190 | preorder(root.left); 191 | } 192 | if (root.right != null) { 193 | preorder(root.right); 194 | } 195 | } 196 | 197 | public static void postorder(Node root) { 198 | if (root.left != null) { 199 | postorder(root.left); 200 | } 201 | if (root.right != null) { 202 | postorder(root.right); 203 | } 204 | System.out.println(root.data); 205 | } 206 | 207 | 208 | public static Node constructionNormal(int[] a, int start, int end) { 209 | int mid = (start + end) / 2; 210 | Node root = null; 211 | if (start >= end) { 212 | return null; 213 | } 214 | root = new Node(a[mid]); 215 | root.left = constructionNormal(a, start, mid); 216 | root.right = constructionNormal(a, mid + 1, end); 217 | return root; 218 | } 219 | 220 | public static int greatestSum(Node root) { 221 | if (root.right != null) { 222 | root.data = root.data + greatestSum(root.right); 223 | return root.data; 224 | } 225 | if (root.left != null) { 226 | root.data = root.data + greatestSum(root.left); 227 | return root.data; 228 | } 229 | return root.data; 230 | } 231 | 232 | // Common ancestor - first node that is greater than first ele and second 233 | // node less than or equal to second ele. 234 | static Node lca(Node root, int v1, int v2) { 235 | if (v1 > v2) { 236 | int temp = v2; 237 | v2 = v1; 238 | v1 = temp; 239 | } 240 | if (root.data >= v1 && root.data <= v2) { 241 | 242 | return root; 243 | } 244 | if (root.left != null) { 245 | return lca(root.left, v1, v2); 246 | } else if (root.right != null) { 247 | return lca(root.right, v1, v2); 248 | } 249 | return null; 250 | } 251 | 252 | static void levelOrder(Node root) { 253 | List queue = new ArrayList(); 254 | queue.add(root); 255 | int level = 0; 256 | while (queue.size() != 0) { 257 | Node now = queue.get(0); 258 | queue.remove(0); 259 | System.out.print(now.data + " : " + now.level + ", "); 260 | level++; 261 | if (now.left != null) { 262 | now.left.level = level; 263 | queue.add(now.left); 264 | } 265 | if (now.right != null) { 266 | now.right.level = level; 267 | queue.add(now.right); 268 | } 269 | 270 | } 271 | 272 | } 273 | 274 | static Node Insert(Node root, int value) { 275 | Node n = new Node(); 276 | n.data = value; 277 | if (root == null) { 278 | return n; 279 | } 280 | if (value > root.data) { 281 | if (root.right == null) { 282 | root.right = n; 283 | } else { 284 | Insert(root.right, value); 285 | } 286 | } 287 | 288 | if (value < root.data) { 289 | if (root.left == null) { 290 | root.left = n; 291 | } else { 292 | Insert(root.left, value); 293 | } 294 | } 295 | return root; 296 | } 297 | 298 | static boolean isSubTree(Node r1, Node r2) { 299 | if (r1 == null && r2 == null) 300 | return true; 301 | 302 | if (r1.data == r2.data) { 303 | if (isIdentical(r1, r2)) { 304 | return true; 305 | } 306 | } 307 | return isSubTree(r1.left, r2) || isSubTree(r1.right, r2); 308 | 309 | } 310 | 311 | static boolean isIdentical(Node r1, Node r2) { 312 | if (r1 == null && r2 == null) 313 | return true; 314 | 315 | if (r1 == null || r2 == null) 316 | return false; 317 | 318 | if (r1.data != r2.data) { 319 | return false; 320 | } 321 | 322 | return isIdentical(r1.left, r2.left) && isIdentical(r1.right, r2.right); 323 | } 324 | } 325 | --------------------------------------------------------------------------------