├── .gitignore ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 hamza94max 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures 2 | 3 | ### Data Structures in Java
4 | A **data structure** is a data organization, management, and storage format that enables efficient access and modification

5 | 6 | 7 |


8 | 9 | 10 | 11 |
12 | Array 13 |
14 | • Arrays give us the ability to: 15 | - Store a (potentially large) collection of homogeneous data 16 | - Have direct access to any one element in the collection by its position
17 | 18 | 19 | **Syntax** 20 | type[] array_name = new type[length];

21 | 22 | 23 | 24 | **Access the Elements of an Array** 25 | ``` java 26 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 27 | System.out.println(cars[0]); 28 | // Outputs Volvo 29 | ``` 30 | 31 | 32 | **Change an Array Element** 33 | 34 | ``` java 35 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 36 | cars[0] = "Opel"; 37 | System.out.println(cars[0]); 38 | // Now outputs Opel instead of Volvo 39 | ``` 40 | 41 | **Array Length** 42 | To find out how many elements an array has, use the length property:
43 | ``` java 44 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 45 | System.out.println(cars.length); 46 | // Outputs 4 47 | ``` 48 | 49 |
50 | 51 | **loop to print all elements in Array** 52 | ``` java 53 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; 54 | for (int i = 0; i < cars.length; i++) { 55 | System.out.println(cars[i]);} 56 | ``` 57 | 58 | 59 | **Resize the size of array** 60 | when you reach capacity, resize to double the size 61 | ``` java 62 | int count = cars.length; 63 | String [] newitems = new String [count*2]; 64 | //copy the elements to new array 65 | for (int i = 0; i < count; i++){ 66 | newitems [i] = cars[i]; 67 | } 68 | ``` 69 | 70 |

