├── CollectionTC.md ├── README.md ├── dataStructureUsage.md ├── generalFunctions.md └── resources ├── Java-Collections-Hierarchy-old.png ├── Java-Collections-Hierarchy.png ├── java-map-hierarchy.png └── trieDS.png /CollectionTC.md: -------------------------------------------------------------------------------- 1 | Below are the Big O performance of common functions of different Java Collections. 2 | 3 | 4 | List | Add | Remove | Get | Contains | Next | Data Structure 5 | ---------------------|------|--------|------|----------|------|--------------- 6 | ArrayList | O(1) | O(n) | O(1) | O(n) | O(1) | Array 7 | LinkedList | O(1) | O(1) | O(n) | O(n) | O(1) | Linked List 8 | CopyOnWriteArrayList | O(n) | O(n) | O(1) | O(n) | O(1) | Array 9 | 10 | 11 | 12 | Set | Add | Remove | Contains | Next | Size | Data Structure 13 | ----------------------|----------|----------|----------|----------|------|------------------------- 14 | HashSet | O(1) | O(1) | O(1) | O(h/n) | O(1) | Hash Table 15 | LinkedHashSet | O(1) | O(1) | O(1) | O(1) | O(1) | Hash Table + Linked List 16 | EnumSet | O(1) | O(1) | O(1) | O(1) | O(1) | Bit Vector 17 | TreeSet | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree 18 | CopyOnWriteArraySet | O(n) | O(n) | O(n) | O(1) | O(1) | Array 19 | ConcurrentSkipListSet | O(log n) | O(log n) | O(log n) | O(1) | O(n) | Skip List 20 | 21 | 22 | 23 | Queue | Offer | Peak | Poll | Remove | Size | Data Structure 24 | ------------------------|----------|------|----------|--------|------|--------------- 25 | PriorityQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap 26 | LinkedList | O(1) | O(1) | O(1) | O(1) | O(1) | Array 27 | ArrayDequeue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List 28 | ConcurrentLinkedQueue | O(1) | O(1) | O(1) | O(n) | O(n) | Linked List 29 | ArrayBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Array 30 | PriorirityBlockingQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap 31 | SynchronousQueue | O(1) | O(1) | O(1) | O(n) | O(1) | None! 32 | DelayQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap 33 | LinkedBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List 34 | 35 | 36 | 37 | Map | Get | ContainsKey | Next | Data Structure 38 | ----------------------|----------|-------------|----------|------------------------- 39 | HashMap | O(1) | O(1) | O(h / n) | Hash Table 40 | LinkedHashMap | O(1) | O(1) | O(1) | Hash Table + Linked List 41 | IdentityHashMap | O(1) | O(1) | O(h / n) | Array 42 | WeakHashMap | O(1) | O(1) | O(h / n) | Hash Table 43 | EnumMap | O(1) | O(1) | O(1) | Array 44 | TreeMap | O(log n) | O(log n) | O(log n) | Red-black tree 45 | ConcurrentHashMap | O(1) | O(1) | O(h / n) | Hash Tables 46 | ConcurrentSkipListMap | O(log n) | O(log n) | O(1) | Skip List 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lastMinuteJavaSyntax 2 | 3 | ## Important Syntax in java 4 | Most of the sites these days allow 10^8 operations per second 5 | 6 | ### Basic 7 | Switch case 8 | ``` 9 | switch(expression) { 10 | case x: 11 | // code block 12 | break; 13 | case y: 14 | // code block 15 | break; 16 | default: 17 | // code block 18 | } 19 | ``` 20 | 21 | ### [String Class](https://www.geeksforgeeks.org/string-class-in-java/) 22 | 23 | Syntax - Taking s1 if one String and (s1,s2) if two strings are required. 24 | 25 | | No. | Methods | Description | 26 | | --- | ------------------------------------------------------- | ---------------------------------------------------------------------------- | 27 | | 1 | `char s1.charAt(int index)` | returns char value for the particular index | 28 | | 2 | `int s1.length()` | O(1) - returns string length | 29 | | 3 | `String s1.substring(int beginIndex)` | returns substring for given begin index. | 30 | | | `String s1.substring(int beginIndex, int endIndex)` | returns substring for given begin index(inclusive) and end index(exclusive). | 31 | | 4 | `boolean s1.contains(CharSequence s)` | returns true or false after matching the sequence of char value. | 32 | | 5 | `boolean s1.equals(Object another)` | checks the equality of string with the given object. | 33 | | 6 | `boolean s1.isEmpty()` | checks if string is empty. | 34 | | 7 | `String s1.concat(String str)` | concatenates the specified string. | 35 | | 8 | `String s1.replace(char old, char new)` | replaces all occurrences of the specified char value. | 36 | | | `String s1.replace(CharSequence old, CharSequence new)` | replaces all occurrences of the specified CharSequence. | 37 | | 9 | `String s1.equalsIgnoreCase(String another)` | compares another string. It doesn't check case. | 38 | | 10 | `String[] s1.split(String regex)` | returns a split string matching regex. | 39 | | | `String[] s1.split(String regex, int limit)` | returns a split string matching regex and limit. | 40 | | 11 | `int s1.indexOf(int ch)` | returns the specified char value index. | 41 | | | `int s1.indexOf(int ch, int fromIndex)` | returns the specified char value index starting with given index. | 42 | | | `int s1.indexOf(String substring)` | returns the specified substring index. | 43 | | | `int s1.indexOf(String substring, int fromIndex)` | returns the specified substring index starting with given index. | 44 | | 12 | `String s1.toLowerCase()` | returns a string in lowercase. | 45 | | 13 | `String s1.toUpperCase()` | returns a string in uppercase. | 46 | | 14 | `String s1.trim()` | removes the beginning and ending spaces of this string. | 47 | | 15 | `String String.valueOf(int value)` | converts the given type into string. It is an overloaded method. | 48 | 49 | --------------------------------------------------- 50 | ### [Buffer String]() 51 | The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. 52 | ```java 53 | StringBuffer s=new StringBuffer(); 54 | StringBuffer s= new StringBuffer(20); 55 | StringBuffer s= new StringBuffer("abc"); 56 | ``` 57 | 58 | | No. | Methods | Description | 59 | | --- | ------------------------------------------------------- | ---------------------------------------------------------------------------- | 60 | | 1 | `int s.length()` | return the length of the string i.e. total number of characters. | 61 | | 2 | `int s.capacity()` | return the current allocated capacity for a string. | 62 | | 3 | `StringBuffer s.append(String s2)` | is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. | 63 | | 4 | `StringBuffer s.insert(int offset, String s1)` | used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. | 64 | | 5 | `StringBuffer s.replace(int startIndex, int endIndex, String str)` | used to replace the string from specified startIndex and endIndex. | 65 | | 6 | `StringBuffer s.delete(int startIndex, int endIndex)` | startIndex - Inclusive and endIndex - Exclusive | 66 | | 7 | `StringBuffer s.reverse()` | used to reverse the string. | 67 | | 8 | `char s.charAt(int index)` | used to return the character at the specified position. | 68 | | 9 | `String s.substring(int beginIndex)` | used to return the substring from the specified beginIndex. | 69 | | 10 | `String s.substring(int beginIndex, int endIndex)` | used to return the substring from the specified beginIndex(inclusive) and endIndex(exclusive). | 70 | | 11 | `void s.setCharAt(int index, char ch)` | method sets the character at the specified index to ch. | 71 | 72 | 73 | ### [Math Class](https://www.geeksforgeeks.org/java-lang-math-class-in-java-set-1/) 74 | 75 | If the return type is of the type same as an argument then we are using _var_ 76 | 77 | | No. | Methods | Description | 78 | | --- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | 79 | | 1 | `var Math.abs(a)` | return the Absolute value of the given value. | 80 | | 2 | `var Math.max(a,b)` | returns the Largest of two values. | 81 | | 3 | `long Math.round(float/double x)` | round off the decimal numbers to the nearest value. | 82 | | 4 | `double Math.sqrt(double x)` | return the square root of a number. | 83 | | 5 | `double Math.cbrt(double x) ` | return the cube root of a number. | 84 | | 6 | `double Math.pow(double a, double b) ` | returns the value of first argument raised to the power to second argument. | 85 | | 7 | `double Math.signum(a) => (a>0): 1.0 / (a<0): -1.0 / (a==0): 0` | used to find the sign of a given value. | 86 | | 8 | `double Math.ceil(double x)` | used to find the smallest integer value that is greater than or equal to the argument or mathematical integer. | 87 | | 9 | `double Math.floor(double a)` | used to find the largest integer value which is less than or equal to the argument | 88 | | 10 | `double Math.random()` | returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. | 89 | | 11 | `double Math.log(double x)` | returns the natural logarithm. | 90 | | 12 | `double Math.log10(double x)` | return the base 10 logarithm of a double value. | 91 | | 13 | `double Math.exp(double x) ` | returns E raised to the power of a double value | 92 | | 14 | `double Math.sin/cos/tan/asin/acos/atan(double a)` | return the trigonometric value. | 93 | | 15 | `double sinh/tanh/cosh(double x) ` | return the trigonometric Hyperbolic value. | 94 | 95 | ------------------------------------------------------------------------------ 96 | ### [Random](https://www.youtube.com/watch?v=VMZLPl16P5c) 97 | ````java 98 | Random r = new Random(n) 99 | r.nextInt(n) // Will generate values b/w 0 to n-1 100 | ```` 101 | 102 | ### [Integer Class](https://www.geeksforgeeks.org/java-lang-integer-class-java/) 103 | 104 | | No. | Methods | Description | 105 | | --- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | 106 | | 1 | `int Integer.compare(int x,int y)` | compare two int x>y => 1 \ x=y => 0 \ x -1 | 107 | | 2 | `int x.compareTo(int x)` | compare two int x>y => 1 \ x=y => 0 \ x -1 | 108 | | 3 | `boolean Integer.equals(Object obj) ` | compares the value of the parameter to the value of the current Integer object and returns boolean ( True or False ). | 109 | | 4 | `int object.intValue() ` | returns the value of the specified number as an int. | 110 | | 5 | `long object.longValue()` | returns the value of the specified number as an long. | 111 | | 6 | `int Integer.parseInt (String s) ` | parses the String argument as a signed decimal integer object | 112 | | | `int Integer.parseInt (String s, int radix) ` | parses the String argument as a signed decimal integer object in the specified radix by the second argument | 113 | | | `int Integer.parseInt (CharSequence s,int beginIndex,int endIndex,int radix)` | parses the CharSequence argument as a signed integer in the specified radix argument, beginning at the specified beginIndex and extending to endIndex - 1. | 114 | | 7 | `int Integer.reverse(int i) ` | method returns the numeric value obtained by reversing order of the bits in the specified int value. | 115 | | 8 | `int Integer.rotateLeft(int i, int distance)` | returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits. | 116 | | | ` int Integer.rotateRight(int i, int distance)` | returns the value obtained by rotating the two's complement binary representation of the specified int value right by the specified number of bits. | 117 | | 9 | `int Integer.signum(int i)` | (a>0): 1.0 / (a<0): -1.0 / (a==0): 0 | 118 | | 10 | `String Integer.toBinaryString (int i)` | returns a string representation of the integer argument as an unsigned integer in binary base 2. | 119 | | | `String Integer.toHexString (int i) ` | returns a string representation of the integer argument as an unsigned integer in binary base 16. | 120 | | | `String Integer.toOctalString (int i)` | returns a string representation of the integer argument as an unsigned integer in binary base 8. | 121 | | 11 | `String a.toString()` | returns a String object representing the value of the Number Object.(int/float/double/boolean etc) | 122 | | | `String Integer.toString(int i) ` | returns a string representation of the int type argument in base 10. | 123 | | | `String Integer.toString(int i, int radix)` | returns a string representation of the int type argument in the specified radix.(First int to radix conversion) | 124 | | 12 | `Integer Integer.valueOf(int i)` | returns the relevant Integer Object holding the value of the argument passed. | 125 | | | `Integer Integer.valueOf(String s)` | returns the relevant Integer Object holding the value of the argument passed. | 126 | | | `Integer Integer.valueOf(String s, int radix)` | convert to int and changes be base from radix to 10. | 127 | | 13 | `String Integer.toBinaryString(int val);` | convert to int to binary string. | 128 | 129 | \*valueOf is present in both Integer and String, Integer.valueOf() give Integer and String.valueOf() gives String 130 | 131 | ------------------------------------------------------------------------- 132 | 133 | ### Collections 134 | 135 | ![Alt text](./resources/Java-Collections-Hierarchy.png "Title") 136 | 137 | ```java 138 | Collection P = new "some type"(); 139 | Collection Q = new "some type"(); 140 | ``` 141 | 142 | | No. | Methods | Description | 143 | | --- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 144 | | 1 | `boolean P.add(E element)` | This method is used to add an object to the collection. | 145 | | 2 | `boolean P.addAll(Q);` | This method adds all the elements in the given collection to this collection. | 146 | | 3 | `P.clear()` | used to clear the Collection upon | 147 | | 4 | `boolean P.contains(Object element)` | returns true if the collection contains the specified element. | 148 | | 5 | `boolean P.containsAll(Q)` | returns true if the collection contains all of the elements in the given collection. | 149 | | 6 | `boolean P.equals(Q)` | This method compares the specified object with this collection for equality. | 150 | | 7 | `int P.hashCode()` | return the hash code value for this collection. | 151 | | 8 | `boolean P.isEmpty()` | This method returns true if this collection contains no elements. | 152 | | 9 | `Collections.max(P)` | used to return the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. | 153 | | 10 | `E P.remove(Object o)` | This method is used to remove the given object from the collection. If there are duplicate values, then this method removes the first occurrence of the object. | 154 | | 11 | `E P.removeAll(Q)` | This method is used to remove all the objects mentioned in the given collection from the collection. | 155 | | 12 | `int P.size()` | This method is used to return the number of elements in the collection. | 156 | | 13 | `Object[] objects = P.toArray();` | This method is used to return an array containing all of the elements in this collection. toArray() method returns an array of type Object(Object[]). We need to typecast it to Integer before using as Integer objects. | 157 | | 14 | `Arrays.sort(intervals,(a,b)->a[0]-b[0]);` | Sort an array with comparator. | 158 | | 15 | `void Arrays.fill(int[] ar, val);` | fill the 1D array with val variable | 159 | 160 | --------------------------------------------------------- 161 | 162 | ### Iterator 163 | 164 | Syntax : 165 | 166 | ```java 167 | Iterator i = Collection.iterator(); 168 | ``` 169 | 170 | | No. | Methods | Description | 171 | | --- | --------------------- | --------------------------------------------------------------------------------- | 172 | | 1 | `boolean i.hasNext()` | returns true if Iterator has more element to iterate. | 173 | | 2 | `Object i.next()` | returns the next element in the collection until the hasNext()method return true. | 174 | | 3 | `void i.remove()` | removes the current element in the collection. | 175 | 176 | ---------------------------------------- 177 | 178 | ### [List](https://www.geeksforgeeks.org/list-interface-java-examples/) 179 | List is an interface which is implemented by various DS such as ArrayList, Linklist etc. 180 | 181 | Syntax: 182 | 183 | ```java 184 | List x = new ArrayList(); 185 | List ll = new LinkedList(); 186 | List s = new Stack(); 187 | List v = new Vector(); 188 | ``` 189 | 2-D List 190 | ```java 191 | List> arr = new ArrayList<>() or List> arr = new ArrayList>() 192 | ``` 193 | 194 | 195 | | No. | Methods | Description | 196 | | --- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 197 | | 1 | `int x.size()` | returns length of an List | 198 | | 2 | `void x.add(int index, E element)` | used to insert the specified element at the specified position in a list. | 199 | | 3 | `boolean x.add(E e)` | used to append the specified element at the end of a list. | 200 | | 4 | `boolean x.addAll(Collection c) ` | used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. | 201 | | 5 | `boolean x.addAll(int index, Collection c)` | used to append all the elements in the specified collection, starting at the specified position of the list. | 202 | | 6 | `void x.clear()` | used to remove all of the elements from this list. | 203 | | 7 | `E x.get(int index)` | used to fetch the element from the particular position of the list. | 204 | | 8 | `boolean x.isEmpty()` | returns true if the list is empty, otherwise false. | 205 | | 9 | `Object[] x.toArray()` | used to return an array containing all of the elements in this list in the correct order. | 206 | | 10 | `Object x.clone()` | used to return a shallow copy of an ArrayList. | 207 | | 11 | `boolean x.contains(Object o)` | returns true if the list contains the specified element | 208 | | 12 | `int x.indexOf(Object o)` | used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. | 209 | | 13 | `E x.remove(int index)` | to remove the element present at the specified position in the list. | 210 | | 14 | `boolean x.remove(Object o)` | used to remove the first occurrence of the specified element. | 211 | | | `boolean x.removeAll(Collection c)` | used to remove all the elements from the list. | 212 | | 15 | `void x.removeRange(int fromIndex, int toIndex)` | to remove all the elements lies within the given range. | 213 | | 16 | `E x.set(int index, E element)` | used to replace the specified element in the list, present at the specified position. | 214 | | 17 | `void x.sort(Comparator c)` | used to sort the elements of the list on the basis of specified comparator. | 215 | | 18 | `List subList(int fromIndex, int toIndex)` | used to fetch all the elements lies within the given range. | 216 | 217 | List | Add | Remove | Get | Contains | Next | Data Structure 218 | ---------------------|------|--------|------|----------|------|--------------- 219 | ArrayList | O(1) | O(n) | O(1) | O(n) | O(1) | Array 220 | LinkedList | O(1) | O(1) | O(n) | O(n) | O(1) | Linked List 221 | 222 | - To initialise an ArrayList with another ArrayList we declare as `ArrayList arr2 = new ArrayList<>(arr1);` 223 | ### LinkedList 224 | 225 | Linked list extend List and dequeue interfaces so methods of both dequeue and list will work here 226 | Syntax: 227 | 228 | ```java 229 | LinkedList x =new LinkedList(); 230 | ``` 231 | 232 | E: data type 233 | ## Dequeue 234 | | No. | Methods | Description | 235 | | --- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 236 | | 1 | `boolean x.add(E e)` | to append the specified element to the end of a list. | 237 | | 2 | `boolean x.addAll(Collection c)` | used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. | 238 | | 3 | `void x.addFirst(E e)` | used to insert the given element at the beginning of a list. | 239 | | | `void x.addLast(E e)` | used to append the given element to the end of a list. | 240 | | 4 | `void x.clear()` | used to remove all the elements from a list. | | 241 | | 5 | `boolean x.contains(Object o)` | used to return true if a list contains a specified element. | 242 | | 6 | `E x.element()` | used to retrieve the first element of a list. | 243 | | 7 | `boolean x.offer(E e)` | adds the specified element as the last element of a list. | 244 | | 8 | `E x.peek()` | retrieves the first element of a list | 245 | | | `E x.poll()` | It retrieves and removes the first element of a list. | 246 | | 9 | `int x.size()` | used to return the number of elements in a list. | | 247 | | 10 | `E x.remove()` | used to remove the head of queuee. | 248 | | 11 | `E x.removeFirst()` | Removes and returns the first element of the deque. Throws an exception if the deque is empty. | 249 | | 12 | `E x.removeLast()` | Removes and returns the last element of the deque. Throws an exception if the deque is empty. | 250 | 251 | pollFirst, pollLast, offerFirst, offerLast, peekFirst, peekLast, removeFirst, removeLast, removeFirstOccurance, removeLastOccurance 252 | ### ListItrator 253 | 254 | ‘ListIterator’ in Java is an Iterator which allows users to traverse Collection in both direction. 255 | 256 | Syntax: 257 | 258 | ```java 259 | ListIterator li = list.listIterator(); 260 | ``` 261 | 262 | | No. | Methods | Description | 263 | | --- | ---------------------------- | ------------------------------------------------------------------------------------------ | 264 | | 1 | `void li.add(Object object)` | It inserts object immediately before the element that is returned by the next( ) function. | 265 | | 2 | `boolean li.hasNext( )` | returns true if the list has a next element. | 266 | | 3 | `boolean li.hasPrevious( ):` | returns true if the list has a previous element. | 267 | | 4 | `Object li.next( )` | returns the next element of the list. | 268 | | 5 | `Object li.previous( )` | returns the previous element of the list. | 269 | | 6 | `void li.remove( )` | removes the current element from the list. | 270 | 271 | ---------------------------------------------------- 272 | 273 | ### [Map](https://www.geeksforgeeks.org/map-interface-java-examples/) 274 | 275 | ![Alt text](./resources/java-map-hierarchy.png "Title") 276 | 277 | ```java 278 | Map m=new HashMap(); 279 | Map map = new LinkedHashMap(); 280 | Map map = new TreeMap(); 281 | ``` 282 | 283 | 284 | | No. | Methods | Description | 285 | | --- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------- | 286 | | 1 | `void m.put(Object key, Object value)` | used to insert an entry in the map. | 287 | | 2 | `void m.putAll(Map map)` | used to insert the specified map in the map. | 288 | | 3 | `void m.putIfAbsent(K key, V value)` | It inserts the specified value with the specified key in the map only if it is not already specified. | 289 | | 4 | `void m.remove(Object key)` | used to delete an entry for the specified key. | 290 | | 5 | `boolean m.remove(Object key, Object value)` | It removes the specified values with the associated specified keys from the map. | 291 | | 6 | `void m.clear()` | used to reset the map. | 292 | | 7 | `boolean m.containsValue(Object value)` | This method returns true if some value equal to the value exists within the map, else return false. | 293 | | | `boolean containsKey(Object key)` | This method returns true if some key equal to the key exists within the map, else return false. | 294 | | 8 | `boolean equals(Object o)` | used to compare the specified Object with the Map. | 295 | | 9 | `V m.get(Object key)` | This method returns the object that contains the value associated with the key else returns null | 296 | | 10 | `boolean m.isEmpty()` | This method returns true if the map is empty; returns false if it contains at least one key. | 297 | | 11 | `int m.size()` | This method returns the number of entries in the map. | 298 | | 12 | `map.forEach((key, value) -> {map.put(key,value+2);});` | Traverse through the values in a map | 299 | 300 | Map.Entry 301 | ```java 302 | for (Map.Entry entry : gfg.entrySet()) 303 | System.out.println("Key = " + entry.getKey() + 304 | ", Value = " + entry.getValue()); 305 | } 306 | 307 | 1 for (Map.Entry entry : map.entrySet()) { ... } Iterates through the key-value pairs using entrySet(). 308 | 2 for (K key : map.keySet()) { ... } Iterates through only the keys using keySet(). 309 | 3 for (V value : map.values()) { ... } Iterates through only the values using values(). 310 | 4 map.forEach((key, value) -> { ... }); Uses the forEach method with a lambda expression. 311 | ``` 312 | 313 | | Map | Get | ContainsKey | Next | Data Structure 314 | ----------------------|----------|-------------|----------|------------------------- 315 | HashMap | O(1) | O(1) | O(h / n) | Hash Table 316 | LinkedHashMap | O(1) | O(1) | O(1) | Hash Table + Linked List 317 | EnumMap | O(1) | O(1) | O(1) | Array 318 | TreeMap | O(log n) | O(log n) | O(log n) | Red-black tree 319 | 320 | --------------------------- 321 | 322 | Here's a new section you can add to your `#lastMinuteJavaSyntax` cheat sheet for **TreeMap in Java**, including syntax, important methods, and complexity: 323 | 324 | --- 325 | 326 | ### [TreeMap](https://www.geeksforgeeks.org/treemap-in-java/) 327 | 328 | A `TreeMap` in Java is a `Map` implementation that keeps its keys **sorted in natural order** or by a custom comparator. Internally, it uses a **Red-Black Tree**. 329 | 330 | ```java 331 | Map map = new TreeMap<>(); 332 | TreeMap tm = new TreeMap<>(); 333 | TreeMap tm = new TreeMap<>(Collections.reverseOrder()); // custom comparator 334 | ``` 335 | 336 | #### Key Properties 337 | 338 | * Sorted based on keys (not insertion order). 339 | * Logarithmic time complexity: **O(log n)** for `put`, `get`, `remove`. 340 | 341 | --- 342 | 343 | | No. | Methods | Description | 344 | | --- | ------------------------------------- | ------------------------------------------------------------------------------------------------ | 345 | | 1 | `V get(Object key)` | Returns the value associated with the specified key. | 346 | | 2 | `V put(K key, V value)` | Inserts or updates the key-value pair. | 347 | | 3 | `V remove(Object key)` | Removes the mapping for this key if present. | 348 | | 4 | `boolean containsKey(Object key)` | Returns true if the map contains a mapping for the specified key. | 349 | | 5 | `boolean containsValue(Object val)` | Returns true if the map maps one or more keys to the specified value. | 350 | | 6 | `K firstKey()` | Returns the **lowest** key currently in this map. | 351 | | 7 | `K lastKey()` | Returns the **highest** key currently in this map. | 352 | | 8 | `Map.Entry firstEntry()` | Returns a key-value mapping associated with the lowest key. | 353 | | 9 | `Map.Entry lastEntry()` | Returns a key-value mapping associated with the highest key. | 354 | | 10 | `Map.Entry higherEntry(K key)` | Returns the least entry **strictly greater** than the given key. | 355 | | 11 | `Map.Entry lowerEntry(K key)` | Returns the greatest entry **strictly less** than the given key. | 356 | | 12 | `Map.Entry floorEntry(K key)` | Returns the greatest entry **less than or equal** to the given key. | 357 | | 13 | `Map.Entry ceilingEntry(K key)` | Returns the least entry **greater than or equal** to the given key. | 358 | | 14 | `SortedMap subMap(K from, K to)` | Returns a view of the portion of this map from `fromKey` (inclusive) to `toKey` (exclusive). | 359 | | 15 | `SortedMap headMap(K toKey)` | Returns a view of the portion of this map whose keys are **strictly less** than `toKey`. | 360 | | 16 | `SortedMap tailMap(K fromKey)` | Returns a view of the portion of this map whose keys are **greater than or equal** to `fromKey`. | 361 | | 17 | `Set keySet()` | Returns a set view of the keys contained in this map. | 362 | | 18 | `Collection values()` | Returns a collection view of the values contained in this map. | 363 | | 19 | `Set> entrySet()` | Returns a set view of the key-value mappings. | 364 | 365 | --- 366 | 367 | #### Example: 368 | 369 | ```java 370 | TreeMap tm = new TreeMap<>(); 371 | tm.put(3, "Three"); 372 | tm.put(1, "One"); 373 | tm.put(2, "Two"); 374 | 375 | System.out.println(tm); // Output: {1=One, 2=Two, 3=Three} 376 | System.out.println(tm.higherKey(2)); // Output: 3 377 | System.out.println(tm.firstEntry().getValue()); // Output: One 378 | ``` 379 | 380 | --- 381 | 382 | Let me know if you want a version comparing `TreeMap` vs `HashMap` in a table! 383 | ---------------------------------- 384 | 385 | ### [Set](https://www.geeksforgeeks.org/set-in-java/) 386 | Since Set is an interface, objects cannot be created of the type Set. We always need a class which extends this list in order to create an object. 387 | 388 | Syntax 389 | ```java 390 | Set hs = new HashSet(); 391 | Set lhs = new LinkedHashSet(); 392 | Set ts = new TreeSet(); 393 | ``` 394 | | No. | Methods | TC(HS) | TC(LHS) | TC(TS) | Description | 395 | | --- | ------------| ---- | ---- | ------------------------ | ----------------------------------------------------------------------------------------------------- | 396 | | 1 | `boolean add(E e)` | O(1) | O(1) | O(log n) | It is used to add the specified element to this set if it is not already present. | 397 | | 2 | `void clear() ` | O(1) | O(1) | O(1) | It is used to remove all of the elements from the set. | 398 | | 3 | `boolean contains(Object o)` | O(1) | O(1) | O(log n) | It is used to return true if this set contains the specified element. | 399 | | 4 | `boolean isEmpty()` | O(1) | O(1) | O(1) | It is used to return true if this set contains no elements. | 400 | | 5 | `boolean remove(Object o)` | O(1) | O(1) | O(log n) | It is used to remove the specified element from this set if it is p. | 401 | | 6 | `int size()` | O(1) | O(1) | O(1) | It is used to return the number of elements in the set. | 402 | | 7 | `Iterator iterator()` | O(h/n) | O(1) | O(log n) | It is used to return an iterator over the elements in this set. | 403 | 404 | Itrator Syntax: 405 | ```java 406 | 1 for (E element : set) { ... } - Uses an enhanced for loop to iterate through each element in the set. 407 | 2 Iterator iterator = set.iterator(); while (iterator.hasNext()) { E element = iterator.next(); } - Uses an Iterator to traverse the set, allowing element removal during iteration. 408 | 3 set.forEach(e -> { ... }); - Uses the forEach method with a lambda expression for iteration. 409 | ``` 410 | Set | Add | Remove | Contains | Next | Size | Data Structure 411 | ----------------------|----------|----------|----------|----------|------|------------------------- 412 | HashSet | O(1) | O(1) | O(1) | O(h/n) | O(1) | Hash Table 413 | LinkedHashSet | O(1) | O(1) | O(1) | O(1) | O(1) | Hash Table + Linked List 414 | EnumSet | O(1) | O(1) | O(1) | O(1) | O(1) | Bit Vector 415 | TreeSet | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree 416 | 417 | 418 | ---------------------------- 419 | 420 | ### [Queue](https://www.geeksforgeeks.org/queue-interface-java/) 421 | 422 | Since Queue is an interface, objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. 423 | 424 | Syntax: 425 | 426 | ```java 427 | Normal queue: Queue lQueue = new LinkedList(); 428 | 429 | Priority Queue: Queue pQueue = new PriorityQueue(); 430 | Queue pbq = new PriorityBlockingQueue(); 431 | ``` 432 | To declare a [Priority queue](http://www.learn4master.com/algorithms/java-priorityqueue-example) which returns maximum value using MaxHeap 433 | ```java 434 | Queue queue = new PriorityQueue(int initialCapacity, Comparator comparator); 435 | PriorityQueue queue = new PriorityQueue<>(size, Collections.reverseOrder()); 436 | ``` 437 | 438 | | No. | Methods | TC(Q) | TC(PQ) | Description | 439 | | --- | ------------------------- | --- | --- |----------------------------------------------------------------------------------------------------------- | 440 | | 1 | `boolean q.add(object) ` | O(1) | O(log n) | This method is used to add elements at the tail of queue. More specifically, at the last of linked-list if it is used, or according to the priority in case of priority queue implementation. | 441 | | | `boolean q.offer(object)` | O(1) | O(log n) | This method is used to insert an element in the queue. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false. | 442 | | 2 | `Object q.peek()` | O(1) | O(1) | This method is used to view the head(first in) of queue without removing it. It returns Null if the queue is empty. | 443 | | | `Object q.element()` | O(1) | O(1) | This method is similar to peek(). It throws NoSuchElementException when the queue is empty. | 444 | | 3 | `Object q.remove()` | O(1) | O(log n) | This method removes and returns the head of the queue. It throws NoSuchElementException when the queue is empty. | 445 | | | `Object q.poll()` | O(1) | O(log n) | This method removes and returns the head of the queue. It returns null if the queue is empty. | 446 | 447 | ### Stack 448 | In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. 449 | ```java 450 | Stack stk = new Stack(); 451 | ``` 452 | | No. | Methods | TC | Description | 453 | | --- | ------------------------- | --- |----------------------------------------------------------------------------------------------------------- | 454 | | 1 | `boolean stk.empty()` | | The method checks the stack is empty or not. | 455 | | 2 | `E stk.push(E item)` or `add(E item)` | | The method pushes (insert) an element onto the top of the stack. | 456 | | 3 | `E stk.pop()` | | The method removes an element from the top of the stack and returns the same element as the value of that function. | 457 | | 4 | `E stk.peek()` | | The method looks at the top element of the stack without removing it. | 458 | | 5 | `int stk.search(Object o)` | | The method searches the specified object and returns the position of the object. | 459 | 460 | --- 461 | 462 | ## [Streams](https://stackify.com/streams-guide-java-8/) [](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html) 463 | ``` 464 | List names = Arrays.asList("Alice", "Bob", "Charlie"); 465 | Stream nameStream = names.stream(); 466 | 467 | String[] colors = {"Red", "Green", "Blue"}; 468 | Stream colorStream = Arrays.stream(colors); 469 | 470 | Stream numbers = Stream.of(1, 2, 3, 4, 5); 471 | ``` 472 | ### Intermediate Operations 473 | | No. | Methods | Description | 474 | | --- | ------------------------- | --------------- | 475 | | 1 | .map(value -> value + 4 | map() produces a new stream after applying a function to each element of the original stream. The new stream could be of different type. | 476 | | 2 | .filter(Predicate) | this produces a new stream that contains elements of the original stream that pass a given test (specified by a Predicate). | 477 | | 3 | .distinct() | does not take any argument and returns the distinct elements in the stream, eliminating duplicates. It uses the equals() method of the elements to decide whether two elements are equal or not. | 478 | | 4 | .sorted((e1, e2) -> e1.getName().compareTo(e2.getName())) | this sorts the stream elements based on the comparator passed we pass into it. | 479 | | 5 | .limit(n) | limit the number of elements in the output for n | 480 | | 6 | .skip(n) | skip the first n elements of the list | 481 | | 6 | .peek() | same as forEach function in terminal operations, instead its a intermediate operation. | 482 | | 7 | .min() .max(Comparator.comparing(Employee::getSalary)) | min() and max() return the minimum and maximum element in the stream respectively, based on a comparator. They return an Optional since a result may or may not exist (due to, say, filtering) | 483 | 484 | 485 | 486 | ### Terminal Operations 487 | | No. | Methods | Description | 488 | | --- | ------------------------- | --- | 489 | | 1 | .forEach(e -> e.operation(10.0)) | Filters elements based on a condition. | 490 | | 2 | .collect(Collector.toList()) | performs mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in the Stream instance. | 491 | | 3 | .count() | Counts the number of entries in the stream. | 492 | | 4 | .anyMatch(Predicate) | checks if the predicate is true for all the elements in the stream. Here, it returns false as soon as it encounters 5, which is not divisible by 2. | 493 | | | .allMatch(Predicate) | checks if the predicate is true for any one element in the stream. Here, again short-circuiting is applied and true is returned immediately after the first element. | 494 | | | .noneMatch(i -> i % 2 == 0) | checks if there are no elements matching the predicate. Here, it simply returns false as soon as it encounters 6, which is divisible by 3 | 495 | | 5 | .findAny() | | 496 | | 6 | .reduce() | takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation | 497 | 498 | 499 | --- 500 | 501 | ## Comparators 502 | ### 1. `naturalOrder()` 503 | - Returns a comparator that compares `Comparable` objects in their natural order (ascending order). 504 | - **Example**: `Comparator naturalOrderComparator = Comparator.naturalOrder();` 505 | 506 | ### 2. `reverseOrder()` 507 | - Returns a comparator that compares `Comparable` objects in reverse of their natural order (descending order). 508 | - **Example**: `Comparator reverseOrderComparator = Comparator.reverseOrder();` 509 | 510 | ### 3. `nullsFirst(Comparator comparator)` 511 | - Returns a comparator that considers `null` to be less than non-null. If both objects are non-null, it uses the provided comparator. 512 | - **Example**: `Comparator nullsFirstComparator = Comparator.nullsFirst(Comparator.naturalOrder());` 513 | 514 | ### 4. `nullsLast(Comparator comparator)` 515 | - Returns a comparator that considers `null` to be greater than non-null. If both objects are non-null, it uses the provided comparator. 516 | - **Example**: `Comparator nullsLastComparator = Comparator.nullsLast(Comparator.naturalOrder());` 517 | 518 | ### 5. `comparing(Function keyExtractor)` 519 | - Returns a comparator that compares objects based on the result of the function applied to each object (key extractor). 520 | - **Example**: `Comparator byNameComparator = Comparator.comparing(Person::getName);` 521 | - **Explanation**: Compares `Person` objects by their `name` attribute. 522 | 523 | ### 6. `comparing(Function keyExtractor, Comparator keyComparator)` 524 | - Returns a comparator that compares objects based on the result of the key extractor function and orders them according to the provided comparator. 525 | - **Example**: `Comparator byNameDescending = Comparator.comparing(Person::getName, Comparator.reverseOrder());` 526 | - **Explanation**: Compares `Person` objects by their `name` attribute in descending order. 527 | 528 | ### 7. `comparingInt(ToIntFunction keyExtractor)` 529 | - Returns a comparator that compares objects based on an integer key extracted from each object. 530 | - **Example**: `Comparator byAgeComparator = Comparator.comparingInt(Person::getAge);` 531 | - **Explanation**: Compares `Person` objects by their `age` attribute. 532 | 533 | ### 8. `comparingLong(ToLongFunction keyExtractor)` 534 | - Returns a comparator that compares objects based on a long key extracted from each object. 535 | - **Example**: `Comparator bySalaryComparator = Comparator.comparingLong(Person::getSalary);` 536 | - **Explanation**: Compares `Person` objects by their `salary` attribute. 537 | 538 | 539 | 540 | 541 | ### Cool Resources 542 | 1. Complete Time Complexity of Collections library - https://github.com/itsPrasheel/lastMinuteJavaSyntax/blob/master/CollectionTC.md 543 | 2. 544 | -------------------------------------------------------------------------------- /dataStructureUsage.md: -------------------------------------------------------------------------------- 1 | ## Tree Map 2 | A tree map is a map which is sorted on the key values when you pass through with an iterator. 3 | 4 | --- 5 | ## Linked HashMap 6 | A linked Hashmap is used when you want to maintain the order in which you added the elements to the map. 7 | 8 | --- 9 | 10 | ## Trie Data Structure 11 | A Trie data structure is a very useful data structure that can be used to store words which is very easy to search. It stores the subsequent letters recursively in a tree which can be very helpful for searching words. 12 | ![Alt text](./resources/trieDS.png "Title") 13 | -------------------------------------------------------------------------------- /generalFunctions.md: -------------------------------------------------------------------------------- 1 | Binary Search 2 | ```java 3 | /** 4 | * Binary‑search helpers for **sorted** (ascending) int arrays. 5 | * 6 | * All methods run in O(log n) time and O(1) space. 7 | */ 8 | public final class BinSearch { 9 | 10 | private BinSearch() {} // utility class ⇒ no instances 11 | 12 | /** Classic binary search: returns index of target or ‑1 if not present. */ 13 | public static int binarySearch(int[] a, int target) { 14 | int lo = 0, hi = a.length - 1; 15 | while (lo <= hi) { 16 | int mid = lo + (hi - lo) / 2; 17 | if (a[mid] == target) return mid; 18 | if (a[mid] < target) lo = mid + 1; 19 | else hi = mid - 1; 20 | } 21 | return -1; 22 | } 23 | 24 | /** 25 | * Lower bound: first index whose value is ≥ target. 26 | * If every element is < target, returns a.length (i.e., “insert at end”). 27 | */ 28 | public static int lowerBound(int[] a, int target) { 29 | int lo = 0, hi = a.length; // hi is exclusive 30 | while (lo < hi) { 31 | int mid = lo + (hi - lo) / 2; 32 | if (a[mid] < target) lo = mid + 1; 33 | else hi = mid; // keep mid (it’s ≥ target) 34 | } 35 | return lo; 36 | } 37 | 38 | /** 39 | * Upper bound: first index whose value is > target. 40 | * If every element is ≤ target, returns a.length. 41 | */ 42 | public static int upperBound(int[] a, int target) { 43 | int lo = 0, hi = a.length; // hi is exclusive 44 | while (lo < hi) { 45 | int mid = lo + (hi - lo) / 2; 46 | if (a[mid] <= target) lo = mid + 1; 47 | else hi = mid; // keep mid (it’s > target) 48 | } 49 | return lo; 50 | } 51 | 52 | /* ── tiny demo ─────────────────────────────────────────────── */ 53 | public static void main(String[] args) { 54 | int[] nums = {1, 3, 3, 5, 7, 7, 7, 9}; 55 | 56 | System.out.println(binarySearch(nums, 5)); // 3 57 | System.out.println(lowerBound(nums, 7)); // 4 58 | System.out.println(upperBound(nums, 7)); // 7 59 | System.out.println(lowerBound(nums, 4)); // 3 (insert pos) 60 | System.out.println(upperBound(nums, 10)); // 8 (end of array) 61 | } 62 | } 63 | 64 | 65 | ``` 66 | 67 | # Trie 68 | 69 | ```haa 70 | public List searchKeys(TrieNode node, String text, int index){ 71 | List res = new ArrayList<>(); 72 | int count = 0; 73 | for(int i=index;i