├── ArrayList methods ├── Arrays and Collections Classes ├── Collection interface class methods ├── ConcurrentHashMap ├── HashSet vs TreeSet vs LinkedHashSet ├── Lg(n) EVERYWHERE for TreeMap & TreeSet methods ├── README.md ├── Size of Int in Java in 64 bit machines ├── Space Complexity of Recursive Calls ├── String, StringBuilder and StringBuffer class methods ├── TimeComplexity Of DataStructures in Java ├── charAt() and deleteCharAt() performance └── methods of List, Set and Map Interfaces /ArrayList methods: -------------------------------------------------------------------------------- 1 | Question Time Complexity of class ArrayList methods time complexity 2 | *************************************************************************************************** 3 | Source: http://stackoverflow.com/questions/6540511/time-complexity-for-java-arraylist 4 | The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. 5 | The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. O(n) because, 6 | once the array is full(i.e. ArrayList is full), the array is copied to different location which has high memory, 7 | this copying of all the elements due to insufficient space causes (n) operation. Hence on an average, 8 | the time complexity is O(n), but if this case is avoided then the time complexity is O(1), similar to array addition 9 | operation. 10 | All of the other operations run in linear time [i.e. O(n) time](roughly speaking). 11 | 12 | ArrayList methods time complexity: 13 | Read/Search any element O(n). If you know the index then the complexity is O(1) 14 | Update : O(n) 15 | Delete at beginning: O(n) 16 | Delete in middle: O(n) 17 | Delete at end: O(n) 18 | Add at beginning: O(n) 19 | Add in middle: O(n) 20 | Add at end: O(n) 21 | 22 | Source: http://www.javaexperience.com/time-complexity-of-collection-classes/#ixzz3QWblGwzS 23 | -------------------------------------------------------------------------------- /Arrays and Collections Classes: -------------------------------------------------------------------------------- 1 | Question: 2 | Time Complexity of Arrays.sort() and Collections.sort() "STATIC" methods 3 | NOTE: Arrays and Collections (BOTH with s) are classes in Java 4 | 5 | Arrays is class in util package, 6 | Collections is class of util package, 7 | Collection is interface of util package 8 | 9 | VERY VERY IMP NOTE: PLURAL (i.e. Arrays and Collections) are CLASSES 10 | whereas SINGULAR form (e.g. Collection) is INTERFACE 11 | 12 | 13 | IMP NOTE: There is no such thing as "Array" in Java. "Arrays" exist BUT "Array" does NOT exist. 14 | Arrays - Class (http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html) 15 | Collection - INTERFACE (http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html) 16 | Collections - Class (http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html) 17 | 18 | Source: http://stackoverflow.com/questions/4254122/what-is-the-time-complexity-of-this-sort-method?rq=1 19 | Solution: The time complexity of this predefined method of Arrays class and Collections class is nlgn 20 | -------------------------------------------------------------------------------- /Collection interface class methods: -------------------------------------------------------------------------------- 1 | Queston : 2 | What is the time complexity of methods of classes which implements Collection interface 3 | 4 | VERY IMP Sources: 5 | http://www.javaexperience.com/time-complexity-of-collection-classes/ 6 | http://simplenotions.wordpress.com/2009/05/13/java-standard-data-structures-big-o-notation/ 7 | http://infotechgems.blogspot.com/2011/11/java-collections-performance-time.html 8 | http://www.introprogramming.info/english-intro-csharp-book/read-online/chapter-19-data-structures-and-algorithm-complexity/ 9 | 10 | Solution: 11 | 12 | Java ArrayList time complexity : 13 | Read/Search any element O(n). If you know the index then the complexity is O(1) 14 | Update : O(n) 15 | Delete at beginning: O(n) 16 | Delete in middle: O(n) 17 | Delete at end: O(n) 18 | Add at beginning: O(n) 19 | Add in middle: O(n) 20 | Add at end: O(n) 21 | 22 | Linked List time complexity : It has elements linked in one direction so as to provide ordered iteration 23 | of elements. 24 | Read/Search any element O(n) 25 | Update : O(n) 26 | Delete at beginning: O(1) 27 | Delete in middle: O(n) 28 | Delete at end: O(n) 29 | Add at beginning: O(1) 30 | Add in middle: O(n) 31 | Add at end: O(n) 32 | 33 | HashMap time complexity : The elements are placed randomly as per the hashcode. Here the assumption is 34 | that a good implementation of hashcode has been provided. 35 | Read/Search any element O(1) 36 | Update : O(1) 37 | Delete : O(1) 38 | Add : O(1) 39 | 40 | LinkedHashMap time complexity : The elements are placed randomly as with HashMap but are linked together 41 | to provide ordered iteration of elements. 42 | Read/Search any element O(1) 43 | Update : O(1) 44 | Delete : O(1) 45 | Add at beginning: O(1) 46 | Add in middle: O(n) 47 | Add at end: O(n) 48 | 49 | HashSet time complexity : The elements are distributed randomly in memory using their hashcode. 50 | Here also the assumption is that good hashcode which generated unique hashcode for different 51 | objects has been provided. 52 | Read/Search any element O(1) 53 | Update : O(1) 54 | Delete : O(1) 55 | Add : O(1) 56 | 57 | LinkedHashSet time complexity : It is same as HashSet with the addition of links between the elements of the Set. 58 | Read/Search any element O(1) 59 | Update : O(1) 60 | Delete : O(1) 61 | Add at beginning: O(1) 62 | Add in middle: O(n) 63 | Add at end: O(n) 64 | 65 | TreeMap time complexity : Provides natural sorting of elements. Uses equals, compare and compareTo 66 | methods to determine the sorting order. 67 | Read/Search any element O(log n) 68 | Update : O(log n) 69 | Delete : O(log n) 70 | Add : O(log n) 71 | 72 | TreeSet time complexity : Internally used an instances of TreeMap with the elements as key and a dummy 73 | value for all entries in the TreeMap. 74 | Read/Search any element O(log n) 75 | Update : O(log n) 76 | Delete : O(log n) 77 | Add : O(log n) 78 | 79 | -------------------------------------------------------------------------------- /ConcurrentHashMap: -------------------------------------------------------------------------------- 1 | Question: When to use ConcurrentHashMap 2 | Q & Ans Source: http://stackoverflow.com/questions/14228974/when-to-use-concurrenthashmap 3 | 4 | Question: What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)? 5 | Q & Ans Source: http://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap?rq=1 6 | -------------------------------------------------------------------------------- /HashSet vs TreeSet vs LinkedHashSet: -------------------------------------------------------------------------------- 1 | Source: http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/ 2 | -------------------------------------------------------------------------------- /Lg(n) EVERYWHERE for TreeMap & TreeSet methods: -------------------------------------------------------------------------------- 1 | Source -> http://www.javaexperience.com/time-complexity-of-collection-classes/ 2 | 3 | TreeMap time complexity : Provides natural sorting of elements. Uses equals, compare and compareTo methods 4 | to determine the sorting order. 5 | Read/Search any element O(log n) 6 | Update : O(log n) 7 | Delete : O(log n) 8 | Add : O(log n) 9 | 10 | TreeSet time complexity : Internally used an instances of TreeMap with the elements as key and a dummy value 11 | for all entries in the TreeMap. 12 | Read/Search any element O(log n) 13 | Update : O(log n) 14 | Delete : O(log n) 15 | Add : O(log n) 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TimeComplexityOfPredefinedMethodsInJava 2 | ======================================= 3 | -------------------------------------------------------------------------------- /Size of Int in Java in 64 bit machines: -------------------------------------------------------------------------------- 1 | 2 | Question 1: On a 64-bit machine is the size of an int in Java 32 bits or 64 bits? 3 | Question & Answer Source: http://stackoverflow.com/questions/400477/on-a-64-bit-machine-is-the-size-of-an-int-in-java-32-bits-or-64-bits 4 | Answer: 32 bits. It's one of the Java language features that the size of the integer does not vary with 5 | the underlying computer. 6 | NOTE: The above is applicable for all other primitive datatypes as well. 7 | Hence, size of ANY PRIMITIVE datatype does not vary with the underlying computer in JAVA. 8 | 9 | Question 2: Size of different primitve datatypes in Java 10 | Answer Source: http://cs.fit.edu/~ryan/java/language/java-data.html 11 | 12 | Question 3: Why is the range of bytes -128 to 127 in Java? 13 | Explanation: That means that the question is asking, Why not -127 to +127 (because 1 bit is used as sign bit 14 | And conversion of 0111 1111 is 127 [please NOTE that 0111 1111 is 127 and NOT 128]) 15 | To check the above please click on this link, which convert binary to decimal, 16 | http://www.binaryhexconverter.com/binary-to-decimal-converter 17 | [NOTE: To answer the above queation, please check the answer mentioned in the below link] 18 | Question & Answer Source: http://stackoverflow.com/questions/3621067/why-is-the-range-of-bytes-128-to-127-in-java 19 | 20 | Question 4: How are negative numbers represented in Java? 21 | Ans: ALL NEGATIVES IN JAVA ARE "NOTREPRESENTED" USING SIGN BIT. 22 | BUT INSTEAD THEY ARE "REPRESENTED" USING 2's COMPLEMENT. 23 | [NOTE: Please check the answer mentioned in the below link] 24 | Question and Answer Source: http://stackoverflow.com/questions/2931630/how-are-negative-numbers-represented-in-32-bit-signed-integer 25 | -------------------------------------------------------------------------------- /Space Complexity of Recursive Calls: -------------------------------------------------------------------------------- 1 | Question: Space complexity of recursive algorithm 2 | Source: http://stackoverflow.com/questions/10821059/space-complexity-of-recursive-algorithm 3 | -------------------------------------------------------------------------------- /String, StringBuilder and StringBuffer class methods: -------------------------------------------------------------------------------- 1 | 1. reverse() method of StringBuilder and StringBuffer class in JAVA 2 | NOTE: This method is NOT present in String class 3 | NOTE: reverse() method is an instance method of StringBuilder class AND 4 | reverse() method is also an instance synchronized method of StringBuffer class in JAVA 5 | 6 | PLEASE NOTE THAT reverse() method is NOT PRESENT in String class of JAVA. The reason being String class 7 | in JAVA is immutable. However, for some reason substring() method is present in String class even though String 8 | is immutable in JAVA. Also StringBuilder and StringBuffer classes each have substring() method. 9 | 10 | Source: http://stackoverflow.com/questions/19814067/time-complexity-of-stringbuilder-reverse-method 11 | Solution: It is O(n). It is impossible to revert a String in less than O(n) 12 | 13 | 2. toCharArray() and toString() methods 14 | NOTE: toCharArray() method is ONLY present in String class & NOT present in StringBuilder and StringBuffer classes. 15 | toString() method is present in all three classes, String, StringBuilder and StringBuffer classes. 16 | Source: http://stackoverflow.com/questions/13079261/what-is-the-runtime-of-tochararray-and-tostring-in-java 17 | Solution: 18 | As far as String.toCharArray() goes, it's O(N), where N is the number of characters in the string, 19 | because each character must be copied into the output. 20 | toString() is O(N) time complexity. 21 | The toString() method is implemented using System.arrayCopy, which happens to be a native method. 22 | I would imagine that the native method probably uses memcpy under the hood which is O(N), so the runtime O 23 | is dependent on the actual jvm implementation. You might take a look at the open jdk source to check the 24 | source for this native method. 25 | 26 | 3. substring() method of String, StringBuilder and StringBuffer classes 27 | NOTE: substring() method is present in all three classes, String, StringBuilder and StringBuffer classes. 28 | Answer: The time compexity of substring() method in all three classes is O(n) 29 | Question: What is the time complexity of the following program ? 30 | 31 | public static void calculateTimeComplexity(String s){ 32 | for(int i=0;i=0;j--){ 34 | System.out.println(s.substring(j,i+1)); 35 | } 36 | } 37 | } 38 | 39 | Options: 1. O(n^2) 40 | 2. O(n^3) 41 | where n = length of the string 42 | 43 | 44 | Solution: 45 | 46 | Answer is option 2. O(n^3) 47 | 48 | Source: http://stackoverflow.com/questions/4679746/time-complexity-of-javas-substring 49 | http://stackoverflow.com/questions/16123446/java-7-string-substring-complexity 50 | http://stackoverflow.com/questions/25514062/what-is-the-time-complexity-of-java-stringbuilder-substring-method-if-it-is-l 51 | 52 | Explanation: 53 | It was O(1) in older versions of Java - it just created a new String with the same underlying char[], 54 | and a different offset and length. 55 | However, this has actually changed started with Java 7 update 6. 56 | The char[] sharing was eliminated, and the offset and length fields were removed. substring() now just copies all the 57 | characters into a new String. 58 | Ergo, substring is O(n) in Java 7 update 59 | 60 | 4. indexOf() method of String, StringBuilder and StringBuffer classes 61 | NOTE: indexOf() method is present in all three classes, String, StringBuilder and StringBuffer classes. 62 | Source: http://stackoverflow.com/questions/12752274/java-indexofstring-str-method-complexity 63 | The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string 64 | and pattern respectively. 65 | What you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing 66 | logical parts of the string which cannot match the pattern. 67 | 68 | 5. charAt() and deleteCharAt() of String, StringBuilder and StringBuffer classes 69 | NOTE: charAt() method is present in all three classes, String, StringBuilder and StringBuffer classes. 70 | deleteCharAt() method is present in StringBuilder and StringBuffer classes. It is not present in String class. 71 | Question: 72 | I've been wondering about the implementation of charAt function for String/StringBuilder/StringBuffer 73 | in java what is the coomplexity of that ? also what about the deleteCharAt() in StringBuffer/StringBuilder ? 74 | Source: http://stackoverflow.com/questions/6461402/java-charat-and-deletecharat-performance 75 | Solution: 76 | The charAt method is O(1). 77 | The deleteCharAt method on StringBuilder and StringBuffer is O(N) on average, assuming you are deleting a 78 | random character from an N character StringBuffer / StringBuilder. (It has to move, on average, 79 | half of the remaining characters to fill up the "hole" left by the deleted character. 80 | There is no amortization over multiple operations; see below.) However, if you delete the last character, 81 | the cost will be O(1). 82 | There is no deleteCharAt method for String. 83 | For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation. 84 | For StringBuffer and StringBuilder, deleteCharAt() is a linear-time (i.e. O(n)) operation, and NOT constant time operation. 85 | StringBuffer and StringBuilder have very similar performance characteristics. 86 | The primary difference is that the former is synchronized (so is thread-safe) while the latter is not. 87 | 88 | 89 | 6. equals() method 90 | Source: http://stackoverflow.com/questions/14552285/what-is-the-time-complexity-of-equals-in-java-for-2-strings 91 | NOTE: equals() is a method of Object class. So ALL CLASSES AND INTERFACES in Java have equals() method 92 | Hence no question arises that whether String, StringBuilder, StringBuffer OR all three classes has equals() method 93 | because ALL CLASSES AND INTERFACES in Java have equals() method 94 | Worst case is O(n), unless the two strings are the same object in which case it's O(1). 95 | (Although in this case n refers to the number of matching characters in the two strings starting 96 | from the first character, not the total length of the string). 97 | This is easily possible in O(n), and impossible in less than that, so that's what it should be. 98 | -------------------------------------------------------------------------------- /TimeComplexity Of DataStructures in Java: -------------------------------------------------------------------------------- 1 | Question: Time Comeplexity of different data structures in Java ? 2 | Source: http://stackoverflow.com/questions/7294634/what-are-the-time-complexities-of-various-data-structures 3 | 4 | Solution: 5 | Arrays 6 | Set, Check element at a particular index: O(1) 7 | Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used, 8 | As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements 9 | Similarly, Insert for arrays is basically Set as mentioned in the beginning 10 | 11 | ArrayList: 12 | Add: Amortized O(1) 13 | Remove: O(n) 14 | Contains: O(n) 15 | Size: O(1) 16 | 17 | Linked List: 18 | Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly. 19 | Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly. 20 | Searching: O(n) 21 | 22 | Doubly-Linked List: 23 | Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly. 24 | Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly. 25 | Searching: O(n) 26 | 27 | Stack: 28 | Push: O(1) 29 | Pop: O(1) 30 | Top: O(1) 31 | Search (Something like lookup, as a special operation): O(n) (I guess so) 32 | 33 | Queue/Deque/Circular Queue: 34 | Insert: O(1) 35 | Remove: O(1) 36 | Size: O(1) 37 | 38 | Binary Search Tree: 39 | Insert, delete and search: Average case: O(log n), Worst Case: O(n) 40 | 41 | Red-Black Tree: 42 | Insert, delete and search: Average case: O(log n), Worst Case: O(log n) 43 | 44 | Heap/PriorityQueue (min/max): 45 | findMin/findMax: O(1) 46 | insert: O(log n) 47 | deleteMin/Max: O(log n) 48 | lookup, delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST 49 | 50 | Java ArrayList time complexity : 51 | Read/Search any element O(n). If you know the index then the complexity is O(1) 52 | Update : O(n) 53 | Delete at beginning: O(n) 54 | Delete in middle: O(n) 55 | Delete at end: O(n) 56 | Add at beginning: O(n) 57 | Add in middle: O(n) 58 | Add at end: O(n) 59 | 60 | Linked List time complexity : It has elements linked in one direction so as to provide ordered iteration 61 | of elements. 62 | Read/Search any element O(n) 63 | Update : O(n) 64 | Delete at beginning: O(1) 65 | Delete in middle: O(n) 66 | Delete at end: O(n) 67 | Add at beginning: O(1) 68 | Add in middle: O(n) 69 | Add at end: O(n) 70 | 71 | HashMap time complexity : The elements are placed randomly as per the hashcode. Here the assumption is 72 | that a good implementation of hashcode has been provided. 73 | Read/Search any element O(1) 74 | Update : O(1) 75 | Delete : O(1) 76 | Add : O(1) 77 | 78 | LinkedHashMap time complexity : The elements are placed randomly as with HashMap but are linked together 79 | to provide ordered iteration of elements. 80 | Read/Search any element O(1) 81 | Update : O(1) 82 | Delete : O(1) 83 | Add at beginning: O(1) 84 | Add in middle: O(n) 85 | Add at end: O(n) 86 | 87 | HashSet time complexity : The elements are distributed randomly in memory using their hashcode. 88 | Here also the assumption is that good hashcode which generated unique hashcode for different 89 | objects has been provided. 90 | Read/Search any element O(1) 91 | Update : O(1) 92 | Delete : O(1) 93 | Add : O(1) 94 | 95 | LinkedHashSet time complexity : It is same as HashSet with the addition of links between the elements of the Set. 96 | Read/Search any element O(1) 97 | Update : O(1) 98 | Delete : O(1) 99 | Add at beginning: O(1) 100 | Add in middle: O(n) 101 | Add at end: O(n) 102 | 103 | TreeMap time complexity : Provides natural sorting of elements. Uses equals, compare and compareTo 104 | methods to determine the sorting order. 105 | Read/Search any element O(log n) 106 | Update : O(log n) 107 | Delete : O(log n) 108 | Add : O(log n) 109 | 110 | TreeSet time complexity : Internally used an instances of TreeMap with the elements as key and a dummy 111 | value for all entries in the TreeMap. 112 | Read/Search any element O(log n) 113 | Update : O(log n) 114 | Delete : O(log n) 115 | Add : O(log n) 116 | 117 | -------------------------------------------------------------------------------- /charAt() and deleteCharAt() performance: -------------------------------------------------------------------------------- 1 | Question 1: 2 | I've been wondering about the implementation of charAt function for String/StringBuilder/StringBuffer 3 | in java what is the coomplexity of that ? also what about the deleteCharAt() in StringBuffer/StringBuilder ? 4 | 5 | Source: http://stackoverflow.com/questions/6461402/java-charat-and-deletecharat-performance 6 | 7 | Solution: 8 | The charAt method is O(1). 9 | The deleteCharAt method on StringBuilder and StringBuffer is O(N) on average, assuming you are deleting a 10 | random character from an N character StringBuffer / StringBuilder. (It has to move, on average, 11 | half of the remaining characters to fill up the "hole" left by the deleted character. 12 | There is no amortization over multiple operations; see below.) However, if you delete the last character, 13 | the cost will be O(1). 14 | There is no deleteCharAt method for String. 15 | For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation. 16 | For StringBuffer and StringBuilder, deleteCharAt() is a linear-time operation. 17 | StringBuffer and StringBuilder have very similar performance characteristics. 18 | The primary difference is that the former is synchronized (so is thread-safe) while the latter is not. 19 | 20 | Question 2. 21 | How String.charAt(int i) is implemented in Java? 22 | 23 | Source: http://stackoverflow.com/questions/20893802/how-string-charatint-i-is-implemented-in-java 24 | 25 | Solution: public char charAt(int index) { 26 | if ((index < 0) || (index >= value.length)) { 27 | throw new StringIndexOutOfBoundsException(index); 28 | } 29 | return value[index]; 30 | } 31 | -------------------------------------------------------------------------------- /methods of List, Set and Map Interfaces: -------------------------------------------------------------------------------- 1 | Source: http://www.acnenomor.com/2331736p1/time-complexity-of-hashmap-methods 2 | remove: O(1) [method of List, Set, Map classes] 3 | size: O(1) [method of List, Set, Map classes] 4 | values: O(n) (on traversal through iterator) [method of Map class] 5 | contains: O(1) [method of HashSet] {uses hash function} 6 | contains: O(n) [method of ArrayList] {to understand this, please understand first how ArrayList works internally. 7 | ArrayList does not contain any hash method. Its actually an array as its name suggests} 8 | How does ArrayList work internally ? 9 | Ans: http://stackoverflow.com/questions/3467965/how-does-arraylist-work 10 | containsKey: O(1) [method of HashMap] 11 | {Source: http://stackoverflow.com/questions/8923251/what-is-the-time-complexity-of-hashmap-containskey-in-java} 12 | containsValue: O(n) [method of HashMap] {since hash function only exists for key and not value, 13 | hence it has to iterate through all elements of the HashMap to find the value. Hence O(n) operation 14 | Source: http://stackoverflow.com/questions/16757359/what-is-the-time-complexity-of-hashmap-containsvalue-in-java} 15 | 16 | VERY VERY HELPFUL TABLE OF TIME COMPLEXITY ANALYSIS: 17 | http://www.c-sharpcorner.com/UploadFile/0f68f2/comparative-analysis-of-list-hashset-and-sortedset/ 18 | 19 | I think that remove() will be the same complexity as get(), O(1), assuming we don't have a giant HashMap with equal 20 | hashCodes, etc etc... 21 | For size() i'd also assume O(1), since a HashSet, which also has no order, has a size() method with complexity O(1). 22 | The one i have no idea of is values() - I'm not sure whether this method will just somehow "copy" the HashMap, 23 | giving a time complexity of O(1), or if it will have to iterate over the HashMap, making the complexity equal 24 | to the amount of elements stored in the HashMap. 25 | --------------------------------------------------------------------------------