71 | 72 | 73 | 74 |
75 | 76 | 77 | 78 | 79 | 80 | **Time**
81 | - **O(1)** to add/remove at end (amortized for allocations for more space), index, or update
82 | - **O(n)** to insert/remove elsewhere
83 | 84 | **Space**
85 | - contiguous in memory, so proximity helps performance
86 | - space needed = (array capacity, which is >= n) * size of item, but even if 2n, still O(n)
87 | 88 | 89 | **resources** 90 | 1. [Arrays (Video)](https://www.coursera.org/lecture/data-structures/arrays-OsBSF) 91 | 2. [ Arrays (CS50)](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4) 92 | 3. [Dynamic Arrays (resize array)](https://www.coursera.org/lecture/data-structures/dynamic-arrays-EwbnV) 93 | 4. [CS50 lecture](https://www.youtube.com/watch?v=xC3BZa1pcsY&list=PLhQjrBD2T380Xnv_v683p6UjiKJZe13ki&index=3) 94 | 95 |
96 | 97 | 98 | 99 |
100 | 101 | 102 | 2D Array 103 |
104 | A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself. For example
105 | 106 | ``` java 107 | int[][] a = new int[3][4]; 108 | ``` 109 | 110 | 111 | 112 | 113 | **Loop to print 2D array**
114 | ``` java 115 | int[][] board = new int [3] [3]; 116 | for (int i = 0; i < board.length; i++) { 117 | for (int j = 0; j < board[i].length; j++) { 118 | System.out.print(board[i][j] + "\t"); 119 | } 120 | } 121 | ``` 122 | 123 |
124 | 125 |
126 |
127 | 128 | LinkedList 129 |
130 | LinkedList is a data structure wherein each element contains both a data value and a pointer to next element in the list

131 | 132 | 133 | Linkedlists accommodate items of varying sizes and allow easy insertion 134 | and deletion of items.
135 | One potential disadvantage of using a list is that 136 | performance for retrieving a specified item in a list of size n is linear — **O(n)**, 137 | as it requires potentially traversing all n elements in the worst case.

138 | 139 | ### **Lists are sometimes used directly by kernel algorithms** 140 | 141 | 142 | 143 | 144 | 145 |
146 | 147 | **Array V.S Linkedlist** 148 | 1) Size of the array is fixed **v.s** Linked list allows dynamic memory allocation
149 | 2) Array elements need contiguous memory locations to store their values **v.s** Linked list elements don’t need contiguous memory locations
150 | 3) Inserting an element in an array is performance wise expensive **v.s** Insert and delete operations in the Linked list are not performance wise expensive because adding and deleting an element from the linked list does’t require element shifting, only the pointer of the previous and the next node requires change.
151 | 152 | 153 | 154 | 155 | 156 | 157 | **Funcations** 158 | ``` java 159 | LinkedList al=new LinkedList(); 160 | al.add("Ravi"); 161 | al.addFirst("First Item"); 162 | al.getFirst(); 163 | al.getLast(); 164 | al.addLast("Last Item"); 165 | al.removeFirst(); 166 | al.removeLast(); 167 | al.remove(2); 168 | al.get(2); 169 | al.size(); 170 | // clear the list 171 | al.clear(); 172 | // clone al ( returns the exact same copy of the Linked List object ) 173 | list2 = (LinkedList) al.clone(); 174 | ``` 175 | 176 |
177 | 178 | 179 | **Time**
180 | - **O(1)** to add/remove at end (amortized for allocations for more space), index, or update
181 | - **O(n)** to insert/remove elsewhere
182 | 183 | **Space**
184 | - The amount of data stored increases linearly with the number of nodes in the list. Therefore, the space complexity of the linked list is linear: **O(n)** 185 | 186 | ### Resources 187 | - [Website ](https://beginnersbook.com/2013/12/linkedlist-in-java-with-example/) 188 | - [CS 61B Lecture](https://archive.org/details/ucberkeley_webcast_htzJdKoEmO0) 189 | - [Lists vs. Arrays](https://www.coursera.org/learn/data-structures-optimizing-performance/lecture/QUaUd/in-the-real-world-lists-vs-arrays) 190 | - [Why you should avoid Linked Lists](https://www.youtube.com/watch?v=YQs6IC-vgmo) 191 | 192 |
193 |
194 | 195 | 196 | Stack 197 |
198 | 199 | A **Stack** is a sequentially ordered data structure that uses the last in, first 200 | out (LIFO) principle for adding and removing items, meaning that the last item 201 | placed onto a stack is the first item removed. The operations for inserting and 202 | removing items from a stack are known as push and pop, respectively. 203 | 204 | ### operating system often uses a stack when invoking function calls.
205 | 206 | Parameters,local variables, and the return address are pushed onto the stack when a 207 | function is called; returning from the function call pops those items off the 208 | stack. 209 | 210 | 211 | 212 | 213 |

214 | 215 | 216 | **Creating a Stack** 217 | ``` java 218 | Stack stacks = new Stack<>(); 219 | ``` 220 | 221 | 222 | **example**
223 | ``` java 224 | Stack animals = new Stack<>(); 225 | animals.push("Dog"); 226 | animals.push("Horse"); 227 | System.out.println("Stack: " + animals); 228 | ``` 229 | 230 | 231 | _**When we push an element into the stack the top is increased by 1.**_

232 | 233 | 234 |

