{"id":18439628,"url":"https://github.com/binaryshrey/dsa","last_synced_at":"2025-06-12T14:32:17.699Z","repository":{"id":63906179,"uuid":"197945884","full_name":"binaryshrey/DSA","owner":"binaryshrey","description":null,"archived":false,"fork":false,"pushed_at":"2022-12-17T12:44:56.000Z","size":251,"stargazers_count":4,"open_issues_count":0,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-07T21:41:30.197Z","etag":null,"topics":["java"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binaryshrey.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-07-20T15:06:43.000Z","updated_at":"2024-01-12T18:09:48.000Z","dependencies_parsed_at":"2023-01-29T17:15:40.342Z","dependency_job_id":null,"html_url":"https://github.com/binaryshrey/DSA","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/binaryshrey/DSA","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryshrey%2FDSA","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryshrey%2FDSA/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryshrey%2FDSA/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryshrey%2FDSA/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binaryshrey","download_url":"https://codeload.github.com/binaryshrey/DSA/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryshrey%2FDSA/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259482489,"owners_count":22864763,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java"],"created_at":"2024-11-06T06:25:50.712Z","updated_at":"2025-06-12T14:32:17.674Z","avatar_url":"https://github.com/binaryshrey.png","language":"Java","readme":"# DSA   \nA beginner's guide to getting started with Data Structures and Algorithms with JAVA.\n\n### Table of contents\n* [Installation](#1-installation)\n* [Hello World](#2-hello-world)\n* [Procedure Oriented Programming](#3-procedure-oriented-programming)\n* [Object Oriented Programming](#4-object-oriented-programming)\n* [Features of JAVA](#5-features-of-java)\n* [Byte Code](#6-byte-code)\n* [JDK](#7-jdk)\n* [JRE](#8-jre)\n* [JVM](#9-jvm)\n* [Garbage Collector](#10-garbage-collector)\n* [Data Types](#11-data-types)\n* [Variables](#12-variables)\n* [Packages](#13-packages)\n* [Formatted Output](#14-formatted-output)\n* [String Manipulation](#15-string-manipulation)\n* [Data Structures](#16-data-structures)\n* [Arrays](#17-arrays)\n* [LinkedList](#18-linkedlist)\n* [Stacks](#19-stacks)\n* [Queue](#20-queue)\n* [Binary Tree](#21-binary-tree)\n* [Binary Search Tree](#22-binary-search-tree)\n* [Heap](#23-heap)\n* [Hashing](#24-hashing)\n* [Graphs](#25-graphs)\n* [Matrix](#26-matrix)\n* [Advanced DS](#27-advanced-ds)\n* [Collections in Java](#28-collections-in-java)\n* [Algorithm Analysis](#29-algorithm-analysis)\n\n\n\u003cbr\u003e\n\n### 1. Installation\n```bash\n$ sudo apt update\n$ sudo apt install openjdk-8-jdk\n$ java -version\n```\n\n### 2. Hello World\n```\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass HelloWorld\n{\n\tpublic static void main (String[] args) throws java.lang.Exception\n\t{\n\t    System.out.println(\"Hello World\");\n\t}\n}\n```\n\n### 3. Procedure Oriented Programming\nProcedure Oriented Programming is a programming paradigm (top-down approach), where a program is written as a sequence of procedures or functions therby divinding a large program into smaller programs with specific functionality.\nIn POP, the major emphasis is on procedure (function) and not on the data and most functions share data defined at global level.\nPOP languages are high-level languages such as BASIC, C, COBOL are machine-independent and we can develop program logic without having a knowledge about computer's architecture.\n\n\n#### Characteristics of POP:\n* Emphasis is on functions\n* Functions share global data\n* Uses Top-Down approach\n\n### 4. Object Oriented Programming\nAn OOP is a design philosophy or programming paradigm, that models software design around data or objects rather than functions and logic. \nAn object is referred to as a data field that has unique attributes and behavior and it also provides reusablity feature to develop productive logic, which means more emphasis is given on data.\n\n#### Characteristics of OOP:\n* More emphasis on data rather than functions\n* Divides the program into no of objects\n\n#### Basic elements of OOP:\n\n* Class : It is a group of similar types of Objects which possess same attributes and behaviour. (Object factory / User-Desined datatype)\n* Object :It is a unique entity that contains data and functions (characteristics and behaviour) toghether in an OOP.\n* Data Abstraction : Act of representing essential features without including the background details\n* Encapsulation : The wrapping of data and functions, toghether in a single unit.\n* Data Hiding : The data which cannot be accessed directly outside class premise.\n* Dynamic Binding : The process of linking function call to function signature\n* Inheritance : Property by which object of one class acquire some common properties of another class\n* Polymorphism : The process of using a function for more than one purpose.\n\n\n### 5. Features of JAVA\n* OOP language\n* Both compiled and Intepreted\n* Platform independent\n* Multi-threaded\n* Case-sensitive\n* Robust and Secure\n\n\n### 6. Byte-Code\nByte Code is an intermediate code in form of .class file which is generated as soon as a Java program is compiled and is then acted upon by JVM making it platform independent.\nJAVA is a HLL. The program written in java is compiled to an intermediate code called Byte Code. This code is independent\nof the machine on which the program is to run. When the code is to be run on any machine, an Intepretor known as JVM \nconverts the Byte Code to MLL.\n\nThe conversion of HLL to MLL can be done in two ways\n* Interpretor : Conversion in performed line by line, execution stops when an error is encountered\n* Compiler : Conversion is performed all at once, all errors are listed toghether\n\n\n### 7. JDK\nThe Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and other tools needed in Java development.\n\n### 8. JRE\nJRE stands for “Java Runtime Environment” and may also be written as “Java RTE.” The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.\n\n### 9. JVM\nJVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).\n\nWhen we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM.\n\n1) Class Loader Subsystem\n\t* Loading : The Class loader reads the .class file, generate the corresponding binary data and save it in method area.\n\t* Linking : Performs verification, preparation, and (optionally) resolution.\n\t* Initialization : In this phase, all static variables are assigned with their values defined in the code \n\n2) JVM Memory\n\t* Method area\n\t* Heap area\n\t* Stack area\n\t* PC registers\n\t* Native method stack\n\n3) Execution Engine\n\t* Interpreter\n\t* Just-In-Time Compiler(JIT)\n\t* Garbage Collector\n\t\n4) Java Native Interface (JNI)\n5) Native Method Libraries\n\n### 10. Garbage Collector\nGarbage Collector destroys un-referenced objects. Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.\nAn object is said to be eligible for GC(garbage collection) iff it is unreachable.\n\nJust before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object. finalize() method is present in Object class with following prototype.\n```\nprotected void finalize() throws Throwable\n```\nThe finalize() method called by Garbage Collector not JVM.\nThe finalize() method is never invoked more than once for any given object.\n\nAn object is said to be eligible for GC(garbage collection) iff it is unreachable. \n#### Ways: \n* Nullifying the reference variable\n* Re-assigning the reference variable\n```\nInteger i = new Integer(4);\ni = null;\n```\n\n### 11. Data Types\n* Primitive \n\n\n| Data type | Size  | Value Range \t    | Precision |\n|:---------:|:-----:|:----------------------|:---------:|\n|boolean    | 1bit  | 0 or 1   \t\t    |   \t|\t\n|byte       | 1byte | -128 to 127\t    |\t\t|\t\n|char       | 2byte | 0 to 65,535\t    |\t\t|\n|short      | 2byte | -32,768 to 32,767\t    |\t\t|\n|int        | 4byte | -2^31 to 2^31-1\t    |\t\t|\n|long       | 8byte | -2^63 to 2^63-1\t    |\t\t|\n|float      | 4byte | -3.4E+38 to 3.4E+38   | 6 digits\t|\n|double     | 8byte | -1.7E+308 to 1.7E+308 | 15 digits |\n\n* Derived\n  * Class\n  * Array\n  * Interface etc\n  \n  \n### 12. Variables\nA Variable is a named memory location that holds a value.\nThere are three types of variables in Java:\n* Local Variables : \n\t* A variable defined within a block or method or constructor is called local variable. \n\t* These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.\n\t* Initilisation of Local Variable is Mandatory.\n\t* The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.\n\n* Instance Variables: \n\t* Instance variables are non-static variables and are declared in a class outside any method, constructor or block.\n\t* As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.\n\t* Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.\n\t* Initilisation of Instance Variable is not Mandatory. Its default value is 0\n\t* Instance Variable can be accessed only by creating objects.\n\t\n* Static Variables: \n\t* Static variables are also known as Class variables. These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.\n\t* Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.\n\t* Static variables are created at the start of program execution and destroyed automatically when execution ends.\n\t* Initilisation of Static Variable is not Mandatory. Its default value is 0\n\t\n\t\n### 13. Packages\nA mechamism of encapsulating a group of classes, interfaces or sub-packages\n#### Types of Packages\n* Built-in\n\t* java.lang\n\t* java.io\n\t* java.util\n\t* java.applet\n\t* java.awt\n\t* java.net\n\t\n* User-Defined\n```\npackage myPackage;\npublic class Hello{\n\tpublic void getNames(String s)\n\t{        \n        \tSystem.out.println(s);        \n\t}\n}\n\n\nimport myPackage.Hello;\npublic class PrintName \n{\n   public static void main(String args[]) \n   {       \n       \n      String name = \"Welcome to JAVA\";\n      Hello obj = new Hello();\n      \n      obj.getNames(name);\n   }\n}\n```\n\n### 19. Formatted Output\n#### Formatting output using System.out.printf()\n```\nclass Format\n{ \n  public static void main(String args[]) \n  { \n    int x = 100; \n    System.out.printf(\"%d\\n\", x); \t\t//100\n  \n    // this will print it upto 2 decimal places \n    System.out.printf(\"%.2f\\n\", Math.PI); \t//3.14\n  \n    float n = 5.2f; \n  \n    // automatically appends zero to the rightmost part of decimal \n    System.out.printf(\"%.4f\\n\", n); \t\t//5.2000\n  } \n} \n```\n\n#### Formatting using DecimalFormat class\n```\nimport java.text.DecimalFormat; \n  \nclass Format\n{ \n  public static void main(String args[]) \n  { \n    double num = 123.4567; \n  \n    // prints only numeric part of a floating number \n    DecimalFormat ft = new DecimalFormat(\"####\"); \n    System.out.println(ft.format(num)); \t\t//123\n  \n    // this will print it upto 2 decimal places \n    ft = new DecimalFormat(\"#.##\"); \n    System.out.println(ft.format(num)); \t\t//123.45\n  \n    // automatically appends zero to the rightmost part of decimal \n    // instead of #,we use digit 0 \n    ft = new DecimalFormat(\"#.000000\"); \n    System.out.println(ft.format(num)); \t\t//123.456700\n  \n    // automatically appends zero to the leftmost of decimal number \n    // instead of #,we use digit 0 \n    ft = new DecimalFormat(\"00000.00\"); \n    System.out.println(ft.format(num)); \t\t//00123.45\n  \n    // formatting money in dollars \n    double income = 23456.789; \n    ft = new DecimalFormat(\"$###,###.##\"); \n    System.out.println(ft.format(income)); \t\t//$23,456.79\n  } \n} \n```\n\t\n\n### 15. String Manipulation\n\n#### Built-in Character methods\n\n* Character.isLetter()\n* Character.isDigit()\n* Character.isLetterorDigit()\n* Character.isWhiteSpace()\n* Character.isUpperCase()\n* Character.toUpperCase()\n* Character.isLowerCase()\n* Character.toLowerCase()\n* Character.getNumericValue()\n\n#### Built-in String methods\n\n* toLowerCase()\n* toUpperCase()\n* replace()\n* trim()\n* equals()\n* equalsIgnoreCase()\n* compareTo()\n* length()\n* charAt()\n* substring()\n* indexOf()\n* lastIndexOf()\n* concat()\n* endsWith()\n* startWith()\n\n#### Built-in StringBuilder methods\n```\nStringBuilder st1 = new StringBuilder(\"Hello\");\nStringBuilder st2 = new StringBuilder();\n```\n* append() : st1.append(\" World\")\n* insert() : st1.insert(1,\"JAVA\")\n* replace() : st1.replace(3,7,\"c++\")\n* delete() : st1.delete(3,7)\n* reverse() : st1.reverse()\n* setCharAt() : st1.setCharAt(4,'b')\n* capacity()\n* charAt()\n* indexOf()\n* lastIndexOf()\n* substring()\n* setLength()\n\n\n\n\n#### String to Primitive type\n```\nint n = Integer.parseInt(str);\n```\n\n### Primitive to String type\n```\nString str = Integer.toString(n);\n```\n\n### 17. Data Structures\nA data structure is a storage that is used to store and organize data. It is a way of arranging data so that it can be accessed and updated efficiently.\n\n\n### 16. Arrays\n\n#### An array is a collection of similar items stored at contiguous memory locations\n\n* Arrays allow random access of elements.\n* Arrays have better cache locality\n* In Java all arrays are dynamically allocated.\n* The direct superclass of an array type is Object. \n* Every array type implements the interfaces Cloneable and java.io.Serializable.\n\n#### Declaration\n* int[] intArray = new int[20];\n* int[][] intArray = new int[10][20]; \n* int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; \n\n#### Passing arrays to Methods\n```\nclass Test \n{   \n    public static void main(String args[])  \n    { \n        int arr[] = {3, 1, 2, 5, 4}; \n        sum(arr); \n    } \n    public static void sum(int[] arr)  \n    { \n        int sum = 0;     \n        for (int i = 0; i \u003c arr.length; i++) \n            sum+=arr[i]; \n        System.out.println(\"sum of array values : \" + sum); \n    } \n} \n```\n\n#### Returning Arrays from Methods\n\n```\nclass Test \n{     \n    public static void main(String args[])  \n    { \n        int arr[] = m1();     \n        for (int i = 0; i \u003c arr.length; i++) \n            System.out.print(arr[i]+\" \"); \n    } \n    public static int[] m1()  \n    { \n        return new int[]{1,2,3}; \n    } \n} \n```\n\n#### Cloning of arrays\nWhen you clone a single dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references.\n```\nclass Test \n{     \n    public static void main(String args[])  \n    { \n        int intArray[] = {1,2,3};     \n        int cloneArray[] = intArray.clone();\n        System.out.println(intArray == cloneArray); \t//false\n        for (int i = 0; i \u003c cloneArray.length; i++) { \n            System.out.print(cloneArray[i]+\" \"); \t//1 2 3\n        } \n    } \n} \n```\n\nA clone of a multidimensional array (like Object[][]) is a “shallow copy” however, which is to say that it creates only a single new array with each element array a reference to an original element array but subarrays are shared.\n```\nclass Test \n{     \n    public static void main(String args[])  \n    { \n        int intArray[][] = {{1,2,3},{4,5}}; \n        int cloneArray[][] = intArray.clone();\n\t\n        System.out.println(intArray == cloneArray);\t\t//false\n        System.out.println(intArray[0] == cloneArray[0]); \t//true\n        System.out.println(intArray[1] == cloneArray[1]); \t//true\n          \n    } \n} \n```\n\n### 17. LinkedList\n\n### 18. Stacks\n\n### 19. Queue\n\n### 20. Binary Tree\nA tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.\nA Binary Tree node contains following parts:\n* Data\n* Pointer to left child\n* Pointer to right child\n\n\nUnlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.\n\n```\nclass Node \n{ \n    int key; \n    Node left, right; \n  \n    public Node(int item) \n    { \n        key = item; \n        left = right = null; \n    } \n} \n```\n\n### 21. Binary Search Tree\n\n### 22. Heap\n\n### 23. Hashing\n\n### 24. Graphs\n* Non-linear data structure. \n* A graph G is a set of ordered pair of Vertices V and a set of ordered pair of Edges E , G = (V,E)\n\nFollowing two are the most commonly used representations of a graph.\n1. Adjacency Matrix\n2. Adjacency List\n\n### 25. Matrix\n\n### 26. Advanced DS\n\n### 27. Collections in Java\nCollections in Java is a framework that provides an architecture to store and manipulate the group of objects.\n\n\t\t\t\tIterable\n\t\t\t\t    ^\n\t\t\t\t    |\n\t\t\t\t    |\n\t\t\t\tCollection\n\t\t\t\t    |\n\t\t--------------------------------------------\n\t\t|\t\t    |\t\t\t    |\n\t\t|\t\t    |\t\t\t    |\t\n\t       List\t\t  Queue\t                   Set\n\t        |\t\t    |\t\t\t    |\t\n\t- ArrayList\t- Queue (Priority Queue)\t- SortedSet (TreeSet)\t\t\n\t- LinkedList\t- Deque (Array Dequeue)\t\t- Set (HashSet, LinkedHashSet)\n\t- Vector (Stack)\n\t\n\n* #### Methods\n```\n.add\n.addAll\n.remove\n.removeAll\n.size\n.contains\n.toArray\n.isEmpty\n```\n\n* #### Iterator interface\nIterator interface provides the facility of iterating the elements in a forward direction only.\n```\n.hasNext()\n.next()\n.remove()\n```\n\n```\nIterator\u003cString\u003e itr=coll.iterator();  \nwhile(itr.hasNext()){  \n\tSystem.out.println(itr.next());  \n}  \n```\n\n### I. List\n### A. ArrayList\n* dynamic arrays in Java\n* allows random access\n* no primitive types - only wrappers\n* non-synchronized\n* maintains insertion order\n```\nArrayList\u003cString\u003e list=new ArrayList\u003cString\u003e();//Creating arraylist  \n\nlist.add(\"Ravi\");\nlist.add(\"Vijay\");  \nlist.add(\"Ravi\");  \nlist.add(\"Ajay\");  \n\n//Traversing list through Iterator  \nIterator itr=list.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n\nfor (int i = 0; i \u003c list.size(); i++)\n    System.out.print(list.get(i) + \" \");\n}\n```\n\n### B. LinkedList\n* impl of LinkedList DS\n```\nLinkedList\u003cString\u003e al=new LinkedList\u003cString\u003e();  \n\nal.add(\"Ravi\");  \nal.add(\"Vijay\");  \nal.add(\"Ravi\");  \nal.add(\"Ajay\");  \n\nIterator\u003cString\u003e itr=al.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n\n### C. Vector\n* similar to ArrayList\n* synchronized\n```\nVector\u003cString\u003e v=new Vector\u003cString\u003e();  \n\nv.add(\"Ayush\");  \nv.add(\"Amit\");  \nv.add(\"Ashish\");  \nv.add(\"Garima\");  \n\nIterator\u003cString\u003e itr=v.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n### D. Stack\n* impl LIFO DS\n* push, peek, pop\n\n```\nStack\u003cString\u003e stack = new Stack\u003cString\u003e();  \n\nstack.push(\"Ayush\");  \nstack.push(\"Garvit\");  \nstack.push(\"Amit\");  \nstack.push(\"Ashish\");  \nstack.push(\"Garima\");  \n\nstack.pop();  \n\nIterator\u003cString\u003e itr=stack.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n\n### II. Queue\n* impl FIFO\n\n#### A.PriorityQueue\n* doesn't allow null values to be stored in the queue.\n```\n\t// Creating empty priority queue\n\tPriorityQueue\u003cInteger\u003e pQueue = new PriorityQueue\u003cInteger\u003e();\n  \n        // Adding items to the pQueue using add()\n        pQueue.add(10);\n        pQueue.add(20);\n        pQueue.add(15);\n  \n        // Printing the top element of PriorityQueue\n        System.out.println(pQueue.peek());\n  \n        // Printing the top element and removing it\n        System.out.println(pQueue.poll());\n  \n        // Printing the top element again\n        System.out.println(pQueue.peek());\n```\n\n### III. Deque\n* add and remove the elements from both ends of the queue\n\n#### A.ArrayDeque\n```\n\t// Initializing an deque\n        ArrayDeque\u003cInteger\u003e de_que = new ArrayDeque\u003cInteger\u003e(10);\n  \n        // add() method to insert\n        de_que.add(10);\n        de_que.add(20);\n        de_que.add(30);\n        de_que.add(40);\n        de_que.add(50);\n  \n        System.out.println(de_que);\n  \n        // clear() method\n        de_que.clear();\n  \n        // addFirst() method to insert the\n        // elements at the head\n        de_que.addFirst(564);\n        de_que.addFirst(291);\n  \n        // addLast() method to insert the\n        // elements at the tail\n        de_que.addLast(24);\n        de_que.addLast(14);\n  \n        System.out.println(de_que);\n```\n\n\n\n### IV. Set Interface\n* doesn't allow us to store the duplicate items. \n* can store at most one null value in Set\n\n#### A. HashSet\n* contains unique items.\n* does not maintains the insertion order\n```\nHashSet\u003cString\u003e set=new HashSet\u003cString\u003e();  \n\nset.add(\"Ravi\");  \nset.add(\"Vijay\");  \nset.add(\"Ravi\");  \nset.add(\"Ajay\");  \n\n//Traversing elements  \nIterator\u003cString\u003e itr=set.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n#### B. LinkedHashSet\n- contains unique elements\n- maintains the insertion order\n- permits null elements.\n```\nLinkedHashSet\u003cString\u003e set=new LinkedHashSet\u003cString\u003e(); \n \nset.add(\"Ravi\");  \nset.add(\"Vijay\");  \nset.add(\"Ravi\");  \nset.add(\"Ajay\");  \n\nIterator\u003cString\u003e itr=set.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n#### C. TreeSet\n- contains unique elements\n- sorted in ascending order\n```\n//Creating and adding elements  \nTreeSet\u003cString\u003e set=new TreeSet\u003cString\u003e();  \n\nset.add(\"Ravi\");  \nset.add(\"Vijay\");  \nset.add(\"Ravi\");  \nset.add(\"Ajay\"); \n \n//traversing elements  \nIterator\u003cString\u003e itr=set.iterator();  \nwhile(itr.hasNext()){  \nSystem.out.println(itr.next());  \n}\n```\n\n\n### 28. Algorithm Analysis\nAn algorithm is a finite sequence of logically related instructions to solve a computational problem.\n#### Types of Algorithm\n* Iterative (Top-down)\n```\nFact(n)\n{\n\tfor i = 1 to n\n\tfact = fact * i;\n\treturn fact;\n}\n```\n\n* Recursive (Bottom-up)\n```\nFact(n)\n{\n\tif n = 1\n\t\treturn 1;\n\telse\n\t\treturn n * fact(n-1);\n}\n\nAsymptotic Analysis : mesauring order of growth of an algorithm in terms of input size\n\nC \u003c loglog(n) \u003c log(n) \u003c n^1/3 \u003c n^1/2 \u003c n \u003c n^2 \u003c n^3 \u003c 2^n \u003c n^n\n\nBest Case − Minimum time required for program execution.\nAverage Case − Average time required for program execution.\nWorst Case − Maximum time required for program execution.\n\n```\n#### Asymptotic Analysis\n* Big-oh notation\n```\nThe function f(n) = O(g(n)) if and only if there exist positive constants c, n0 such that\nf(n) ≤ cg(n), ∀n ≥ n0 .\n```\nBig-oh can be used to denote all upper bounds on the time complexity of an algorithm. Big-oh also captures the worst case analysis of an algorithm.\n\n\n* Omega notation\n```\nThe function f (n) = Ω(g(n)) if and only if there exist positive constants c, n0 such that f(n) ≥\nc.g(n), ∀n ≥ n0.\n```\nOmega can be used to denote all lower bounds of an algorithm. Omega notation also denotes the best case analysis of an algorithm.\n\n* Theta notation\n```\nThe function f (n) = Θ(g(n)) if and only if there exist positive constants c1 , c2 , n0 such that\nc1 g(n) ≤ f (n) ≤ c2 g(n), ∀n ≥ n0 .\n```\nTheta can be used to denote tight bounds of an algorithm.\n\n\n#### Alternative Big-oh notations:\n* O(1)\t\t: O(yeah)\n* O(logn)\t: O(nice)\n* O(n logn)\t: O(k-ish)\n* O(n)\t\t: O(ok)\n* O(n^2)\t: O(my)\n* O(2^n)\t: O(no)\n* O(n^n) \t: O(damn)\n* O(n!)\t\t: O(mg!)\n\n\n#### Calucalting Time-Complexity for Recurrence relations\n* Step Count Method\n* Substitution Method\n* Master Theorem\n* Recurrence Tree\n\n```\nMaster Theorem :\nLet a≥1 and b\u003e1 be constants, let f(n) be a non negative function,\nand let T(n) be defined on the non-negative integers by the recurrence\n\nT(n) = aT(n/b) + f(n)\n\nThen T(n) has the following asymptotic bounds:\n\nCase 1: If f(n) = O(n log b a−e ) for some constant e\u003e0 Then T(n) = θ(n log b a )\nCase 2: If f(n) = θ(n log b a ) then T(n) = θ(n log b a * log n)\nCase 3: If f(n) = Ω(n log b a+e ) for some constant e\u003e0, and if af (n/b) ≤ cf (n) for\nsome constant c\u003c1 and all sufficiently large n, then T(n) = θ(f(n)).\n```\n\n#### Analysis of Loops\n\n* O(1) : set of non-recursive and non-loop statements\n* O(n)\n```\nfor (int i = 1; i \u003c= n; i += c) {  \n\t// some O(1) expressions\n}\nfor (int i = n; i \u003e 0; i -= c) {\n\t// some O(1) expressions\n}\n ```\n *  O(n^c)\n ```\nfor (int i = 1; i \u003c=n; i += c) {\n\tfor (int j = 1; j \u003c=n; j += c) {\n\t\t// some O(1) expressions\t\n\t}\n}\nfor (int i = n; i \u003e 0; i -= c) {\n\tfor (int j = i+1; j \u003c=n; j += c) {\n\t\t// some O(1) expressions\n}\n```\n* O(Logn)\n```\nfor (int i = 1; i \u003c=n; i *= c) {\n\t// some O(1) expressions\n}\nfor (int i = n; i \u003e 0; i /= c) {\n\t// some O(1) expressions\n}\n```\n* O(LogLogn)\n```\nfor (int i = 2; i \u003c=n; i = pow(i, c)) { \n\t// some O(1) expressions\n}\nfor (int i = n; i \u003e 1; i = fun(i)) { \n\t// some O(1) expressions\n}\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinaryshrey%2Fdsa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinaryshrey%2Fdsa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinaryshrey%2Fdsa/lists"}