235 | 236 | 237 | 238 | 239 | **other Funcations** 240 | > 241 | **empty()** The method checks the stack is empty or not.
242 | **push(E item)** The method pushes (insert) an element onto the top of the stack.
243 | **pop()** The method removes an element from the top of the stack and returns the same element as the value of that function.
244 | **peek()** The method looks at the top element of the stack without removing it.
245 | **search(Object o)** The method searches the specified object and returns the position of the object
246 | **size()** to get the size of the Stack
247 | 248 | **Resources**
249 | - [Stacks (CS 50)](https://www.youtube.com/watch?v=hVsNqhEthOk)
250 | - [Stacks(Coursera)](https://www.coursera.org/lecture/data-structures/stacks-UdKzQ) 251 | 252 | 253 | 254 | 255 | 256 |
257 | 258 |
259 | Queue 260 |

261 | 262 | **Queue** is a data structure which follows the principle of **FIFO** (First-In-First-Out)
263 | items are removed from a queue in the order 264 | in which they were inserted. There are many everyday examples of queues, 265 | including shoppers waiting in a checkout line at a store and cars waiting in line 266 | at a traffic signal. Queues are also quite common in operating systems—jobs 267 | that are sent to a printer are typically printed in the order in which they were 268 | submitted, for example

269 | 270 | **tasks that are waiting to be run on an available CPU are often organized in queues.** 271 |


272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 |

280 | 281 | **FRONT** track the first element of the queue
282 | **REAR** track the last elements of the queue
283 | _**initially, set value of FRONT and REAR to -1**_

284 | 285 | **Funcations**
286 | - **Enqueue()**: Add an element to the end of the queue _(increase the REAR index by 1)_ 287 | - **Dequeue()**: Remove an element from the front of the queue _(increase the FRONT index by 1)_ 288 | - **IsEmpty()**: Check if the queue is empty 289 | - **IsFull()**: Check if the queue is full 290 | - **Peek()**: Get the value of the front of the queue without removing it

291 | 292 | 293 | 294 | **Complexity Analysis**
295 | The complexity of enqueue and dequeue operations in a queue using an array is ***O(1)**.
296 | a bad implementation using linked list where you enqueue at head and dequeue at tail would be O(n) because you'd need the next to last element, causing a full traversal each dequeue

297 | 298 | **Applications of Queue** 299 | - Serving requests on a single shared resource, like a printer, CPU task scheduling etc. 300 | - In real life scenario, Call Center phone systems uses Queues to hold people calling them in an order, until a service representative is free.

301 | 302 | 303 | **Resources**
304 | - [Queue (video)](https://www.coursera.org/lecture/data-structures/queues-EShpq)
305 | - [Queue (CS50)](https://www.youtube.com/watch?v=3TmUv1uS92s)
306 | - [Website](https://www.programiz.com/dsa/queue)
307 | - [Code Resources](https://www.softwaretestinghelp.com/java-queue-interface/)
308 | 309 | 310 | 311 |
312 | 313 | 314 | 315 | 316 |
317 | Hash table 318 |
319 | 320 | **Hashtable** is a combination of an array and linkedlist inside of it . 321 | Called Dictionary in Python
322 | 323 | A **hash function** takes data as its input, performs a numeric operation on this 324 | data, and returns a numeric value. This numeric value can then be used as an 325 | index into a table (typically an array) to quickly retrieve the data.


326 | 327 | **Because of this performance, hash functions are used extensively in 328 | operating systems.**
329 | 330 | 331 | 332 | 333 | 334 |

335 | 336 | 337 | 338 | ### One potential difficulty with hash functions is that two inputs can result in the same output value—that is, they can link to the same table location. We can accommodate this hash collision by having a linked list at that table location that contains all of the items with the same hash value. Of course, the more collisions there are, the less efficient the hash function is.

339 | 340 | 341 | 342 | 343 | - The Hash Function should be such that the keys generated are uniformly distributed. 344 | - The size of the Hash Table is dependent on the Hash Function. So, the choice of Hash Function should be done perfectly. 345 | - In the case of a collision in the Hash Table, apply proper collision handling technique. 346 | 347 | 348 | 349 | ``` java 350 | Hashtable hashtable = new Hashtable<>(); 351 | //2. Add mappings to hashtable 352 | hashtable.put(1, "A"); 353 | hashtable.put(2, "B" ); 354 | hashtable.put(3, "C"); 355 | System.out.println(hashtable); 356 | //output 357 | {3 = C, 2 = B, 1 = A} 358 | ``` 359 | 360 | 361 | **Methods** 362 | - **Object put(Object key, Object value) :** It maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. 363 | - **Object remove(Object key) :** It removes the key (and its corresponding value) from hashtable. 364 | - **boolean containsValue(Object value) :** It returns true if specified value exist within the hash table for any pair, else return false. 365 | - **void clear()** : It is used to remove all pairs in the hashtable. 366 | - **Object get(Object key) :** It returns the value to which the specified key is mapped. Returns null if no such key is found. 367 | - **void rehash() :** It is used to increase the size of the hash table and rehashes all of its keys. 368 | - **int size() :** It returns the number of entries in the hash table. 369 | 370 | 371 | 372 | 373 | **Time**
374 | The Hash Table will perform the insertion, deletion, and searching operation in **O(1)** time.
375 | searching for a data item through a list of size n can require up to **O(n)** 376 | comparisons in the worst case
377 | 378 | 379 | **Resources**
380 | [Hash tables (CS50) ](https://www.youtube.com/watch?v=nvzVHwrrub0)
381 | [CS 50 lecture](https://www.youtube.com/watch?v=4IrUAqYKjIA&list=PLhQjrBD2T381L3iZyDTxRwOBuUt6m1FnW&index=6&t=4702s)
382 | [Hashing with Chaining (MIT lecture)](https://www.youtube.com/watch?v=0M_kIqhwbFo)
383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 |
392 | 393 | 394 | 395 |
396 | Tree 397 |
398 | 399 | A **tree** is a data structure that can be used to represent data hierarchically. Data 400 | values in a tree structure are linked through parent–child relationships.
401 | 402 | 403 | 404 | In a binary tree, a parent **may have at most two children**, which we term the left child 405 | and the right child
406 | 407 | additionally requires an ordering between the parent’s two children in which lef t child <= right child.
408 | 409 | **Linux uses a balanced binary search tree as part its CPU-scheduling algorithm.** 410 | 411 | 412 | 413 |

414 | 415 | 416 | 417 | 418 | 419 | 420 |

421 | 422 | 423 | - **Root**: Root is the node that is present at the top of the tree. There can be only one root of a particular tree. 424 | - **Parent**: All the nodes having at least one child is called the parent node. 425 | - **Child**: The node below the parent node is called the child node of the parent node. 426 | - **Leaf**: The node having zero children is called the leaf node. 427 | 428 | 429 | 430 | ## **Time**
431 | When we search for an item in a binary search tree, the worst-case performance is **O(n)** 432 | 433 | 434 | **Resources**
435 | [ Introduction To Trees ( Arabic )](https://www.youtube.com/watch?v=XDDZNL-yG2U) 436 | 437 | 438 |
439 | 440 | 441 | 442 |
443 | Graph 444 |
445 | What is a graph?
446 | A graph models a set of connections. For 447 | example, suppose you and your friends are 448 | playing poker, and you want to model who owes 449 | whom money. Here’s how you could say, “Alex 450 | owes Rama money.”

451 | 452 | 453 | 454 |

455 | 456 | **That’s all there is to it! Graphs are made up of nodes and edges. A node can be directly connected to many other nodes.** 457 | 458 | Vertex: Vertices are the point that joints edges. It represents the data. It is also known as a node. It is denoted by a circle and it must be labeled. To construct a graph there must be at least a node. For example, house, bus stop, etc. 459 | 460 | Edge: An edge is a line that connects two vertices. It represents the relation between the vertices. Edges are denoted by a line. For example, a path to the bus stop from your house. 461 | 462 | 463 | **resources** 464 | 1. [Graph](https://www.javatpoint.com/java-graph) 465 | 466 | 467 | 468 | 469 |
470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 |

480 | 481 | 482 | 483 | 484 | 485 | 486 | ## Books 487 | - [Grokking Algorithms ](https://github.com/camoverride/lit/blob/master/Grokking-Algorithms.pdf) 488 | 489 | 490 | 491 | 492 | ## Courses 493 | - [CS 50 (Course)](https://www.youtube.com/watch?v=4IrUAqYKjIA&list=PLhQjrBD2T381L3iZyDTxRwOBuUt6m1FnW&t=0s) 494 | - [Blog (MindOrks)](https://blog.mindorks.com/android-developer-should-know-these-data-structures-for-next-interview) 495 | - [Data stracture (Coursera)](https://www.coursera.org/learn/data-structures) 496 | - [Data Structures and Performance (Course)](https://www.coursera.org/learn/data-structures-optimizing-performance) 497 | - [Data Structures in java (Article)](https://www.linkedin.com/pulse/data-structures-java-omar-ismail/) 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | --------------------------------------------------------------------------------