├── .DS_Store ├── JAVA ├── Collections │ ├── binarySearch.md │ ├── max.md │ ├── min.md │ ├── reverse.md │ ├── reverseOrder.md │ ├── rotate.md │ ├── shuffle.md │ ├── sort.md │ └── swap.md ├── Iterators.md ├── Pair │ ├── hashing.md │ ├── pair.md │ ├── sorting.md │ └── utilities.md ├── README.md ├── Strings.md ├── containers │ ├── lists.md │ ├── maps.md │ ├── queues.md │ ├── sets.md │ └── stack.md ├── p1.JPG ├── p2.JPG ├── p3.JPG └── p4.JPG ├── LICENSE ├── README.md ├── _config.yml ├── cpp ├── .DS_Store ├── Iterators.md ├── README.md ├── containers │ ├── Pairs&Tuples.markdown │ ├── Vectors.markdown │ ├── bitsets.md │ ├── maps.md │ ├── queue.md │ ├── sets.md │ └── stacks.md ├── functions │ ├── MaxMin.md │ ├── binary_search.md │ ├── is_sorted.md │ ├── lower_bound.md │ ├── max_element.md │ ├── min_element.md │ ├── next_permutation.md │ ├── reverse.md │ ├── set_difference.md │ ├── set_intersection.md │ ├── set_union.md │ ├── sort.md │ └── upper_bound.md ├── introduction.md ├── problems │ ├── chefcode.cpp │ ├── ipctrain.cpp │ ├── kjcp01.cpp │ ├── kjcp02.cpp │ └── snakeeat.cpp └── templates.md ├── problems.md ├── python ├── Readme.md ├── containers │ ├── dictionary.md │ ├── heapq.md │ ├── lists.md │ └── sets.md └── methods │ ├── Counters.md │ ├── bisect.md │ ├── itertools.md │ └── miscellaneous.md ├── reference.md └── template.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/.DS_Store -------------------------------------------------------------------------------- /JAVA/Collections/binarySearch.md: -------------------------------------------------------------------------------- 1 |

binarySearch()

2 | 3 | 4 | ## Function 5 | 6 | > This function is used to search the specified object in a list using the binary search algorithm. 7 | 8 | > The method returns the index of the search key, if it is contained in the list and throws ClassCastException if the list contains elements that are not mutually comparable. 9 | 10 | ## Declaration 11 | 12 | ```java 13 | public static int binarySearch(List list,T key,Comparator c) 14 | ``` 15 | 16 | ## Parameters 17 | list − This is the list to be searched. 18 | 19 | key − This is the key to be searched for. 20 | 21 | c − This is the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used. The list must be sorted into ascending order according to the specified comparator. 22 | This parameter is optional. 23 | 24 | NOTE!- One important point to keep in mind is that the elements in the Collection must be already sorted, else the results will be something unexpected. 25 | 26 | ## Example (Without Comparator) 27 | 28 | ```java 29 | import java.util.*; 30 | 31 | public class BinarySearch 32 | { 33 | public static void main(String args[]) 34 | { 35 | 36 | ArrayList list = new ArrayList(); 37 | 38 | list.add(30); 39 | list.add(45); 40 | list.add(100); 41 | list.add(250); 42 | list.add(500); 43 | 44 | int index = Collections.binarySearch(list,45); 45 | 46 | System.out.println("Position of 45 is "+index); 47 | } 48 | } 49 | ``` 50 | 51 | ## Output 52 | 53 | ``` 54 | Position of 45 is 1 55 | ``` 56 | 57 | ## Example (With Comparator) 58 | 59 | ```java 60 | import java.util.*; 61 | 62 | public class BinarySearchwithComparator 63 | { 64 | public static void main(String args[]) 65 | { 66 | ArrayList list = new ArrayList(); 67 | list.add(500); 68 | list.add(250); 69 | list.add(100); 70 | list.add(45); 71 | list.add(30); 72 | int index = Collections.binarySearch(list, 30, 73 | Collections.reverseOrder()); 74 | 75 | System.out.println("Position of 30 is " + index); 76 | } 77 | } 78 | 79 | ``` 80 | 81 | ## Output 82 | 83 | ``` 84 | Position of 30 is 4 85 | ``` 86 | -------------------------------------------------------------------------------- /JAVA/Collections/max.md: -------------------------------------------------------------------------------- 1 |

max()

2 | 3 | 4 | ## Function 5 | 6 | >It returns the maximum element of the given collection, according to the order induced by the specified comparator. 7 | 8 | >All elements in the collection must be mutually comparable by the specified comparator 9 | (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection) 10 | 11 | 12 | NOTE!- This method requires a list type of data, we need to first convert the collection to list first using aslist() function. 13 | 14 | ## Declaration 15 | 16 | ```java 17 | public static T max(Collection coll,Comparator comp) 18 | ``` 19 | ## Parameters 20 | coll - The collection whose maximum element is to be determined. 21 | 22 | comp - The comparator with which to determine the maximum element. 23 | 24 | If the second argument is not provided, then comparison is made based on the natural order of elements 25 | ## Example 26 | 27 | ```java 28 | import java.util.*; 29 | public class MaxExample 30 | { 31 | public static void main(String args[]) 32 | { 33 | List list = new ArrayList(); 34 | list.add(100); 35 | list.add(-2); 36 | list.add(86); 37 | list.add(986); 38 | list.add(112); 39 | System.out.println("The maximum value in collection is "+Collections.max(list,null)); 40 | } 41 | } 42 | ``` 43 | 44 | ## Output 45 | 46 | ``` 47 | The maximum value in collection is 986 48 | ``` 49 | -------------------------------------------------------------------------------- /JAVA/Collections/min.md: -------------------------------------------------------------------------------- 1 |

min()

2 | 3 | 4 | ## Function 5 | 6 | >It returns the minimum element present in the given collection, according to the order induced by the specified comparator. 7 | 8 | >All elements in the collection must be mutually comparable by the specified comparator 9 | (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection) 10 | 11 | NOTE!- This method requires a list type of data, we need to first convert the collection to list first using aslist() function. 12 | 13 | ## Declaration 14 | 15 | ```java 16 | public static T min(Collection coll,Comparator comp) 17 | ``` 18 | 19 | ## Parameters 20 | coll - The collection whose minimum element is to be determined. 21 | 22 | comp - The comparator with which to determine the minimum element. 23 | 24 | If the second argument is not provided, then comparison is made based on the natural order of elements 25 | 26 | ## Example 27 | 28 | ```java 29 | import java.util.*; 30 | public class MinExample 31 | { 32 | public static void main(String args[]) 33 | { 34 | List list = new ArrayList(); 35 | list.add(100); 36 | list.add(-2); 37 | list.add(86); 38 | list.add(986); 39 | list.add(112); 40 | System.out.println("The minimum value in collection is "+Collections.min(list,null)); 41 | } 42 | } 43 | ``` 44 | 45 | ## Output 46 | 47 | ``` 48 | The minimum value in collection is -2 49 | ``` 50 | -------------------------------------------------------------------------------- /JAVA/Collections/reverse.md: -------------------------------------------------------------------------------- 1 |

reverse()

2 | 3 | 4 | ## Function 5 | 6 | >It reverses the order of the elements in the specified list. 7 | 8 | This method can be used to reverse a LinkedList, ArrayList and arrays. 9 | 10 | ## Declaration 11 | 12 | ```java 13 | public static void reverse(List list) 14 | ``` 15 | 16 | ## Parameters 17 | list - The list which is to be sorted. 18 | 19 | ## Example 20 | 21 | ```java 22 | import java.util.*; 23 | 24 | public class ReverseList 25 | { 26 | public static void main(String[] args) 27 | { 28 | ArrayList letters = new ArrayList(); 29 | letters.add("A"); 30 | letters.add("B"); 31 | letters.add("C"); 32 | letters.add("D"); 33 | letters.add("E"); 34 | 35 | System.out.println("Before reversing: "+letters); 36 | Collections.reverse(letters); 37 | System.out.println("After reversing: "+letters); 38 | } 39 | } 40 | ``` 41 | 42 | ## Output 43 | 44 | ``` 45 | Before reversing: [A, B, C, D, E] 46 | After reversing: [E, D, C, B, A] 47 | ``` 48 | -------------------------------------------------------------------------------- /JAVA/Collections/reverseOrder.md: -------------------------------------------------------------------------------- 1 |

reverseOrder()

2 | 3 | 4 | ## Function 5 | 6 | > This function returns a comparator that reverse the natural ordering imposed by Comparable. 7 | 8 | > This method along with sort() is used to sort a collection in descending order. 9 | 10 | ## Declaration 11 | 12 | ```java 13 | public static Comparator reverseOrder(Comparator cmp) 14 | ``` 15 | 16 | ## Parameters 17 | cmp − This is the comparator. 18 | This parameter is optional. 19 | 20 | ## Example (Using Comparator) 21 | 22 | ```java 23 | import java.util.*; 24 | class User 25 | { 26 | String name; 27 | public User(String name) 28 | { 29 | this.name = name; 30 | } 31 | public String getName() 32 | { 33 | return name; 34 | } 35 | 36 | } 37 | public class ReverseOrderwithComparator 38 | { 39 | public static void main(String args[]) 40 | { 41 | ArrayList list = new ArrayList (); 42 | list.add(new User("ABC")); 43 | list.add(new User("XYZ")); 44 | list.add(new User("PQR")); 45 | System.out.println("Sort using Comparator:"); 46 | Collections.sort(list, new UserComparator()); 47 | for(User u: list) 48 | { 49 | System.out.println(u.getName()); 50 | } 51 | System.out.println("Reverse Order using Comparator:"); 52 | Collections.sort(list, Collections.reverseOrder(new UserComparator())); 53 | for(User u: list) 54 | { 55 | System.out.println(u.getName()); 56 | } 57 | } 58 | } 59 | class UserComparator implements Comparator { 60 | @Override 61 | public int compare(User u1, User u2) { 62 | return (u1.getName()).compareTo(u2.getName()); 63 | } 64 | } 65 | ``` 66 | 67 | ## Output 68 | 69 | ``` 70 | Sort using Comparator: 71 | ABC 72 | PQR 73 | XYZ 74 | Reverse Order using Comparator: 75 | XYZ 76 | PQR 77 | ABC 78 | ``` 79 | -------------------------------------------------------------------------------- /JAVA/Collections/rotate.md: -------------------------------------------------------------------------------- 1 |

rotate()

2 | 3 | 4 | ## Function 5 | 6 | > It is used to rotate the elements present in the specified list by a given distance. 7 | 8 | > The distance can be zero, negative, or greater than size of the list. 9 | 10 | > Positive distance rotates the list to the right, negative distance rotates the list to the left while zero distance does not rotate the list. 11 | 12 | This method can be used to rotate lists and arrays. 13 | 14 | ## Declaration 15 | 16 | ```java 17 | public static void rotate(List list,int distance) 18 | ``` 19 | 20 | ## Parameters 21 | list - This is the list to be rotated. 22 | 23 | distance - This is the distance to rotate the list. 24 | 25 | ## Example 26 | 27 | ```java 28 | import java.util.*; 29 | 30 | public class RotateList 31 | { 32 | public static void main(String[] args) 33 | { 34 | List numbers = new ArrayList(); 35 | for (int i = 101; i <= 110; i++) 36 | numbers.add(i); 37 | System.out.println("Before rotating: " +numbers); 38 | Collections.rotate(numbers,3); 39 | System.out.println("After rotating: " +numbers); 40 | } 41 | } 42 | 43 | ``` 44 | 45 | ## Output 46 | 47 | ``` 48 | Before rotating: [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] 49 | After rotating: [108, 109, 110, 101, 102, 103, 104, 105, 106, 107] 50 | ``` 51 | -------------------------------------------------------------------------------- /JAVA/Collections/shuffle.md: -------------------------------------------------------------------------------- 1 |

shuffle()

2 | 3 | 4 | ## Function 5 | 6 | > It is used to randomly shuffle the specified list in place using a default or specified source of randomness. 7 | 8 | ## Declaration 9 | 10 | ```java 11 | public static void shuffle(List list,Random r) 12 | ``` 13 | 14 | ## Parameters 15 | list - The list to be shuffled. 16 | 17 | r - The custom source of randomness to use to shuffle the list. This can be used to make shuffling a deterministic process if needed. 18 | When using identical sources of randomness to shuffle two same lists, both lists will contain elements in the exact same order after shuffling. 19 | 20 | When second parameter is not present, the list is shuffled using default source of randomness. 21 | 22 | ## Example (Default source of randomness) 23 | 24 | ```java 25 | import java.util.*; 26 | 27 | public class ShuffleList 28 | { 29 | public static void main(String[] args) 30 | { 31 | List num = new ArrayList(); 32 | for (int i = 11; i <= 20; i++) 33 | num.add(i); 34 | System.out.println("Before shuffling: " +num); 35 | Collections.shuffle(num); 36 | System.out.println("After shuffling: " +num); 37 | } 38 | } 39 | 40 | ``` 41 | 42 | ## Output 43 | 44 | ``` 45 | Before shuffling: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] 46 | After shuffling: [12, 20, 11, 17, 13, 19, 15, 16, 18, 14] 47 | ``` 48 | 49 | ## Example (Custom source of randomness) 50 | 51 | ```java 52 | import java.util.*; 53 | 54 | public class ShuffleList 55 | { 56 | public static void main(String[] args) 57 | { 58 | List num = new ArrayList(); 59 | List num_copy = new ArrayList(); 60 | for (int i = 1; i <= 10; i++) 61 | { 62 | num.add(i); 63 | num_copy.add(i); 64 | } 65 | System.out.println("Before shuffling num: " +num); 66 | System.out.println("Before shuffling num_copy: " +num_copy); 67 | Collections.shuffle(num,new Random(3)); 68 | Collections.shuffle(num_copy,new Random(3)); 69 | System.out.println("After shuffling num: " +num); 70 | System.out.println("After shuffling num_copy: " +num_copy); 71 | } 72 | } 73 | 74 | ``` 75 | 76 | ## Output 77 | 78 | ``` 79 | Before shuffling num: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 80 | Before shuffling num_copy: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 81 | After shuffling num: [7, 6, 2, 4, 9, 8, 10, 1, 3, 5] 82 | After shuffling num_copy: [7, 6, 2, 4, 9, 8, 10, 1, 3, 5] 83 | ``` 84 | 85 | NOTE!- This function runs in linear time 86 | -------------------------------------------------------------------------------- /JAVA/Collections/sort.md: -------------------------------------------------------------------------------- 1 |

sort()

2 | 3 | 4 | ## Function 5 | 6 | > It is used to sort the elements present in the specified list of Collection in ascending order using the Merge Sort technique. 7 | 8 | > It can sort the elements of ArrayList, linked list, queue and many more. It can be used to sort an array after creating an ArrayList of given array items. 9 | 10 | ## Declaration 11 | 12 | ```java 13 | public static void sort(List list,Comparator c) 14 | ``` 15 | 16 | ## Parameters 17 | list - This is the list to be sorted. 18 | 19 | c - This is the comparator to determine the order of the list. 20 | 21 | 22 | ## Example (Using a Comparator) 23 | 24 | ```java 25 | import java.util.*; 26 | import java.lang.*; 27 | import java.io.*; 28 | 29 | class Product 30 | { 31 | int id, weight; 32 | String name; 33 | public Product(int id, String name, int weight) 34 | { 35 | this.id = id; 36 | this.weight = weight; 37 | this.name = name; 38 | } 39 | 40 | public String toString() 41 | { 42 | return this.id + " " + this.name + 43 | " " + this.weight; 44 | } 45 | } 46 | 47 | class SortbyWeight implements Comparator 48 | { 49 | // Used for sorting in ascending order of weight 50 | public int compare(Product p1, Product p2) 51 | { 52 | return p1.weight - p2.weight; 53 | } 54 | } 55 | 56 | public class SortUsingComparator 57 | { 58 | public static void main (String args[]) 59 | { 60 | ArrayList list = new ArrayList(); 61 | list.add(new Product(111, "Watermelon",3)); 62 | list.add(new Product(112, "Cake",2)); 63 | list.add(new Product(113, "Chocolate",1)); 64 | 65 | System.out.println("Unsorted"); 66 | for (Product p:list) 67 | System.out.println(p); 68 | 69 | Collections.sort(list, new SortbyWeight()); 70 | 71 | System.out.println("\nSorted by weight"); 72 | for (Product p:list) 73 | System.out.println(p); 74 | } 75 | } 76 | ``` 77 | 78 | ## Output 79 | 80 | ``` 81 | Unsorted 82 | 111 Watermelon 3 83 | 112 Cake 2 84 | 113 Chocolate 1 85 | 86 | Sorted by weight 87 | 113 Chocolate 1 88 | 112 Cake 2 89 | 111 Watermelon 3 90 | ``` 91 | 92 | -------------------------------------------------------------------------------- /JAVA/Collections/swap.md: -------------------------------------------------------------------------------- 1 |

swap()

2 | 3 | 4 | ## Function 5 | 6 | > It is used to swap the elements at the specified positions in the specified list. 7 | 8 | ## Declaration 9 | 10 | ```java 11 | public static void swap(List list,int index1,int index2) 12 | ``` 13 | 14 | ## Parameters 15 | list - The list in which to the swap elements. 16 | 17 | index1 - The index of first element to be swapped. 18 | 19 | index2 - The index of the other element to be swapped. 20 | 21 | If the elements with index numbers of index1 and index2 do not exist, the method throws ArrayIndexOutOfBoundsException. 22 | 23 | ## Example 24 | 25 | ```java 26 | import java.util.*; 27 | public class SwapExample 28 | { 29 | public static void main(String args[]) 30 | { 31 | ArrayList list = new ArrayList(); 32 | list.add(50); 33 | list.add(10); 34 | list.add(20); 35 | list.add(40); 36 | System.out.println("Before swapping: " +list); 37 | Collections.swap(list, 0,3); 38 | System.out.println("After swapping: " +list); 39 | } 40 | } 41 | ``` 42 | 43 | ## Output 44 | 45 | ``` 46 | Before swapping: [50, 10, 20, 40] 47 | After swapping: [40, 10, 20, 50] 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /JAVA/Iterators.md: -------------------------------------------------------------------------------- 1 | # Iterators in JAVA 2 | 3 | - ### Simple and Easy method (For-each Style) 4 | Write collection name right side of colon : in for-each loop and Collection variable in left side of colon. 5 | 6 | For example. 7 | 8 | ```java 9 | 10 | ArrayList al=new ArrayList<>(); //Collection declaration 11 | 12 | al.add(2); al.add(3); al.add(4); // populating data 13 | 14 | for(Integer x: al){ 15 | 16 | System.out.println(x); 17 | 18 | } 19 | 20 | ``` 21 | 22 | Output 23 | ``` 24 | 2 25 | 26 | 3 27 | 28 | 4 29 | ``` 30 | 31 | 32 | - ### Iterator 33 | In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a 34 | 35 | collection of objects. 36 | 37 | - It is used to traverse a collection object elements one by one. 38 | - It is available since Java 1.2 Collection Framework. 39 | - It is applicable for all Collection classes. So it is also known as Universal Java Cursor. 40 | - It supports both READ and REMOVE Operations. 41 | - Compare to Enumeration interface, Iterator method names are simple and easy to use. 42 | - In java ```Iterator``` is class and Object of this class is used to iterate over certain collections. 43 | 44 | Iterator is like pointer which points to location. 45 | 46 | In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples 47 | in the coming section. 48 | 49 | - boolean hasNext():Returns true if the iteration has more elements. 50 | - E next(): Returns the next element in the iteration. 51 | - default void remove(): Removes from the underlying collection the last element returned by this iterator. 52 | - default void forEachRemaining(Consumer action): Performs the given action for each remaining element until all elements have been processed or the action throws an exception. 53 | 54 | 55 | Even Every Collection has ```iterator()``` method which returns reference of Iterator object which we can use to iterate over Collection. 56 | 57 | Iterator object has .next() method which returns next element of collection and increments pointer. 58 | 59 | hasNext() method which returns boolean value which represents existence of next element in collection. 60 | 61 | So by using both the methods we can iterate over collection. 62 | 63 | For example. 64 | 65 | ```java 66 | 67 | ArrayList al=new ArrayList<>(); //Collection declaration 68 | 69 | al.add(2); al.add(3); al.add(4); // populating data 70 | 71 | Iterator it=al.iterator(); // '<>' these Brackets should contain type of objects you have added in Collection 72 | 73 | while(it.hasNext()){ 74 | Integer x=it.next(); 75 | System.out.println(x); 76 | } 77 | 78 | ``` 79 | 80 | Output 81 | ``` 82 | 2 83 | 84 | 3 85 | 86 | 4 87 | ``` 88 | 89 | - ### ListIterator 90 | **Note** : Collections are of different types for e.g Lists, maps,sets and many more. 91 | 92 | Normal Iterator object can only be incremented but ListIterator Object can be decremented as well. 93 | 94 | Hence it is most powerful iterator object. 95 | 96 | hasPrevious() and previous() have similar meaning as hasNext() and next() methods. 97 | 98 | ``public interface ListIterator extends Iterator `` 99 | 100 | An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain 101 | 102 | the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element 103 | 104 | that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of 105 | 106 | Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last 107 | 108 | element returned by a call to next() or previous(). 109 | 110 | This interface is a member of the Java Collections Framework. 111 | 112 | ```java 113 | 114 | 115 | ArrayList al=new ArrayList<>(); //Collection declaration 116 | 117 | al.add(2); al.add(3); al.add(4); // populating data 118 | 119 | ListIterator it=al.listIterator(); // '<>' these Brackets should contain type of objects you have added in Collection 120 | 121 | while(it.hasNext()){ 122 | Integer x=it.next(); 123 | if(it.hasPrevious()){ 124 | Integer y=it.previous(); 125 | System.out.println("Previous "+y); 126 | } 127 | it.next(); 128 | System.out.println("Next "+x); 129 | 130 | } 131 | 132 | ``` 133 | 134 | **Output** 135 | ``` 136 | Previous 2 137 | 138 | Next 2 139 | 140 | Previous 3 141 | 142 | Next 3 143 | 144 | Previous 4 145 | 146 | Next 4 147 | 148 | ``` 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /JAVA/Pair/hashing.md: -------------------------------------------------------------------------------- 1 |

Hashing

2 | 3 | ## Introduction 4 | 5 | > Hashing is the process of indexing and retrieving element (data) in a data structure to provide faster way of finding the element using the hash key. 6 | 7 | > Java provides HashMap and HashSet classes to implement Hashing by using the hashcode value of an object to determine where the object should be stored in the collection. This hashcode is used again to help locate the object in the collection. 8 | 9 | > In case you want to hash your custom class, you need to use the hashCode() and the equals() methods provided in java.lang.Object class and override them. 10 | 11 | ## hashcode() and equals() methods 12 | 13 | > equals(Object obj): This method indicates whether some other object passed as an argument is "equal to" the current instance. Two objects are equal if and only if they are stored in the same memory address. 14 | 15 | > hashcode(): This method returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance. This integer might change between several executions of the application and won't stay the same. 16 | 17 | 18 | NOTE!- If two objects are equal according to the equals(Object) method, then calling the hashcode() method on each of the two objects must produce the same integer result. 19 | 20 | ## Why overriding hashCode() and equals() method is needed? 21 | Note the examples given below. 22 | In the first example, both the methods are overridden so that Pair("Hello","World") and Pair("World","Hello") both have the same hashCode. 23 | ```java 24 | class Pair 25 | { 26 | String a,b; 27 | public Pair(String a, String b) 28 | { 29 | super(); 30 | this.a = a; 31 | this.b = b; 32 | } 33 | @Override 34 | public boolean equals(Object obj) 35 | { 36 | boolean t = true; 37 | if (this == obj) 38 | return true; 39 | if (obj == null) 40 | return false; 41 | if (this.hashCode() == obj.hashCode()) 42 | return true; 43 | return t; 44 | } 45 | 46 | @Override 47 | public int hashCode() 48 | { 49 | return a.hashCode() + b.hashCode(); 50 | } 51 | } 52 | 53 | public class Main 54 | { 55 | public static void main(String args[]) 56 | { 57 | Pair p1 = new Pair ("Hello", "World"); 58 | Pair p2 = new Pair ("World", "Hello"); 59 | System.out.println("p1 hashcode = " + p1.hashCode()); 60 | System.out.println("p2 hashcode = " + p2.hashCode()); 61 | System.out.println("Checking equality between p1 and p2 = " + p1.equals(p2)); 62 | } 63 | } 64 | ``` 65 | ## Output 66 | ``` 67 | p1 hashcode = 153375780 68 | p2 hashcode = 153375780 69 | Checking equality between p1 and p2 = true 70 | ``` 71 | 72 | > If equals() and hashCode() methods are not overridden, we will get different hash code for Pair("Hello", "World") and Pair("World", "Hello"). The example below demonstrates this. 73 | 74 | ```java 75 | class Pair 76 | { 77 | String a,b; 78 | public Pair(String a, String b) 79 | { 80 | super(); 81 | this.a = a; 82 | this.b = b; 83 | } 84 | //Not overriding equals() and hashCode() methods 85 | } 86 | 87 | public class Main 88 | { 89 | public static void main(String args[]) 90 | { 91 | Pair p1 = new Pair ("Hello", "World"); 92 | Pair p2 = new Pair ("World", "Hello"); 93 | System.out.println("p1 hashcode = " + p1.hashCode()); 94 | System.out.println("p2 hashcode = " + p2.hashCode()); 95 | System.out.println("Checking equality between p1 and p2 = " + p1.equals(p2)); 96 | } 97 | } 98 | ``` 99 | ## Output 100 | ``` 101 | p1 hashcode = 366712642 102 | p2 hashcode = 1829164700 103 | Checking equality between p1 and p2 = false 104 | ``` 105 | -------------------------------------------------------------------------------- /JAVA/Pair/pair.md: -------------------------------------------------------------------------------- 1 |

Pair

2 | 3 | ## Function 4 | > JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. 5 | 6 | > simply refers to a pair of values that are stored together. 7 | 8 | > Pairs provide a convenient way of handling simple key to value association and are particularly useful when we want to return two values from a method. 9 | 10 | NOTE!- You need to have Java 8 installed on your machine in order to run the below program. 11 | 12 | 13 | ## Syntax 14 | ```java 15 | //This returns an object of Pair class with key of Type T1 and Value of Type T2 16 | Pair p = new Pair <> (val1, val2); 17 | ``` 18 | 19 | ## Parameters 20 | val1 : Key of type T1 21 | 22 | val2 : Value for key val1, of type T2 23 | 24 | ## Methods of Pair Class 25 | 26 | Method | Description 27 | ------------ | ------------- 28 | Pair (K key, V value) | Creates a new pair 29 | boolean equals() | It is used to compare two pair objects. It compares on the basic of the values () which are stored in the pair objects. 30 | String toString() | It returns the String representation of the Pair. 31 | K getKey() | It returns key for the pair. 32 | V getValue() | It returns value for the pair. 33 | int hashCode() | Generates a hash code for the Pair. 34 | 35 | ## Example 36 | ```java 37 | import javafx.util.Pair; 38 | 39 | public class Main 40 | { 41 | public static void main(String args[]) 42 | { 43 | Pair p1 =new Pair<>("Mumbai",6); 44 | Pair p2 =new Pair<>("Chennai",7); 45 | Pair p3 =new Pair<>("Bombay",6); 46 | Pair p4 =new Pair<>("Mumbai",6); 47 | //equals method example 48 | System.out.println(p1.equals(p2)); 49 | System.out.println(p1.equals(p3)); 50 | System.out.println(p1.equals(p4)); 51 | //toString example 52 | System.out.println(p1.toString()); 53 | //getKey and getValue example 54 | System.out.println("Number of alphabets in "+p1.getKey()+" is "+p1.getValue()); 55 | } 56 | 57 | 58 | } 59 | ``` 60 | 61 | ## Output 62 | ``` 63 | false 64 | false 65 | true 66 | Mumbai=6 67 | Number of alphabets in Mumbai is 6 68 | ``` -------------------------------------------------------------------------------- /JAVA/Pair/sorting.md: -------------------------------------------------------------------------------- 1 |

Sorting

2 | 3 | ## Introduction 4 | > To sort a collection of Pair objects, we need to override the compareTo() method or create a new method to compare the keys or values. This is because it is not clear whether to sort based on key (first value) or based on value (second value) of Pair objects. 5 | 6 | > It is possible to sort a Hashmap based on key but to sort a HashMap by it's values, we need to convert the existing Map into a List and then sort this list by using Comparator interface and then again put this sorted list back to a Map. 7 | 8 | ## Example (Sorting by second value using Comparator) 9 | ```java 10 | import javafx.util.Pair; 11 | import java.util.*; 12 | 13 | public class Main 14 | { 15 | public static void main(String args[]) 16 | { 17 | List> fruits = new ArrayList>(); 18 | fruits.add(new Pair("Strawberry",7)); 19 | fruits.add(new Pair("Watermelon",2)); 20 | fruits.add(new Pair("Orange",5)); 21 | 22 | fruits.sort(new Comparator>() { 23 | @Override 24 | public int compare(Pair o1, Pair o2) { 25 | if (o1.getValue() < o2.getValue()) { 26 | return -1; 27 | } else if (o1.getValue().equals(o2.getValue())) { 28 | return 0; 29 | } else { 30 | return 1; 31 | } 32 | } 33 | }); 34 | System.out.println("Sorting by second value (integer) in ascending order:"); 35 | System.out.println(fruits); 36 | } 37 | 38 | 39 | } 40 | ``` 41 | ## Output 42 | ``` 43 | Sorting by second value (integer) in ascending order: 44 | [Watermelon=2, Orange=5, Strawberry=7] 45 | ``` 46 | 47 | 48 | ## Example (Sorting by first value in descending order) 49 | ```java 50 | import javafx.util.Pair; 51 | import java.util.*; 52 | 53 | public class Main 54 | { 55 | public static void main(String args[]) 56 | { 57 | List> fruits = new ArrayList>(); 58 | fruits.add(new Pair("Strawberry",7)); 59 | fruits.add(new Pair("Watermelon",2)); 60 | fruits.add(new Pair("Orange",5)); 61 | 62 | fruits.sort(new Comparator>() { 63 | @Override 64 | public int compare(Pair o1, Pair o2) { 65 | if ((o1.getKey()).compareTo(o2.getKey()) >0 ) { 66 | return -1; 67 | } else if (o1.getKey().equals(o2.getKey())) { 68 | return 0; 69 | } else { 70 | return 1; 71 | } 72 | } 73 | }); 74 | System.out.println("Sorting by first value (string) in descending order:"); 75 | System.out.println(fruits); 76 | } 77 | 78 | 79 | } 80 | ``` 81 | 82 | ## Output 83 | ``` 84 | Sorting by first value (string) in descending order: 85 | [Watermelon=2, Strawberry=7, Orange=5] 86 | ``` 87 | -------------------------------------------------------------------------------- /JAVA/Pair/utilities.md: -------------------------------------------------------------------------------- 1 |

Utilities

2 | 3 | ## Introduction 4 | 5 | > java.util contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). 6 | 7 | > Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). 8 | 9 | 10 | ## Methods of Collection interface 11 | 12 | Method | Description 13 | ------------ | ------------- 14 | public boolean add(Object element) | This method is used to insert an element in a collection. 15 | public boolean addAll(Collection c) | This method is used to insert all elements of Collection c in the invoking collection. 16 | public boolean remove(Object element) | This method is used to delete an element from a collection. 17 | public boolean removeAll(Collection c) | This method is used to delete all the elements of Collection c from the invoking collection. 18 | public boolean retainAll(Collection c) | This method is used to delete all the elements of invoking collection except the elements which are present in specified Collection c. 19 | public int size() | This method returns the total number of elements in the collection. 20 | public void clear() | This method removes all the elements from the collection. 21 | public boolean contains(Object element) | This method is used to search an element in invoking collection. 22 | public boolean containsAll(Collection c) | This method is used to check if all the elements of Collection c are present in invoking collection or not. 23 | public Iterator iterator() | This method returns an iterator. 24 | public boolean isEmpty() | This method checks if collection is empty. 25 | public boolean equals(Object element) | This method is used to compare objects of collections. 26 | 27 | NOTE!- The above methods work for Set and List Interfaces. 28 | 29 | 30 | ## Methods of Iterator interface 31 | 32 | Method | Description 33 | ------------ | ------------- 34 | public boolean hasNext() | It returns true if iterator has more elements. 35 | public Object next() | It returns the element and moves the cursor pointer to the next element. 36 | public void remove() | It removes the last elements returned by the iterator. It is rarely used. 37 | 38 | ## Example 39 | ```java 40 | //This example demonstrates the use of all methods listed above 41 | import java.util.*; 42 | 43 | public class Main 44 | { 45 | public static void main(String args[]) 46 | { 47 | ArrayList num= new ArrayList(); 48 | ArrayList even_num= new ArrayList(); 49 | ArrayList odd_num= new ArrayList(); 50 | 51 | //inserting elements using add() method 52 | for(int i=1;i<=10;i++) 53 | num.add(i); 54 | 55 | System.out.println("Original list of numbers is: "); 56 | //Print numbers using iterator 57 | Iterator it = num.iterator(); 58 | while(it.hasNext()) 59 | System.out.println(it.next()); 60 | 61 | for(int i=2;i<=10;i=i+2) 62 | even_num.add(i); 63 | 64 | System.out.println("List of even numbers is: "); 65 | Iterator even_it = even_num.iterator(); 66 | while(even_it.hasNext()) 67 | System.out.println(even_it.next()); 68 | 69 | 70 | //inserting all elements of num in odd_num 71 | odd_num.addAll(num); 72 | 73 | //removing elements of even_num from odd_num 74 | odd_num.removeAll(even_num); 75 | 76 | System.out.println("List of odd numbers is: "); 77 | Iterator odd_it = odd_num.iterator(); 78 | while(odd_it.hasNext()) 79 | System.out.println(odd_it.next()); 80 | 81 | 82 | num.clear(); 83 | int n = num.size(); 84 | int e = even_num.size(); 85 | System.out.println("Size of num list is "+n+" and that of even_num list is "+e); 86 | 87 | //check if even_num list contains 10 88 | boolean check = even_num.contains(10); 89 | System.out.println("even_num contains 10? "+check); 90 | 91 | //check if even_num contains all elements of odd_num 92 | check = even_num.containsAll(odd_num); 93 | System.out.println("even_num contains odd_num? "+check); 94 | boolean empty = num.isEmpty(); 95 | System.out.println("num is empty? "+empty); 96 | //even if any one element of odd_num is not present in even_num, the method will return false 97 | 98 | //check if temp is equl to odd_num 99 | ArrayList temp= new ArrayList(); 100 | temp.addAll(odd_num); 101 | check= temp.equals(odd_num); 102 | System.out.println("temp list equal to odd_num? "+check); 103 | 104 | 105 | } 106 | } 107 | ``` 108 | 109 | ## Output 110 | ``` 111 | Original list of numbers is: 112 | 1 113 | 2 114 | 3 115 | 4 116 | 5 117 | 6 118 | 7 119 | 8 120 | 9 121 | 10 122 | List of even numbers is: 123 | 2 124 | 4 125 | 6 126 | 8 127 | 10 128 | List of odd numbers is: 129 | 1 130 | 3 131 | 5 132 | 7 133 | 9 134 | Size of num list is 0 and that of even_num list is 5 135 | even_num contains 10? true 136 | even_num contains odd_num? false 137 | num is empty? true 138 | temp list equal to odd_num? true 139 | ``` 140 | 141 | 142 | ## Methods of Map Interface 143 | Method | Description 144 | ------------ | ------------- 145 | Object put(Object key, Object value) | It is used to insert an entry in this map. 146 | void putAll(Map map) | It is used to insert the specified map in this map. 147 | Object remove(Object key) | It is used to delete an entry for the specified key. 148 | Object get(Object key) | It is used to return the value for the specified key. 149 | boolean containsKey(Object key) | It is used to search the specified key from this map. 150 | Set keySet() | It is used to return the Set view containing all the keys. 151 | Set entrySet() | It is used to return the Set view containing all the keys and values. 152 | 153 | 154 | ## Methods of Map.Entry Interface 155 | 156 | Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value. 157 | 158 | Method | Description 159 | ------------ | ------------- 160 | Object getKey() | It is used to obtain key. 161 | Object getValue() | It is used to obtain value. 162 | 163 | 164 | Maps can also be traversed using Iterator. 165 | 166 | ## Example 167 | ```java 168 | //This example demonstrates use of all Map Interface methods 169 | import java.util.*; 170 | class Main 171 | { 172 | public static void main(String args[]) 173 | { 174 | Map map=new HashMap(); 175 | Map copy=new HashMap(); 176 | map.put(100,"ABC"); 177 | map.put(101,"XYZ"); 178 | map.put(102,"PQR"); 179 | 180 | //traversing map 181 | System.out.println("Traversing map:"); 182 | for(Map.Entry m:map.entrySet()) 183 | System.out.println(m.getKey()+" "+m.getValue()); 184 | 185 | 186 | System.out.println("Value of key 100 in map is " +map.get(100)); 187 | 188 | //inserting all elements of map into copy 189 | copy.putAll(map); 190 | System.out.println("Traversing copy: "); 191 | for(Map.Entry c:copy.entrySet()) 192 | System.out.println(c.getKey()+" "+c.getValue()); 193 | 194 | 195 | map.remove(102); 196 | System.out.println("Removed key 102 from map."); 197 | boolean check = map.containsKey(102); 198 | 199 | System.out.println("map contains key 102? "+check); 200 | 201 | } 202 | } 203 | ``` 204 | 205 | ## Output 206 | ``` 207 | Traversing map: 208 | 100 ABC 209 | 101 XYZ 210 | 102 PQR 211 | Value of key 100 in map is ABC 212 | Traversing copy: 213 | 100 ABC 214 | 101 XYZ 215 | 102 PQR 216 | Removed key 102 from map. 217 | map contains key 102? false 218 | ``` 219 | 220 | -------------------------------------------------------------------------------- /JAVA/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

JAVA Collections Framework

4 | 5 |
6 | 7 | ### Index 8 | 1. Containers 9 | 1. [Lists](./containers/lists.md) 10 | 1. ArrayList 11 | 2. Vector 12 | 3. LinkedList 13 | 2. [Queues](./containers/queues.md) 14 | 1. PriorityQueue 15 | 3. [Stack](./containers/stack.md) 16 | 4. [Maps](./containers/maps.md) 17 | 1. HashMap 18 | 2. TreeMap 19 | 3. LinkedHashMap 20 | 5. [Sets](./containers/sets.md) 21 | 1. HashSet 22 | 2. LinkedHashSet 23 | 3. TreeSet 24 | 6. Pairs 25 | 1. [Hashing](./Pair/hashing.md) 26 | 2. [Pair](./Pair/pair.md) 27 | 3. [Utilities](./Pair/utilities.md) 28 | 4. [sorting](./Pair/sorting.md) 29 | 7. [String/StringBuffers](./Strings.md) 30 | 2. Collections 31 | 1. [reverse](./Collections/reverse.md) 32 | 2. [Sort](./Collections/sort.md) 33 | 3. [reverseOrder](./Collections/reverseOrder.md) 34 | 4. [shuffle](./Collections/shuffle.md) 35 | 5. [rotate](./Collections/rotate.md) 36 | 6. [swap](./Collections/swap.md) 37 | 7. [binarySearch](./Collections/binarySearch.md) 38 | 8. [min](./Collections/min.md) 39 | 9. [max](./Collections/max.md) 40 | 3. [Iterators](./Iterators.md) 41 | 1. iterator 42 | 2. listIterator 43 | 3. for each style -------------------------------------------------------------------------------- /JAVA/Strings.md: -------------------------------------------------------------------------------- 1 | # JAVA String/StringBuffer 2 | 3 | ### Difference Between String and StringBuffer Class in Java : 4 | 5 | 6 | String and StringBuffer both are the classes which operate on strings. The object of String class is of fixed length. 7 | 8 | The object of the StringBuffer class is growable. The basic difference between String and StringBuffer is that the object of the “String” class is immutable. 9 | 10 | The object of the class “StringBuffer” mutable. 11 | 12 | 13 | ![p1](https://github.com/Kadam-Tushar/standard-library-in-x/blob/master/JAVA/p1.JPG) 14 | 15 | **What is meant by immutable:** 16 | 17 | we cannot append,remove new string to created object.StringBuffer objects provide more functionality to the strings as compared to the class String. 18 | 19 | Hence, it is preferable to work with StringBuffer instead of class String.so when we want to make fixed size string use string object and when we want perform operation like append remove we use stringBuffer class object. 20 | 21 | ``` 22 | String Object: 23 | 24 | Creating empty string object → String str = new String (“Hello”); 25 | 26 | Appending new string → str.concat(“World !”); 27 | 28 | Printing string object → System.out.println(str); 29 | 30 | Output → Hello 31 | 32 | StringBuffer Object: 33 | 34 | Creating empty string object → String str = new String (“Hello”); 35 | 36 | Appending new string → str.append(“ World !”); 37 | 38 | Printing string object → System.out.println(str); 39 | 40 | Output → Hello World ! 41 | 42 | ``` 43 | 44 | ### Important Note : 45 | - Concat operation on StringBuffer is O(1 ) while for String Class it is O(n). 46 | 47 | - Because String is immutable hence new object is created for every concat. 48 | 49 | ### Important methods of String class: 50 | 51 | ![p4](https://github.com/Kadam-Tushar/standard-library-in-x/blob/master/JAVA/p4.JPG) 52 | 53 | 54 | ### Important methods of StringBuffer class: 55 | 56 | ![p3](https://github.com/Kadam-Tushar/standard-library-in-x/blob/master/JAVA/p3.JPG) 57 | 58 | -------------------------------------------------------------------------------- /JAVA/containers/lists.md: -------------------------------------------------------------------------------- 1 |

Lists

2 | 3 |

Arraylists

4 | 5 | >Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface 6 | 7 | >ArrayList in Java can be seen as similar to vector in C++. 8 | 9 | > ArrayList only supports object entries, not the primitive data types(like int, float, char, etc). 10 | 11 | >Java ArrayList class maintains insertion order 12 | 13 | >Java ArrayList allows random access because array works at the index basis. 14 | 15 | >In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list. 16 | 17 | 18 | 19 | ### Operations 20 | 21 | 22 | |
Function
|
What it does?
|
Complexity
23 | | :------------- | :------------- | :------------- | 24 | | void clear() | It is used to remove all of the elements from this list.|O(1) 25 | | void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior 26 | | int indexOf(Object o) | It is 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 |O(n) 27 | | int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.|O(n) 28 | | Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n) 29 | | Object clone() | It is used to return a shallow copy of an ArrayList.|- 30 | | void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|- 31 | 32 | 33 | ### Implementation of ArrayList 34 | 35 | ```java 36 | //declaration 37 | //creating new generic arraylist 38 | ArrayList al=new ArrayList(); 39 | ``` 40 | ```java 41 | //simple example 42 | import java.util.*; 43 | class TestCollection1{ 44 | public static void main(String args[]){ 45 | ArrayList list=new ArrayList();//Creating arraylist 46 | list.add("Shivam"); 47 | list.add("Tushar"); 48 | list.add("Chirag"); 49 | list.add("Neel"); 50 | //Traversing list through Iterator 51 | Iterator itr=list.iterator(); 52 | while(itr.hasNext()){ 53 | System.out.println(itr.next()); 54 | } 55 | System.out.println(); 56 | 57 | 58 | //addall() 59 | 60 | ArrayList al2=new ArrayList(); 61 | list.add("Devansh"); 62 | al2.addAll(list); 63 | Iterator itr2 = al2.iterator(); 64 | 65 | while(itr2.hasNext()){ 66 | System.out.println(itr2.next()); 67 | } 68 | System.out.println(); 69 | 70 | //indexOf() 71 | 72 | int pos1 =list.indexOf("Shivam"); 73 | System.out.println(pos1); 74 | } 75 | 76 | } 77 | 78 | ``` 79 | Output: 80 | ``` 81 | Shivam 82 | Tushar 83 | Chirag 84 | Neel 85 | 86 | Shivam 87 | Tushar 88 | Chirag 89 | Neel 90 | Devansh 91 | 92 | 0 93 | 94 | ``` 95 | 96 |
97 | 98 |

Vector

99 | 100 | >Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an index. 101 | 102 | >They are very similar to ArrayList but Vector is synchronised and have some legacy method which collection framework does not contain. 103 | 104 | >It extends AbstractList and implements List interfaces. 105 | 106 | 107 | ### Operations 108 | 109 | |
Function
|
What it does?
|
Complexity
110 | | :------------- | :------------- | :------------- | 111 | |void clear() | It is used to remove all of the elements from this list.|O(1) 112 | |void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior 113 | |int indexOf(Object o) | It is 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 |O(n) 114 | |int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.|O(n) 115 | |Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n) 116 | |Object clone() | It is used to return a shallow copy of an ArrayList.|O(n) 117 | |void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|- 118 | |boolean contains(Object o) |This method returns true if this vector contains the specified element |O(n) 119 | |boolean remove(Object o) |This method removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.|O(n) 120 | |boolean equals(Object o)| This method compares the specified Object with this Vector for equality.|O(n) 121 | 122 | 123 | ### Implementation of Vectors 124 | 125 | ```java 126 | //declaration 127 | 128 | 129 | import java.util.*; 130 | class Vector_demo 131 | { 132 | public static void main(String[] arg) 133 | { 134 | 135 | // create default vector 136 | Vector v = new Vector(); 137 | 138 | v.add("Shivam"); 139 | v.add("Chirag"); 140 | v.add("Devansh"); 141 | v.add("Nishchith"); 142 | 143 | System.out.println("Vector is " + v); 144 | 145 | //addall() 146 | Vector arr = new Vector(); 147 | 148 | // copying all element of array list int0 vector 149 | arr.addAll(v); 150 | System.out.println("vector arr:" + arr); 151 | 152 | // check whether vector contains "Nishchith" 153 | if(v.contains("Nishchith")) 154 | System.out.println("Nishchith exists"); 155 | 156 | //equals 157 | 158 | Vector v1 = new Vector(); 159 | v1.add("Shivam"); 160 | v1.add("Chirag"); 161 | v1.add("Devansh"); 162 | v1.add("Nishchith"); 163 | System.out.println(v.equals(v1); 164 | } 165 | } 166 | ``` 167 | 168 | 169 | Output 170 | ``` 171 | Vector is [Shivam, Chirag, Devansh, Nishchith] 172 | vector arr:[Shivam, Chirag, Devansh, Nishchith] 173 | Nishchith exists 174 | true 175 | ``` 176 | 177 | 178 | 179 |

Difference between ArrayList and Vector

180 | 181 | |
ArrayList
|
Vector
182 | | :------------- | :------------- | 183 | |1)ArrayList is not synchronized.|1)Vector is synchronized. 184 | |2) ArrayList increments 50% of current array size if number of element exceeds from its capacity.|2)Vector increments 100% means doubles the array size if total number of element exceeds than its capacity 185 | |3) ArrayList uses Iterator interface to traverse the elements.|3)Vector uses Enumeration interface to traverse the elements. But it can use Iterator also. 186 | |4)Is is fast|4)It is comparatively slower. 187 | 188 |
189 | 190 |

LinkedList

191 | 192 | >Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure 193 | 194 | >Java LinkedList class can contain duplicate elements. 195 | 196 | >Java LinkedList class maintains insertion order. 197 | 198 | >Java LinkedList class can be used as list, stack or queue. 199 | 200 | ### Operations 201 | 202 | |
Function
|
What it does?
|
Complexity
203 | | :------------- | :------------- | :------------- | 204 | |void clear() | It is used to remove all of the elements from this list.|O(1) 205 | |void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior 206 | |int indexOf(Object o) | It is 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 |O(n) 207 | |int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.in|O(n) 208 | |Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n) 209 | |Object clone() | It is used to return a shallow copy of an ArrayList.|O(n) 210 | |void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|O(n) 211 | |void addFirst(Object o)|It is used to insert the given element at the beginning of a list.|O(1) 212 | |void addLast(Object o) |It is used to insert the given element at the ending of a list.|O(1) 213 | |int size() |It is used to return the number of elements in a list|O(1) 214 | |Object getFirst()|It is used to return the first element in a list.|O(1) 215 | |Object getLast()|It is used to return the last element in a list.|O(1) 216 | 217 | 218 | 219 | ### Implementation of LinkedList 220 | 221 |
222 | 223 | ```java 224 | // declaration 225 | //eg 226 | LinkedList al=new LinkedList(); 227 | 228 | ``` 229 | 230 | 231 | ```java 232 | import java.util.*; 233 | public class LinkedList_Demo{ 234 | public static void main(String args[]){ 235 | 236 | LinkedList al=new LinkedList(); 237 | al.add("Neel"); 238 | al.add("Devansh"); 239 | Iterator itr=al.iterator(); 240 | while(itr.hasNext()){ 241 | System.out.println(itr.next()); 242 | } 243 | System.out.println(); 244 | 245 | //addfirst and last 246 | 247 | al.addFirst("chirag"); 248 | al.addLast("hello"); 249 | Iterator itr2 = al.iterator(); 250 | while(itr2.hasNext()){ 251 | System.out.println(itr2.next()); 252 | } 253 | } 254 | } 255 | 256 | ``` 257 | Output: 258 | ``` 259 | Neel 260 | Devansh 261 | 262 | chirag 263 | Neel 264 | Devansh 265 | hello 266 | ``` 267 | 268 | -------------------------------------------------------------------------------- /JAVA/containers/maps.md: -------------------------------------------------------------------------------- 1 |
2 |

Maps

3 |
4 | 5 | 6 | A map contains values on the basis of key i.e. key 7 | and value pair. Each key and value pair is known as an entry. Map contains only unique keys. 8 | Map is useful if you have to search, update or delete elements on the basis of key. 9 | 10 | ## HashMaps 11 | Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map 12 | interface. 13 | The important points about Java HashMap class are: 14 | 15 | * A HashMap contains values based on the key. 16 | * It contains only unique elements. 17 | * It may have one null key and multiple null values. 18 | * It maintains no order. 19 | 20 | **HashMap Class Declaration** 21 | ```java 22 | public class HashMap extends AbstractMapimplements Map, Cloneable, Serializable 23 | ``` 24 | *Where* 25 | * K: It is the type of keys maintained by this map. 26 | * V: It is the type of mapped values. 27 | 28 | **Constructors of Java HashMap class :** 29 | 30 | | Constructor | Description | 31 | | :---------------| :--------------------| 32 | |HashMap()| It is used to construct a default HashMap. 33 | |HashMap(Map m) |It is used to initializes the hash map by using the elements of the given Map object m. 34 | |HashMap(int capacity) |It is used to initializes the capacity of the hash map to the given integer value, capacity. 35 | |HashMap(int capacity, float fillRatio)| It is used to initialize both the capacity and fill ratio of the hash map by using its arguments.| 36 | 37 | 38 | **Methods of HashMaps Class** 39 | 40 | | Method | Description | 41 | | :------------------- | :------------------ | 42 | |void clear()| It is used to remove all of the mappings from this map.| 43 | | boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key.| 44 | | boolean containsValue(Object value) | It is used to return true if this map maps one or more keys to the specified value.| 45 | | boolean isEmpty()| It is used to return true if this map contains no key-value mappings.| 46 | |Object clone()| It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.| 47 | |Set entrySet() | It is used to return a collection view of the mappings contained in this map. | 48 | | Set keySet() | It is used to return a set view of the keys contained in this map.| 49 | |Object put(Object key, Object value)| It is used to associate the specified value with the specified key in this map.| 50 | |int size()| It is used to return the number of key-value mappings in this map.| 51 | |Collection values() |It is used to return a collection view of the values contained in this map| 52 | 53 | ### Example 54 | ``` java 55 | import java.util.*; 56 | class TestCollection13{ 57 | public static void main(String args[]){ 58 | HashMap hm=new HashMap(); 59 | hm.put(100,"Amit"); 60 | hm.put(101,"Vijay"); 61 | hm.put(102,"Rahul"); 62 | for(Map.Entry m:hm.entrySet()){ 63 | System.out.println(m.getKey()+" "+m.getValue()); 64 | } 65 | } 66 | } 67 | ``` 68 | #### Output 69 | ```java 70 | 102 Rahul 71 | 100 Amit 72 | 101 Vijay 73 | ``` 74 | 75 | 76 | 77 | 78 | ## TreeMaps 79 | 80 | Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order. 81 | 82 | The important points about Java TreeMap class are: 83 | 84 | * A TreeMap contains values based on the key. 85 | * It implements the NavigableMap interface and extends AbstractMap class. 86 | * It contains only unique elements. 87 | * It cannot have null key but can have multiple null values. 88 | * It is same as HashMap instead maintains ascending order. 89 | 90 | **Tree Map class declaration** 91 | 92 | ```java 93 | public class TreeMap extends AbstractMapimplements NavigableMap, Cloneable, Serializable 94 | ``` 95 | *Where* 96 | * K: It is the type of keys maintained by this map. 97 | * V: It is the type of mapped values. 98 | 99 | **Constructors of Java TreeMap class :** 100 | 101 | |Constructor| Description| 102 | | :---------------| :--------------------| 103 | |TreeMap()| It is used to construct an empty tree map that will be sorted using the natural order of its key. 104 | |TreeMap(Comparator comp)| It is used to construct an empty tree-based map that will be sorted using the comparator comp. 105 | |TreeMap(Map m)| It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys. 106 | |TreeMap(SortedMap sm)| It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm.| 107 | 108 | **Methods of Java TreeMap class** 109 | 110 | | Method| Description | 111 | | :-----------------| :---------------------| 112 | |boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key.| 113 | |boolean containsValue(Object value)| It is used to return true if this map maps one or more keys to the specified value. 114 | |Object firstKey() |It is used to return the first (lowest) key currently in this sorted map. 115 | |Object get(Object key)| It is used to return the value to which this map maps the specified key.| 116 | |Object lastKey()| It is used to return the last (highest) key currently in this sorted map. 117 | |Object remove(Object key) |It is used to remove the mapping for this key from this TreeMap if present.| 118 | |void putAll(Map map)| It is used to copy all of the mappings from the specified map to this map. 119 | |Set entrySet()| It is used to return a set view of the mappings contained in this map.| 120 | |int size()| It is used to return the number of key-value mappings in this map.| 121 | |Collection values()| It is used to return a collection view of the values contained in this map. 122 | 123 | 124 | ### Example 125 | 126 | ```java 127 | import java.util.*; 128 | class TestCollection15{ 129 | public static void main(String args[]){ 130 | TreeMap hm=new TreeMap(); 131 | hm.put(100,"Amit"); 132 | hm.put(102,"Ravi"); 133 | hm.put(101,"Vijay"); 134 | hm.put(103,"Rahul"); 135 | for(Map.Entry m:hm.entrySet()){ 136 | System.out.println(m.getKey()+" "+m.getValue()); 137 | } 138 | } 139 | } 140 | ``` 141 | #### Output 142 | ```java 143 | 100 Amit 144 | 101 Vijay 145 | 102 Ravi 146 | 103 Rahul 147 | ``` 148 | **Note :** 149 | ###### Difference between Hash Map and Tree Maps : 150 | 151 | |HashMap| TreeMap| 152 | | :--------------- | :--------------| 153 | |1) HashMap can contain one null key.| TreeMap can not contain any null key.| 154 | |2) HashMap maintains no order.| TreeMap maintains ascending order.| 155 | 156 | 157 | ## LinkedHashMap 158 | Java LinkedHashMap class is Hash table and Linked list 159 | implementation of the Map interface, with predictable 160 | iteration order. It inherits HashMap class and 161 | implements the Map interface. 162 | 163 | The important points about Java LinkedHashMap class 164 | are: 165 | * A LinkedHashMap contains values based on the key. 166 | * It contains only unique elements. 167 | * It may have one null key and multiple null values. 168 | * It is same as HashMap instead maintains insertion order. 169 | 170 | **LinkedMaps Class Declaration** 171 | ```java 172 | public class LinkedHashMap extends HashMapimplements Map 173 | ``` 174 | * K: It is the type of keys maintained by this map. 175 | * V: It is the type of mapped values. 176 | 177 | **Constructors of Java LinkedHashMap class :** 178 | 179 | |Constructor| Description| 180 | | :---------------| :--------------------| 181 | |LinkedHashMap()| It is used to construct a default LinkedHashMap. 182 | |LinkedHashMap(int capacity)| It is used to initialize a LinkedHashMap with the given capacity. 183 | |LinkedHashMap(int capacity, float fillRatio) |It is used to initialize both the capacity and the fillRatio. 184 | |LinkedHashMap(Map m)| It is used to initialize the LinkedHashMap with the elements from the given Map class m.| 185 | 186 | **Methods of LinkedHashMap Class** 187 | 188 | |Method|Description | 189 | | :----------------| :-------------------| 190 | |Object get(Object key) | It is used to return the value to which this map maps the specified key. 191 | |void clear() |It is used to remove all mappings from this map. 192 | |boolean containsKey(Object key)| It is used to return true if this map maps one or more keys to the specified value.| 193 | 194 | ###### Example 195 | ```java 196 | import java.util.*; 197 | class TestCollection14{ 198 | public static void main(String args[]){ 199 | 200 | LinkedHashMap hm=new LinkedHashMap(); 201 | 202 | hm.put(100,"Amit"); 203 | hm.put(101,"Vijay"); 204 | hm.put(102,"Rahul"); 205 | 206 | for(Map.Entry m:hm.entrySet()){ 207 | System.out.println(m.getKey()+" "+m.getValue()); 208 | } 209 | } 210 | } 211 | ``` 212 | **Output** 213 | ```java 214 | 100 Amit 215 | 101 Vijay 216 | 102 Rahul 217 | ``` 218 | -------------------------------------------------------------------------------- /JAVA/containers/queues.md: -------------------------------------------------------------------------------- 1 |

Queue

2 | 3 |
4 | 5 | >Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last. 6 | 7 |
8 | 9 | 10 | ### Operations 11 | 12 | 13 | |
Function
|
What it does?
|
Complexity
| 14 | | :------------- | :------------- | :------------- | 15 | | boolean add(object) |It is used to insert the specified element into this queue and return true upon success.|O(log(n)) | 16 | | boolean offer(object) |It is used to insert the specified element into this queue.|O(log(n)) 17 | |Object remove() |It is used to retrieves and removes the head of this queue.|O(log(n)) 18 | |Object poll() |It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.|O(1) 19 | |Object peek() |It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.|O(1) 20 | 21 |

Priority Queues

22 | 23 | > Java Priority Queue is implemented using Heap Data Structures 24 | 25 | ### Implementions 26 | 27 | 28 | 29 | ```java 30 | // Java progrm to demonstrate working of priority queue in Java 31 | import java.util.*; 32 | 33 | class Example 34 | { 35 | public static void main(String args[]) 36 | { 37 | 38 | PriorityQueue pQueue = 39 | new PriorityQueue(); 40 | 41 | pQueue.add("Shivam"); 42 | pQueue.add("Neel"); 43 | pQueue.add("Devansh"); 44 | 45 | System.out.println("Head value using peek function:" 46 | + pQueue.peek()); 47 | 48 | System.out.println("The queue elements:"); 49 | Iterator itr = pQueue.iterator(); 50 | while (itr.hasNext()) 51 | System.out.println(itr.next()); 52 | 53 | pQueue.poll(); 54 | System.out.println("After removing an element" + 55 | "with poll function:"); 56 | Iterator itr2 = pQueue.iterator(); 57 | while (itr2.hasNext()) 58 | System.out.println(itr2.next()); 59 | 60 | pQueue.remove("Neel"); 61 | System.out.println("after removing Java with" + 62 | " remove function:"); 63 | Iterator itr3 = pQueue.iterator(); 64 | while (itr3.hasNext()) 65 | System.out.println(itr3.next()); 66 | 67 | 68 | } 69 | } 70 | ``` 71 | 72 | 73 | Output: 74 | ``` 75 | Head value using peek function:Shivam 76 | The queue elements: 77 | Shivam 78 | Neel 79 | Devansh 80 | 81 | After removing an elementwith poll function: 82 | Neel 83 | Devansh 84 | after removing Neel with remove function: 85 | Devansh 86 | ``` 87 | 88 | 89 | -------------------------------------------------------------------------------- /JAVA/containers/sets.md: -------------------------------------------------------------------------------- 1 |
2 |

Sets

3 |
4 | 5 | 6 | A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. 7 | ## HashSets : 8 | * Java HashSet class is used to create a collection that uses a hash table for storage. 9 | * It inherits the AbstractSet class and implements Set interface. 10 | * The important points about Java HashSet class are: 11 | * HashSet stores the elements by using a mechanism called hashing. 12 | * HashSet contains unique elements only. 13 | 14 | **Hierarchy of HashSet class** : 15 | The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order. 16 | 17 | **HashSet class declaration** 18 | ```java 19 | public class HashSet extends AbstractSet implements Set, Cloneable, Serializable 20 | ``` 21 | **Constructors of Java HashSet class :** 22 | 23 | |Constructor | Description | 24 | | :---------------| :--------------------| 25 | |HashSet() | It is used to construct a default HashSet. 26 | |HashSet(Collection c) |It is used to initialize the hash set by using the elements of the collection c.| 27 | |HashSet(int capacity)| It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.| 28 | 29 | **Methods of Java HashSet class:** 30 | 31 | | Method | Description| 32 | | :--------------| :------------------ 33 | |void clear() |It is used to remove all of the elements from this set.| 34 | |boolean contains(Object o)| It is used to return true if this set contains the specified element. 35 | |boolean add(Object o) |It is used to adds the specified element to this set if it is not already present. 36 | |boolean isEmpty() |It is used to return true if this set contains no elements. 37 | |boolean remove(Object o) |It is used to remove the specified element from this set if it is present. 38 | |Object clone()| It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned. 39 | |Iterator iterator() |It is used to return an iterator over the elements in this set. 40 | |int size()| It is used to return the number of elements in this set.| 41 | 42 | ##### Example : 43 | ```java 44 | import java.util.*; 45 | class TestCollection9{ 46 | public static void main(String args[]){ 47 | //Creating HashSet and adding elements 48 | HashSet set=new HashSet(); 49 | set.add("Ravi"); 50 | set.add("Vijay"); 51 | set.add("Ravi"); 52 | set.add("Ajay"); 53 | //Traversing elements 54 | Iterator itr=set.iterator(); 55 | while(itr.hasNext()){ 56 | System.out.println(itr.next()); 57 | } 58 | } 59 | } 60 | ``` 61 | **Output :** 62 | ```java 63 | Ajay 64 | Vijay 65 | Ravi 66 | ``` 67 | 68 | ## LinkedHashSet : 69 | Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface. 70 | 71 | The important points about Java LinkedHashSet class are: 72 | * Contains unique elements only like HashSet. 73 | * Provides all optional set operations, and permits null elements. 74 | * Maintains insertion order. 75 | 76 | **Hierarchy of LinkedHashSet class** 77 | 78 | The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order. 79 | 80 | **LinkedHashSet class declaration** 81 | ```java 82 | public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable 83 | ``` 84 | **Constructors of Java LinkedHashSet class** 85 | 86 | |Constructor|Description| 87 | | :--------------| :-------------------------| 88 | |HashSet()| It is used to construct a default HashSet. 89 | |HashSet(Collection c) |It is used to initialize the hash set by using the elements of the collection c. 90 | |LinkedHashSet(int capacity)| It is used initialize the capacity of the linkedhashset to the given integer value capacity. 91 | |LinkedHashSet(int capacity, float fillRatio)| It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument. 92 | 93 | **Example :** 94 | 95 | ```java 96 | import java.util.*; 97 | class TestCollection10{ 98 | public static void main(String args[]){ 99 | LinkedHashSet al=new LinkedHashSet(); 100 | al.add("Ravi"); 101 | al.add("Vijay"); 102 | al.add("Ravi"); 103 | al.add("Ajay"); 104 | Iterator itr=al.iterator(); 105 | while(itr.hasNext()){ 106 | System.out.println(itr.next()); 107 | } 108 | } 109 | } 110 | ``` 111 | **Output :** 112 | ```java 113 | Ravi 114 | Vijay 115 | Ajay 116 | ``` 117 | 118 | ## TreeSet : 119 | Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order. 120 | 121 | The important points about Java TreeSet class are: 122 | * Contains unique elements only like HashSet. 123 | * Access and retrieval times are quiet fast. 124 | * Maintains ascending order. 125 | * Hierarchy of TreeSet class 126 | * Java TreeSet class implements NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order. 127 | 128 | **TreeSet class declaration :** 129 | ```java 130 | public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, Serializable 131 | ``` 132 | **Constructors of Java TreeSet class :** 133 | 134 | |Constructor|Description| 135 | | :-----------------------| :-------------------------| 136 | |TreeSet() |It is used to construct an empty tree set that will be sorted in an ascending order according to the natural order of the tree set.| 137 | |TreeSet(Collection c) |It is used to build a new tree set that contains the elements of the collection c. 138 | |TreeSet(Comparator comp)| It is used to construct an empty tree set that will be sorted according to given comparator. 139 | |TreeSet(SortedSet ss)| It is used to build a TreeSet that contains the elements of the given SortedSet.| 140 | 141 | **Methods of Java TreeSet class :** 142 | 143 | |Method| Description | 144 | | :---------------- |:--------------------- 145 | |boolean addAll(Collection c) |It is used to add all of the elements in the specified collection to this set. 146 | |boolean contains(Object o)| It is used to return true if this set contains the specified element.| 147 | |boolean isEmpty()| It is used to return true if this set contains no elements.| 148 | |boolean remove(Object o)| It is used to remove the specified element from this set if it is present. 149 | |void add(Object o)| It is used to add the specified element to this set if it is not already present. 150 | |void clear() |It is used to remove all of the elements from this set. 151 | |Object clone()| It is used to return a shallow copy of this TreeSet instance. 152 | |Object first()| It is used to return the first (lowest) element currently in this sorted set. 153 | |Object last()| It is used to return the last (highest) element currently in this sorted set. 154 | |int size()| It is used to return the number of elements in this set.| 155 | 156 | **Example : ** 157 | ```java 158 | import java.util.*; 159 | class TestCollection11{ 160 | public static void main(String args[]){ 161 | //Creating and adding elements 162 | TreeSet al=new TreeSet(); 163 | al.add("Ravi"); 164 | al.add("Vijay"); 165 | al.add("Ravi"); 166 | al.add("Ajay"); 167 | //Traversing elements 168 | Iterator itr=al.iterator(); 169 | while(itr.hasNext()){ 170 | System.out.println(itr.next()); 171 | } 172 | } 173 | } 174 | ``` 175 | **Output :** 176 | 177 | ```java 178 | Ajay 179 | Ravi 180 | Vijay 181 | ``` -------------------------------------------------------------------------------- /JAVA/containers/stack.md: -------------------------------------------------------------------------------- 1 |

Stack

2 | 3 |
4 | 5 | >Java provides an inbuilt object type called Stack. It is a collection that is based on the last in first out (LIFO) principle. On Creation, a stack is empty. 6 | 7 |
8 | 9 | 10 | ### Operations 11 | 12 | 13 | |
Function
|
What it does?
|
Complexity
| 14 | | :------------- | :------------- | :------------- | 15 | | Object push(Object element) |Pushes an element on the top of the stack.|O(1) | 16 | | Object pop() | Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty.|O(1) | 17 | |Object peek( ) |Returns the element on the top of the stack, but does not remove it.|O(1) | 18 | |boolean empty() |It returns true if nothing is on the top of the stack. Else, returns false.|O(1)| 19 | |int search(Object element) | It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.| - | 20 | 21 | ### Implementions 22 | 23 | ```java 24 | import java.io.*; 25 | import java.util.*; 26 | 27 | class Main 28 | { 29 | public static void main (String[] args) 30 | { 31 | Stack stack = new Stack(); 32 | 33 | stack.push(10); 34 | stack.push(3); 35 | stack.push(5); 36 | stack.push(20); 37 | System.out.println("Current Stack [ bottom to top ]"); 38 | for(Integer i : stack){ 39 | System.out.print(" "+i); 40 | } 41 | System.out.println("Popped : "+ stack.pop()); 42 | stack.push(7); 43 | System.out.println("Peak : " + stack.peek()) ; 44 | System.out.println("Element 3 at position : " + stack.search(3)); 45 | } 46 | } 47 | 48 | ``` 49 | 50 | 51 | Output: 52 | ``` 53 | Current Stack 54 | 10 3 5 20 55 | Popped : 20 56 | Peak : 7 57 | Element 3 at position : 3 58 | ``` 59 | 60 | 61 | -------------------------------------------------------------------------------- /JAVA/p1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p1.JPG -------------------------------------------------------------------------------- /JAVA/p2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p2.JPG -------------------------------------------------------------------------------- /JAVA/p3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p3.JPG -------------------------------------------------------------------------------- /JAVA/p4.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p4.JPG -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 KJSCE Codecell 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 |

Standard Template Library

2 | 3 |
4 | 5 | [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) 6 | [![HitCount](http://hits.dwyl.io/KJSCE-Codecell/standard-library-in-x.svg)](http://hits.dwyl.io/KJSCE-Codecell/standard-library-in-x) 7 | [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/dwyl/esta/issues) 8 |
9 | [![Generic badge](https://img.shields.io/badge/MadeIn-Python-.svg)](https://shields.io/) 10 | [![Generic badge](https://img.shields.io/badge/MadeIn-CPP-.svg)](https://shields.io/) 11 | [![Generic badge](https://img.shields.io/badge/MadeIn-JAVA-.svg)](https://shields.io/) 12 | 13 |
14 | 15 | --- 16 | 17 | A comprehensive guide to standard template library to make your life easier in X where: 18 | * [X = C++](./cpp/README.md) 19 | * [X = Python](./python/Readme.md) 20 | * [X = Java](./JAVA/README.md) 21 | 22 | --- 23 |

Built by folks at KJSCE CODECELL with :heart:

-------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker 2 | -------------------------------------------------------------------------------- /cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/cpp/.DS_Store -------------------------------------------------------------------------------- /cpp/Iterators.md: -------------------------------------------------------------------------------- 1 |

Iterators

2 | 3 |

INTRODUCTION

4 | 5 | What are iterators? In STL iterators are the most general way to access data in containers
6 | An iterator is any object that, points to some element in a range of elements (such as an array or a container) and has the ability 7 | to iterate through those elements using a set of operators (with at least the increment (++) and dereference (*) operators).
8 | Iterators provide some common additional functionality to container and makes it possible to iterate(traverse) through the containers which 9 | can be accessed through the bracket( **[ ]** ) operator.
10 | The main advantage of iterators, of course, is that they greatly increase the reuse of code: your own algorithms, based on iterators, will work on a wide range of containers, and your own containers, 11 | which provide iterators, may be passed to a wide range of standard functions. 12 | 13 |

CONSTRUCTION

14 | general construction of iterators looks like 15 | 16 | ```cpp 17 | Container ::iterator name; 18 | ``` 19 | ex. for creating an iterator for a vector 20 | 21 | ```cpp 22 | vector ::iterator it; 23 | ``` 24 | 25 | for list 26 | 27 | ```cpp 28 | list ::iterator it; 29 | ``` 30 |
31 | 32 |

FUNCTIONS

33 | 34 | |
Function
|
What it does ?
| 35 | | :------------- | :------------- | 36 | | **begin()** |This function is used to return the beginning position of the container. | 37 | | **end()** |This function is used to return the end position of the container | 38 | | **advance()** |This function is used to increment the iterator position till the specified number mentioned in its arguments | 39 | | **next()** |This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments | 40 | | **prev()** |This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments | 41 | | **inserter()** | This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted. | 42 | | **distance()** |Calculates the number of elements between first and last| 43 | 44 | **Note** - A few datatypes allow '-' operation to find the distance *second-first* but these aren't allowed for all containers hence we use distance(). 45 | 46 |

IMPLEMENTATION

47 | 48 | The following is the implementation of few iterator function in vectors, 49 | ```cpp 50 | 51 | #include 52 | #include // for iterators 53 | #include // for vectors 54 | using namespace std; 55 | int main() 56 | { 57 | vector ar = { 1, 2, 3, 4, 5 }; 58 | // Declaring iterator to a vector 59 | vector::iterator ptr; 60 | // Displaying vector elements using begin() and end() 61 | cout << "The vector elements are : "; 62 | for (ptr = ar.begin(); ptr < ar.end(); ptr++) 63 | cout << *ptr << " "; 64 | cout<<"\n"; 65 | vector::iterator ptr1 = ar.begin(); 66 | advance(ptr1, 3); 67 | cout << "The position of iterator after advancing is : "; 68 | cout << *ptr1 << " "; 69 | return 0; 70 | } 71 | 72 | ``` 73 | Output: 74 | ``` 75 | The vector elements are : 76 | 1 2 3 4 5 77 | The position of iterator after advancing is : 78 | 4 79 | 80 | ``` 81 |
82 | 83 |

REVERSE ITERATORS

84 | 85 |

INTRODUCTION

86 | 87 | Reverse iterator is an iterator adaptor that reverses the direction of a given iterator. 88 | In other words, when provided with a bidirectional iterator, std::reverse_iterator produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator.
89 | Here we make us of rend() and rbegin() where rbegin() points to the last element of the container and rend() points to one position before the first element.
90 | Using the operation ++ makes the iterator move a step towards the first element 91 | 92 |

IMPLEMENTATION

93 | 94 | ```cpp 95 | for(vector::reverse_iterator i=ar.rbegin();i!=ar.rend();++i) 96 | { 97 | cout<<*i<<" "; 98 | } 99 | ``` 100 | Output: 101 | 102 | ``` 103 | 5 4 3 2 1 104 | ``` 105 | All other functions are the same as that of the iterators. 106 | 107 | **Note** - (For some lazy people) some efforts in typing of syntax can be reduced if you make use of **auto** keyword used provided by c++, using this the above implementation would look like: 108 | 109 | ```cpp 110 | for(auto i=ar.rbegin();i!=ar.rend();++i) 111 | { 112 | cout<<*i<<" "; 113 | } 114 | ``` 115 | -------------------------------------------------------------------------------- /cpp/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

C++ STL

4 | 5 |
6 | 7 | ### Index 8 | 1. [Introduction](./introduction.md) 9 | 2. [What are templates?](./templates.md) 10 | 3. Containers 11 | 1. [Vectors](./containers/Vectors.markdown) 12 | 2. [Iterators](./Iterators.md) 13 | 3. [Sets](./containers/sets.md) 14 | 1. Unordered Sets 15 | 2. Multiset 16 | 4. [Maps](./containers/maps.md) 17 | 1. Unordered Maps 18 | 2. Multimap 19 | 5. [Pairs & Tuples](./containers/Pairs&Tuples.markdown) 20 | 6. [Queue](./containers/queue.md) 21 | 1. Priority Queue 22 | 7. [Stack](./containers/stacks.md) 23 | 8. [Bitset](./containers/bitsets.md) 24 | 4. In-built functions 25 | 1. [next_permutation()](./functions/next_permutation.md) 26 | 2. [max_element()](./functions/max_element.md) 27 | 3. [min_element()](./functions/min_element.md) 28 | 4. [binary_search()](./functions/binary_search.md) 29 | 5. [lower_bound()](./functions/lower_bound.md) 30 | 6. [upper_bound()](./functions/upper_bound.md) 31 | 7. [sort()](./functions/sort.md) 32 | 8. [reverse()](./functions/reverse.md) 33 | 9. [set_union()](./functions/set_union.md) 34 | 10. [set_intersection()](./functions/set_intersection.md) 35 | 11. [set_difference()](./functions/set_difference.md) 36 | 12. [max() & min()](./functions/MaxMin.md) 37 | 13. [is_sorted()](./functions/is_sorted.md) 38 | 5. Solutions to problem 39 | 1. [Second Year Pains-KJCP02](./problems/kjcp02.cpp) 40 | 2. [Sorting Tool-KJCPR](./problems/kjcp01.cpp) 41 | 3. [Snake Eat-SNAKEEAT](./problems/snakeeat.cpp) 42 | 4. [Ipc Trainers-IPCTRAIN](./problems/ipctrain.cpp) 43 | 5. [Chef Subseq-CHEFCODE](./problems/chefcode.cpp) 44 | -------------------------------------------------------------------------------- /cpp/containers/Pairs&Tuples.markdown: -------------------------------------------------------------------------------- 1 |

Pairs & Tuples


2 | 3 |

Pairs

4 | 5 |

Introduction

6 | 7 | Many times while solving various problem where we require 2 values to completely linked with each other in such a scenario it is best to use pairs.
8 | Pair is a container that can be used to bind together a two values which may be of different types. Pair provides a way to store two heterogeneous objects as a single unit. 9 | 10 |

construction

11 | The simplest form in general would be the following: 12 | 13 | ```cpp 14 | template struct pair { 15 | T1 first; 16 | T2 second; 17 | }; 18 | 19 | ``` 20 | 21 | In general pair is a pair of integer values. At a more complex level, pair > is a pair of string and two integers. In the second case, the usage may be like this: 22 | 23 | 24 | ```cpp 25 | pair > P; 26 | string s = P.first; // extract string 27 | int x = P.second.first; // extract first int 28 | int y = P.second.second; // extract second int 29 | 30 | ``` 31 | 32 | 33 | We can also initialize a pair just like in vectors 34 | 35 | ```cpp 36 | pair Pair_name (value1, value2) ; 37 | pair g1; //default 38 | pair g2(1, 'a'); //initialized, different data type 39 | pair g3(1, 10); //initialized, same data type 40 | pair g4(g3); //copy of g3 41 | 42 | ``` 43 | 44 |

Functions

45 | 46 | |
Function
|
What it does ?
|
Complexity
| 47 | | :------------- | :------------- | :------------- | 48 | | make_pair() |This template function allows to create a value pair without writing the types explicitly |O(1) 49 | | operators(=, ==, !=, >=, <=) : |These operations can be appllied to pairs|O(1) 50 | | swap() |This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of same type. |O(1) 51 | 52 |

Implementation

53 | 54 | ```cpp 55 | #include 56 | #include //required for pairs 57 | using namespace std; 58 | 59 | int main() 60 | { 61 | pair PAIR1 ; 62 | pair PAIR2 ("Codecell", 1.23) ; 63 | pair PAIR3 ; 64 | 65 | PAIR1.first = 100; 66 | PAIR1.second = 'C' ; 67 | 68 | PAIR3 = make_pair ("Codecell is Best",4.56); 69 | 70 | cout << PAIR1.first << " " ; 71 | cout << PAIR1.second << endl ; 72 | 73 | cout << PAIR2.first << " " ; 74 | cout << PAIR2.second << endl ; 75 | 76 | cout << PAIR3.first << " " ; 77 | cout << PAIR3.second << endl ; 78 | 79 | pairpair1 = make_pair(1, 12); 80 | pairpair2 = make_pair(9, 12); 81 | 82 | cout << (pair1 == pair2) << endl; //compares both first and second values for equality 83 | cout << (pair1 != pair2) << endl; // checks first if they are equal then second 84 | cout << (pair1 >= pair2) << endl; //checks first followed by second 85 | cout << (pair1 <= pair2) << endl; 86 | cout << (pair1 > pair2) << endl; 87 | cout << (pair1 < pair2) << endl; 88 | 89 | cout << "Before swapping:\n " ; 90 | cout << "Contents of pair1 = " << pair1.first << "," << pair1.second ; 91 | cout << "Contents of pair2 = " << pair2.first << "," << pair2.second ; 92 | pair1.swap(pair2); 93 | 94 | cout << "\nAfter swapping:\n "; 95 | cout << "Contents of pair1 = " << pair1.first << "," << pair1.second ; 96 | cout << "Contents of pair2 = " << pair2.first << "," << pair2.second ; 97 | 98 | return 0; 99 | } 100 | ``` 101 | Output 102 | 103 | ``` 104 | 100 C 105 | Codecell 1.23 106 | Codecell is Best 4.56 107 | 0 108 | 1 109 | 0 110 | 1 111 | 0 112 | 1 113 | Before swapping: 114 | Contents of pair1 = 1,12 115 | Contents of pair2 = 9,12 116 | After swapping: 117 | Contents of pair1 = 9,12 118 | Contents of pair2 = 1,12 119 | ``` 120 |

Note

121 | Pairs are mainly used at places where we need to rearrange certain data types(sort/insert) but keep together another value related to along with it throughout the process for certain use
122 | By default sorting a pair related container causes data compared on the basis of first parameter although we can create some custom compare function to change the behavior
123 | 124 | ```cpp 125 | #include 126 | using namespace std; 127 | 128 | int main() 129 | { 130 | // Declaring vector of pairs 131 | vector< pair > vect; 132 | 133 | // Initializing 1st and 2nd element of 134 | // pairs with array values 135 | int arr[] = {10, 20, 5, 40 }; 136 | int arr1[] = {30, 60, 20, 50}; 137 | int n = sizeof(arr)/sizeof(arr[0]); 138 | 139 | // Entering values in vector of pairs 140 | for (int i=0; i Tuples 189 | 190 | 191 |

Introduction

192 | 193 | Tuples are nothing completely different but pairs extended from their limitation of size two. In problem solving many time we may accross situation where we require 3-4 values linked together as one that is when we use tuples
194 | A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed 195 | 196 | 197 |

Operations

198 | 199 | |
Function
|
What it does ?
| 200 | | :------------- | :------------- | 201 | | get() |get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element | 202 | | make_tuple() |make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in tuple| 203 | | tuple_size |It returns the number of elements present in the tuple | 204 | | swap() |The swap(), swaps the elements of the two different tuples.| 205 | | tie() |The work of tie() is to unpack the tuple values into seperate variables. There are two variants of tie(), with and without “ignore” , the “ignore” ignores a particular tuple element and stops it from getting unpacked.| 206 | | tuple_cat() |This function concatenates two tuples and returns a new tuple| 207 | 208 | 209 |

Implementation

210 | 211 | 212 | ```cpp 213 | 214 | #include 215 | #include // for tuple 216 | using namespace std; 217 | int main() 218 | { 219 | // Initializing variables for unpacking 220 | int i_val; 221 | char ch_val; 222 | float f_val; 223 | 224 | // Declaring tuple 225 | tuple gk; 226 | 227 | // Assigning values to tuple using make_tuple() 228 | gk = make_tuple('a', 10, 15.5); 229 | 230 | // Initializing tuple 231 | tuple tup1(20,'g',17.5); 232 | 233 | // Printing initial tuple values using get() 234 | cout << "The initial values of tuple are : "; 235 | cout << get<0>(gk) << " " << get<1>(gk); 236 | cout << " " << get<2>(gk) << endl; 237 | 238 | // Use of get() to change values of tuple 239 | get<0>(gk) = 'b'; 240 | get<2>(gk) = 20.5; 241 | 242 | // Printing modified tuple values 243 | cout << "The modified values of tuple are : "; 244 | cout << get<0>(gk) << " " << get<1>(gk); 245 | cout << " " << get<2>(gk) << endl; 246 | 247 | // Use of size to find tuple_size of tuple 248 | cout << "The size of tuple is : "; 249 | cout << tuple_size::value << endl; 250 | 251 | // Use of tie() without ignore 252 | tie(i_val,ch_val,f_val) = tup1; 253 | 254 | // Displaying unpacked tuple elements 255 | // without ignore 256 | cout << "The unpacked tuple values (without ignore) are : "; 257 | cout << i_val << " " << ch_val << " " << f_val; 258 | cout << endl; 259 | 260 | // Use of tie() with ignore 261 | // ignores char value 262 | tie(i_val,ignore,f_val) = tup1; 263 | 264 | // Displaying unpacked tuple elements 265 | // with ignore 266 | cout << "The unpacked tuple values (with ignore) are : "; 267 | cout << i_val << " " << f_val; 268 | cout << endl; 269 | 270 | // Concatenating 2 tuples to return a new tuple 271 | auto tup3 = tuple_cat(gk,tup1); 272 | // Displaying new tuple elements 273 | cout << "The new tuple elements in order are : "; 274 | cout << get<0>(tup3) << " " << get<1>(tup3) << " "; 275 | cout << get<2>(tup3) << " " << get<3>(tup3) << " "; 276 | cout << get<4>(tup3) << " " << get<5>(tup3) << endl; 277 | 278 | return 0; 279 | } 280 | 281 | ``` 282 | 283 | Output: 284 | 285 | ``` 286 | The initial values of tuple are : a 10 15.5 287 | The modified values of tuple are : b 10 20.5 288 | The size of tuple is : 3 289 | The unpacked tuple values (without ignore) are : 20 g 17.5 290 | The unpacked tuple values (with ignore) are : 20 17.5 291 | The new tuple elements in order are : b 10 20.5 20 g 17.5 292 | ``` 293 | 294 |

Note

295 | Although it might seem to you that tuples are not of much importance but that is not the case it does saves your time in and makes your code clean for writing nested pairs
296 | Also the functionality of sorting of pairs can be extended to tuples by appropriately modifying the custom function involved. 297 | -------------------------------------------------------------------------------- /cpp/containers/Vectors.markdown: -------------------------------------------------------------------------------- 1 |

Vectors

2 | 3 |

INTRODUCTION

4 | 5 | The simplest STL container is vector.
6 | Vector is just an array with extended functionality. In other words, vectors are dynamic arrays. 7 | 8 |

CONSTRUCTION

9 | 10 | ```cpp 11 | vector a; //empty vector 12 | vector b (no of elements, value of each element); //fixed number of elements with default value 13 | vector c (starting iterator/pointer,ending iterator/pointer); //inserting elements from other data structures 14 | vector d (name of vector to be copied); 15 | vector > matrix(no of rows,vector(no of coloumn,default value)) //Declaring a 2D array 16 | 17 | // Note: 18 | vector v[10]; // following declaration isn't a vector with 10 elements but an array of size ten having vector elements 19 | 20 | ``` 21 |
22 | 23 |

FUNCTIONS

24 | 25 | |
Function
|
What it does ?
|
Complexity
| 26 | | :------------- | :------------- | :------------- | 27 | | at() |Returns the reference to the element at a particular position (can also be done using ‘[ ]’ operator) |O(1) 28 | | clear() |Deletes all the elements from the vector and assign an empty vector |O(N) 29 | | pop_back() |Removes the last element from the vector |O(1) 30 | | push_back() |Inserts a new element at the end of the vector |O(1) 31 | | front() |Returns reference of the first element |O(1) 32 | | back() |Returns reference of the last element |O(1) 33 | | empty() |Returns 1 if vector is empty, else 0 |O(1) 34 | | size() |Returns the total no of elements in the vector| O(1) 35 | | resize() |Resizes the vector to the new length which can be less than or greater than the current length |O(N) 36 | 37 | 38 |

Note

39 | begin() and end() function return an iterator(like a pointer) initialized to the first or the last element of the container that can be used to iterate through the collection, while front() and back() function just return a reference to the first or the last element of the container. 40 | 41 |

PASSING AS ARGUMENT TO FUNCTION

42 | 43 | Another very important thing that you should remember: When vector is passed as a parameter to some function, a copy of vector is actually created. It may take a lot of time and memory to create new vectors when they are not really needed. 44 | ```cpp 45 | void some_function(vector v) { // Never do it unless you’re sure what you do! 46 | // ... 47 | } 48 | ``` 49 | Instead, use the following construction: 50 | ```cpp 51 | int modify_vector(vector& v) { // Correct 52 | V[0]++; 53 | } 54 | ``` 55 | 56 |

Implementation

57 | 58 | ```cpp 59 | #include 60 | #include 61 | 62 | using namespace std; 63 | 64 | int main() 65 | { 66 | vector v; 67 | v.push_back(5); 68 | while(v.back() > 0) 69 | v.push_back(v.back() - 1); 70 | for(int i = 0;i < v.size();++i) 71 | cout << v.at(i) << ' '; 72 | cout << endl; 73 | while(!v.empty()) 74 | { 75 | cout << v.back() << ' '; 76 | v.pop_back(); 77 | } 78 | cout << endl; 79 | return 0; 80 | } 81 | ``` 82 | 83 | Output: 84 | ``` 85 | 5 4 3 2 1 0 86 | 0 1 2 3 4 5 87 | ``` 88 |
89 | Further much more functionality can be understood once we start using iterators 90 | -------------------------------------------------------------------------------- /cpp/containers/bitsets.md: -------------------------------------------------------------------------------- 1 |

Bitsets

2 | 3 |

INTRODUCTION

4 | 5 | * A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than other methods to store them.
6 | * However, a limitation of bitset is, N must be known at compile time, it isn't dynamic
7 | * As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector. 8 | * We can access each bit of bitset individually with help of array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array.
9 |
!Remember bitset starts its indexing backward that is for 10110, 0 are at 0th and 3rd indices whereas 1 are at 1st 2nd and 4th indices.
10 | 11 |

CONSTRUCTION

12 | 13 | ```cpp 14 | 15 | bitset<10> bset1; // default constructor initializes with all 10 bits 0 16 | 17 | bitset<10> bset2(20); // bset2 is initialized with bits of 20 18 | 19 | bitset<10> bset3(string("1100")); // bset3 is initialized with bits of specified binary string 20 | 21 | ``` 22 | 23 |

FUNCTIONS

24 | 25 | |
Function
|
What it does ?
| 26 | | :------------- | :------------- | 27 | | count() |Returns the number of bits in the bitset that are set (i.e., that have a value of one). | 28 | | size() |Returns the number of bits in the bitset. | 29 | | test() |Returns boolean value regarding a position being set | 30 | | any()/none() |Returns true/false if any bit is set in a given bitset | 31 | | all() |Returns true if all bits are set | 32 | | set() |Sets all bits to 1 or specific bits to 1 or 0 | 33 | | reset() |Sets all bits to 0 or specific pos to 0 | 34 | | flip() |Flips bitvalue at a specific or all positions | 35 | | to_string/to_ulong/to_ullong |Converts the bitsets into appropriate datatypes | 36 | 37 |

IMPLEMENTATION

38 | 39 | ```cpp 40 | 41 | #include 42 | #include 43 | #include //for bitsets 44 | using namespace std; 45 | 46 | #define M 32 47 | 48 | int main() 49 | { 50 | 51 | bitset<8> set8; // 00000000 52 | bitset<8> bset1; // 00000000 53 | 54 | // setting first bit (or 6th index) 55 | set8[1] = 1; // 00000010 56 | set8[4] = set8[1]; // 00010010 57 | cout << set8 << endl; 58 | 59 | int numberof1 = set8.count(); // count function returns number of set bits in bitset 60 | 61 | // size function returns total number of bits in bitset so there difference will give us number of unset(0) bits in bitset 62 | int numberof0 = set8.size() - numberof1; 63 | cout << set8 << " has " << numberof1 << " ones and " 64 | << numberof0 << " zeros\n"; 65 | 66 | cout << "bool representation of " << set8 << " : "; 67 | for (int i = 0; i < set8.size(); i++) 68 | cout << set8.test(i) << " "; // test function return 1 if bit is set else returns 0 69 | 70 | cout << endl; 71 | 72 | if (!set8.any()) // any function returns true, if atleast 1 bit is set 73 | cout << "set8 has no bit set.\n"; 74 | 75 | if (!bset1.any()) 76 | cout << "bset1 has no bit set.\n"; 77 | 78 | bset1[0]=1; 79 | 80 | // none function returns true, if none of the bits are set 81 | if (!bset1.none()) 82 | cout << "bset1 has atleast a bit set\n"; 83 | 84 | cout << set8.set() << endl; // bset.set() sets all bits 85 | 86 | cout << set8.set(4, 0) << endl; // bset.set(pos, b) makes bset[pos] = b 87 | 88 | cout << set8.set(4) << endl; // bset.set(pos) makes bset[pos]=1 89 | 90 | // reset function makes all bits 0 91 | cout << set8.reset(2) << endl; 92 | cout << set8.reset() << endl; 93 | 94 | // flip function flips all bits i.e. 1 <-> 0 95 | // and 0 <-> 1 96 | cout << set8.flip(2) << endl; 97 | cout << set8.flip() << endl; 98 | 99 | // Converting decimal number to binary by using bitset 100 | int num = 100; 101 | cout << "\nDecimal number: " << num 102 | << " Binary equivalent: " << bitset<8>(num)< set9(43); //00101011 107 | string s; 108 | s=set9.to_string(); 109 | cout<PROBLEMS 142 | 143 |

144 | NOTE!- As such bitset may not feel useful but there are particular sets of problems wherein such properties and function would save a lot of efforts and make things much more simpler. 145 | -------------------------------------------------------------------------------- /cpp/containers/maps.md: -------------------------------------------------------------------------------- 1 |
2 |

Map

3 |
4 | 5 |

Introduction:

6 | 7 | A map is a datastructure to store a key value pair. 8 | 9 |

Import:

10 | 11 | ```cpp 12 | #include 13 | ``` 14 | 15 |

Properties:

16 | 17 | 1. It is a datastructure which stores a key value pair. 18 | 19 | 2. Elements are referenced using their keys not by position(unlike arrays). 20 | 21 | 3. The elements are stored in orders(i.e. they are pre-sorted). 22 | 23 | 4. Internal implementation is like a binary search tree. 24 | 25 | 5. Size is increased and decreased automatically, according to storage needs. 26 | 27 | 6. Keys are unique. Same key cannot be used to store more than 1 values. 28 | 29 |

Usage:

30 |

1. Initialize

31 | 32 | Template has two data types first for key and second for value. User defined comparator can be added as third parameter. 33 | 34 |

2. Constructors

35 |

1. Default:

Makes an empty container. 36 |
37 | ```cpp 38 | map var_name; //Starts the var_name map with no key value pairs 39 | ``` 40 | 41 |
42 | 43 |

2. Range:

Used to copy range of elements from one map to other. 44 | 45 | ```cpp 46 | map var_name1; 47 | //fill 10 elements in var_name 48 | //If want to copy elements from 0-10 49 | map var_name2(var_name1.begin(),var_name1.end()); 50 | ``` 51 | 52 | Note: The template types should be same.
53 |

3. Copy:

54 | Copy entire container in new map object.
55 | 56 | ```cpp 57 | map var_name(map_object); 58 | ``` 59 | 60 | Copies the map_object in var_name. The map_object should be of same type.

61 | 62 |

3. Insert

63 |

1. Insert using key and value directly, using array-like syntax.

64 | 65 | ```cpp 66 | map map_object; 67 | map_object['a'] = 10; 68 | ``` 69 | 70 |
Note:
This method overwrites the previous value (if any). 71 | 72 |

2. Insert using insert()

73 | 74 | ```cpp 75 | map_object.insert(make_pair('b', 20)); 76 | ``` 77 | 78 |
Note:
This method does not overwrite the previous value (if any) but returns an object pointing to the previous value and new value is not inserted. 79 | 80 |

3. Returned object of insert()

81 | 82 | The return_object is a pair, first is an iterator to inserted element(or the same key element if insertion was prevented) and second is a boolean object which is true if insert happened and is false if it was stopped. 83 |
84 | 85 | ```cpp 86 | #include 87 | map mymap; 88 | mymap.insert ( pair('a',100) ); 89 | mymap.insert ( pair('z',200) ); 90 | 91 | pair::iterator,bool> ret; 92 | ret = mymap.insert (pair('z',500) ); 93 | if (ret.second==false) { 94 | cout << "element 'z' already existed"; 95 | cout << " with a value of " << ret.first->second << '\n'; 96 | } 97 | ``` 98 | 99 |

4. Access

100 | 101 |

1. Access using key directly

102 | 103 | ```cpp 104 | cout << mymap['b']; 105 | ``` 106 | 107 |

2. Access using at()

108 | 109 | ```cpp 110 | cout << mymap.at('b'); 111 | ``` 112 | 113 |

3. Access using find()

114 | 115 | ```cpp 116 | cout << mymap.find('b')->second; 117 | cout << (*mymap.find('b')).second; 118 | ``` 119 |
Note:
This method returns an iterator to the elements. 120 | 121 |

5. Delete

122 |

1. erase()

123 | 124 | ```cpp 125 | mymap.erase('b'); 126 | it = mymap.find('a'); 127 | mymap.erase(it, mymap.end()); 128 | ``` 129 | 130 |

6. Iteration

131 | 132 |

1. Begin()

Returns an iterator to first element in the map. 133 |

2. End()

Returns an iterator to the end of map (Not the last element). 134 | 135 | ```cpp 136 | map mymap; 137 | 138 | mymap['b'] = 100; 139 | mymap['a'] = 200; 140 | mymap['c'] = 300; 141 | for (std::map::iterator it=mymap.begin(); it!=mymap.end(); it++) 142 | std::cout << it->first << " => " << it->second << '\n'; 143 | return 0; 144 | ``` 145 | 146 |

Complexities

147 | 148 |

Insert: O(log(n))

149 |

Access: O(log(n))

150 |

Delete: O(1) + Access = O(log(n))

151 | 152 | 153 |
154 |

Unordered Map

155 |
156 | 157 |

Introduction:

158 | 159 | An unordered map is a datastructure to store a key value pair and access it fast enough. 160 | 161 |

Import:

162 | 163 | ```cpp 164 | #include 165 | ``` 166 | 167 |

Properties:

168 | 169 | 1. It is a datastructure which stores a key value pair. 170 | 171 | 2. Elements are referenced using their keys not by position(unlike arrays). 172 | 173 | 3. The elements are not sorted. 174 | 175 | 4. Internal implementation is using hashing. 176 | 177 | 5. Size is increased and decreased automatically, according to storage needs. 178 | 179 | 6. Keys are unique. Same key cannot be used to store more than 1 values. 180 | 181 | 7. Introduced in C++11. 182 | 183 |

Usage

184 |

1. Initialize

185 | 186 | Template has two data types first for key and second for value. 187 | 188 |

2. Constructors

189 |

1. Default:

Makes an empty container. 190 | 191 | ```cpp 192 | unordered_map var_name; //Starts the var_name map with no key value pairs 193 | ``` 194 | 195 |
196 | 197 |

2. Range:

Used to copy range of elements from one map to other. 198 | 199 | ```cpp 200 | unordered_map var_name1; 201 | //fill 10 elements in var_name 202 | //If want to copy elements from 0-10 203 | unordered_map var_name2(var_name1.begin(),var_name1.end()); 204 | ``` 205 | 206 | Note: The template types should be same.
207 |

3. Copy:

208 | Copy entire container in new map object.
209 | 210 | ```cpp 211 | unordered_map var_name(map_object); 212 | ``` 213 | 214 | Copies the map_object in var_name. The map_object should be of same type.

215 |

4. List:

216 | Initialize a list as a key value pair. 217 | 218 | 219 |

3. Insert

220 |

1. Insert using key and value directly, using array-like syntax.

221 | 222 | ```cpp 223 | unordered_map map_object; 224 | map_object['a'] = 10; 225 | ``` 226 | 227 |
Note:
This method overwrites the previous value (if any). 228 | 229 |

2. Insert using insert()

230 | 231 | ```cpp 232 | map_object.insert(make_pair('b', 20)); 233 | ``` 234 | 235 |
Note:
This method does not overwrite the previous value (if any) but returns an object pointing to the previous value and new value is not inserted. 236 | 237 |

3. Returned object of insert()

238 | 239 | The return_object is a pair, first is an iterator to inserted element(or the same key element if insertion was prevented) and second is a boolean object which is true if insert happened and is false if it was stopped. 240 | 241 | ```cpp 242 | unordered_map mymap; 243 | mymap.insert ( pair('a',100) ); 244 | mymap.insert ( pair('z',200) ); 245 | 246 | pair::iterator,bool> ret; 247 | ret = mymap.insert (pair('z',500) ); 248 | if (ret.second==false) { 249 | cout << "element 'z' already existed"; 250 | cout << " with a value of " << ret.first->second << '\n'; 251 | } 252 | ``` 253 | 254 |

4. Access

255 | 256 |

1. Access using key directly

257 | 258 | ```cpp 259 | cout << mymap['b']; 260 | ``` 261 | 262 |

2. Access using at()

263 | 264 | ```cpp 265 | cout << mymap.at('b'); 266 | ``` 267 | 268 |

3. Access using find()

269 | 270 | ```cpp 271 | cout << mymap.find('b')->second; 272 | cout << (*mymap.find('b')).second; 273 | ``` 274 | 275 |
Note:
This method returns an iterator to the elements. 276 | 277 |

5. Delete

278 |

1. erase()

279 | 280 | ```cpp 281 | mymap.erase('b'); 282 | it = mymap.find('a'); 283 | mymap.erase(it, mymap.end()); 284 | ``` 285 | 286 |

6. Iteration

287 | 288 |

1. Begin()

Returns an iterator to first element in the map. 289 |

2. End()

Returns an iterator to the end of map (Not the last element). 290 | 291 | ```cpp 292 | unordered_map mymap; 293 | 294 | mymap['b'] = 100; 295 | mymap['a'] = 200; 296 | mymap['c'] = 300; 297 | for (unordered_map::iterator it=mymap.begin(); it!=mymap.end(); it++) 298 | cout << it->first << " => " << it->second << '\n'; 299 | return 0; 300 | ``` 301 | 302 |

Complexities

303 | 304 |

Insert (Average Case): O(1)

305 |

Insert (Worst Case): O(n)

306 |

Access: O(1)

307 |

Delete (Average Case): O(1)

308 |

Delete (Worst Case): O(n)

309 | 310 | 311 |
312 |

Multimap

313 |
314 | 315 |

Introduction:

316 | 317 | A Multimap is a datastructure to store a key value pair having multiple keys. 318 | 319 |

Import:

320 | 321 | ```cpp 322 | #include 323 | ``` 324 | 325 |

Properites:

326 | 327 | Same as maps but only it can have multiple values for a key. 328 | 329 |

Usage:

330 |

1. Initialize

331 | 332 | Template has two data types first for key and second for value. User defined comparator can be added as third parameter. 333 | 334 |

2. Constructors

335 |

1. Default:

Makes an empty container. 336 | 337 | ```cpp 338 | multimap var_name; //Starts the var_name map with no key value pairs 339 | ``` 340 | 341 |
342 | 343 |

2. Range:

Used to copy range of elements from one map to other. 344 | 345 | ```cpp 346 | multimap var_name1; 347 | //fill 10 elements in var_name 348 | //If want to copy elements from 0-10 349 | multimap var_name2(var_name1.begin(),var_name1.end()); 350 | ``` 351 | 352 | Note: The template types should be same.
353 |

3. Copy:

354 | Copy entire container in new map object.
355 | 356 | ```cpp 357 | multimap var_name(map_object); 358 | ``` 359 | 360 | Copies the map_object in var_name. The map_object should be of same type.

361 |

3. Insert

362 |

1. Insert using insert()

363 | This method inserts an element with the key and value provided. 364 | Use this link because it is very similar to maps and unordered_maps. 365 |

4. Access

366 |

1. Access using find()

367 | Returns an iterator to an arbitrary element of possibly multiple elements having the given key.
368 | Example 369 | 370 |

2. Access using equal_range()

371 | Returns a pair of iterators. First is an iterator to the first element having the given key. Second is the iterator to the next to last element having the key.
372 | Example 373 | 374 |

5. Delete

375 |

1. erase()

376 | Deletes an element using its iterator. Same as maps and unordered_maps.
377 | Example 378 | 379 |

6: Iteration

380 | Same as maps and unordered_maps.
381 | Example 382 | 383 |

Complexities

384 |

Insert: O(log(n))

385 |

Access: O(log(n))

386 |

Delete: O(1) + Access = O(log(n))

387 | -------------------------------------------------------------------------------- /cpp/containers/queue.md: -------------------------------------------------------------------------------- 1 |
2 |

Queue

3 | 4 | 5 | > Queue is a container which follows FIFO order (First In First Out). 6 | 7 | > Elements are inserted at one end ( Rear ) and extracted from another end( Front ) 8 | 9 |
10 | 11 | ### Operations( Member functions ) 12 | 13 | |
Function
|
What it does ?
|
Complexity
| 14 | | :------------- | :------------- | :------------- | 15 | | push( ) | Inserts an element in queue at one end(rear). | O(1) 16 | | pop( ) | Deletes an element from another end if queue(front). | O(1) 17 | | front( ) | Access the element on the front end of queue. | O(1) 18 | | empty( ) | Checks if the queue is empty or not. | O(1) 19 | | size( ) | returns the size of queue. | O(1) 20 | 21 |
22 | 23 | ### Implementation 24 | 25 | ```cpp 26 | #include 27 | #include 28 | #include 29 | 30 | using namespace std; 31 | 32 | int main(){ 33 | int i ; 34 | queue q ; // declaratation 35 | for ( i = 1 ; i < 4; i++ ){ 36 | q.push(i*i); 37 | } 38 | printf("Size of queue %d \n ", q.size()); 39 | while(!q.empty()){ 40 | printf(" %d ",q.front()); 41 | q.pop(); 42 | } 43 | return 0 ; 44 | } 45 | ``` 46 | 47 | Output 48 | 49 | ``` 50 | Size of queue 3 51 | 1 4 9 52 | 53 | ``` 54 |
55 | 56 | ### Problems 57 | 58 | * codechef 59 | 60 |
61 | 62 |
63 |

Priority-Queue

64 | 65 | > A priority queue is a container that provides constant time extraction of the largest element . 66 | 67 | > In a priority queue, an element with high priority is served before an element with low priority. 68 | 69 | > All insertion / deletion operations takes place in Logarithmic time . 70 | 71 | 72 |
73 | 74 | ### Operations( Member functions ) 75 | 76 | |
Function
|
What it does ?
|
Complexity
| 77 | | :------------- | :------------- | :------------- | 78 | | push( ) | Inserts a new element in the priority queue. | O(logN) 79 | | pop( ) | Removes the largest(Top) element from the priority queue . | O(LogN) 80 | | top( ) | Returns a reference to the largest element in the priority queue. | O(1) 81 | | empty( ) | Returns true if the priority queue is empty and false if the priority queue has at least one element | O(1) 82 | | size( ) | Returns the number of element in the priority queue. | O(1) 83 | 84 |
85 | 86 | 87 | ### Implementation 88 | 89 | ```cpp 90 | #include 91 | #include 92 | 93 | using namespace std; 94 | 95 | int main() 96 | { 97 | priority_queue pq; // declaratation 98 | pq.push(10); 99 | pq.push(20); 100 | pq.push(5); 101 | while(!pq.empty()) 102 | { 103 | cout << pq.top() << endl; 104 | pq.pop(); 105 | } 106 | return 0; 107 | } 108 | ``` 109 | 110 | Output 111 | 112 | ``` 113 | 20 114 | 10 115 | 5 116 | 117 | ``` 118 |
119 | 120 | ### Problems 121 | * codechef 122 | 123 | 124 | #### Note - Follow up [deque](http://www.cplusplus.com/reference/deque/deque/) as above 125 | -------------------------------------------------------------------------------- /cpp/containers/sets.md: -------------------------------------------------------------------------------- 1 |
2 |

Sets

3 | 4 | Sets are containers which store only unique values and permit easy look ups.
5 | 6 | The values in the sets are stored in some specific order (like ascending or descending).
7 | 8 | Elements can only be inserted or deleted, but cannot be modified.
9 | 10 | We can access and traverse set elements using iterators just like vectors. 11 |
12 | 13 | > Internally implemented as binary search tree. 14 | 15 |
16 | 17 | ### Operations( Member functions ) 18 | 19 | |
Function
|
What it does ?
|
Complexity
| 20 | | :------------- | :------------- | :------------- | 21 | | begin( ) | Returns an iterator to the first element of the set. | O(1) 22 | | end( ) | Returns an iterator pointing to a position which is next to the last element | O(1) 23 | | clear( ) | Deletes all the elements in the set and the set will be empty. | O(N) 24 | | count( ) | Returns 1 or 0 if the element is in the set or not respectively. | O(logN) 25 | | empty( ) | Returns true if the set is empty and false if the set has at least one element | O(1) 26 | | erase( ) | Deletes a particular element or a range of elements from the set. | O(N) 27 | | find( ) | Searches for a particular element and returns the iterator pointing to the element if the element is found otherwise it will return the iterator returned by end(). | O(logN) 28 | | size( ) | Returns the size of the set or the number of elements in the set. | O(1) 29 | | insert( ) | insert a new element. | O(logN) 30 | 31 |
32 | 33 | 34 | ### Implementation 35 | 36 | ```cpp 37 | // declaratation 38 | 39 | set s1; // Empty Set 40 | int a[]= {1, 2, 3, 4, 5, 5}; 41 | set s2 (a, a + 6); // s2 = {1, 2, 3, 4, 5} 42 | set s4 (s3.begin(), s3.end()); // Set created using iterators 43 | ``` 44 | 45 | ```cpp 46 | #include 47 | #include 48 | #include 49 | 50 | using namespace std; 51 | 52 | int main() 53 | { 54 | set s; 55 | set ::iterator it; // iterator to traverse 56 | int A[] = {3, 5, 2, 1, 5, 4}; 57 | for(int i = 0;i < 6;++i) 58 | s.insert(A[i]); 59 | s.erase(A[3]); // erases 1 form the set 60 | printf("size of set %d\n",(int)s.size()); 61 | for(it = s.begin();it != s.end();++it) 62 | cout << *it << ' '; 63 | cout << endl; 64 | return 0; 65 | 66 | } 67 | ``` 68 | Output: 69 | ``` 70 | size of set 4 71 | 2 3 4 5 72 | ``` 73 |
74 | 75 | ### Problems 76 | 77 | * codechef 78 |
79 | 80 |
81 |

Unordered-Sets

82 | 83 | Unordered sets are containers that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value.
84 | 85 | Pros : Faster than sets (promises amortized O(1) for search).
86 | 87 | Cons : Look up not guaranteed to be O(1) Therotical worst case is O(n)
88 | 89 | 90 | ### Note : Implementation && Member functions are similar as Sets . 91 | 92 | ### Problems 93 | 94 | * codechef 95 |
96 | 97 |
98 |

Multiset

99 | 100 | Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values.
101 | 102 | Internally, the elements in a multiset are always sorted following a specific strict weak ordering criterion indicated by its internal [comparison object](http://www.cplusplus.com/reference/map/multimap/key_comp/) (of type Compare). 103 |
104 | 105 | ```cpp 106 | multiset > m ; 107 | m.insert(40); 108 | m.insert(60); 109 | m.insert(20); 110 | m.insert(60); // 60 will be added again to the multiset unlike set 111 | ``` 112 | 113 | ### Note : [Implementation](http://www.cplusplus.com/reference/set/multiset/multiset/) && Member functions are same as Sets . 114 | 115 | ### Extending This : 116 | 117 | |
Function
|
What it does ?
|
Complexity
| 118 | | :------------- | :------------- | :------------- | 119 | | rbegin() | Returns a reverse iterator pointing to the last element in the container | O(1) 120 | | rend() | Returns a reverse iterator pointing to the theoretical element right before the first element in the container | O(1) 121 | | equal_range() | The function returns a pair, whose member pair::first is the lower bound of the range (the same as lower_bound), and pair::second is the upper bound | O(logN) 122 | 123 | ### Problems 124 | 125 | * codechef 126 |
127 | -------------------------------------------------------------------------------- /cpp/containers/stacks.md: -------------------------------------------------------------------------------- 1 |

Stacks

2 | 3 |

INTRODUCTION

4 | 5 | Stacks are dynamic data structures that follow the Last In First Out (LIFO) principle. The last item to be inserted into a stack is the first one to be deleted from it.
6 | 7 | For example, you have a stack of trays on a table. The tray at the top of the stack is the first item to be moved if you require a tray from that stack.
8 | 9 | Stacks have restrictions on the insertion and deletion of elements. Elements can be inserted or deleted only from one end of the stack i.e. from the *top*. The element at the top is called the *top* element. The operations of inserting and deleting elements are called push() and pop() respectively.
10 | 11 |

CONSTRUCTION

12 | 13 | ```cpp 14 | stack name; 15 | ``` 16 | 17 |

FUNCTIONS

18 | 19 | |
Function
|
What it does ?
|
Complexity
| 20 | | :------------- | :------------- | :------------- | 21 | | empty() |Returns whether the stack is empty |O(1) 22 | | size() |Returns the size of the stack |O(1) 23 | | top() |Returns a reference to the top most element of the stack |O(1) 24 | | push(g) |Adds the element ‘g’ at the top of the stack |O(1) 25 | | pop() |Deletes the top most element of the stack |O(1) 26 | 27 |

Implementation

28 | 29 | ```cpp 30 | #include 31 | #include 32 | 33 | using namespace std; 34 | 35 | void showstack(stack kj) 36 | { 37 | stack c = kj; 38 | while (!c.empty()) 39 | { 40 | cout << '\t' << c.top(); 41 | c.pop(); 42 | } 43 | cout << '\n'; 44 | } 45 | 46 | int main () 47 | { 48 | stack KJC; 49 | KJC.push(10); 50 | KJC.push(30); 51 | KJC.push(20); 52 | KJC.push(5); 53 | KJC.push(1); 54 | 55 | cout << "The stack KJC is : "; 56 | showstack(KJC); 57 | 58 | cout << "\nKJC.size() : " << KJC.size(); 59 | cout << "\nKJC.top() : " << KJC.top(); 60 | 61 | 62 | cout << "\nKJC.pop() : "; 63 | KJC.pop(); 64 | showstack(KJC); 65 | 66 | return 0; 67 | } 68 | 69 | ``` 70 | 71 | Output 72 | 73 | ``` 74 | The stack KJC is : 1 5 20 30 10 75 | 76 | KJC.size() : 5 77 | KJC.top() : 1 78 | KJC.pop() : 5 20 30 10 79 | 80 | ``` 81 | 82 |

Problems

83 | -------------------------------------------------------------------------------- /cpp/functions/MaxMin.md: -------------------------------------------------------------------------------- 1 |

Max and Min

2 | 3 |

Max

4 | 5 |

Function

6 | Returns the largest of a and b. If both are equivalent, a is returned. 7 |

Declaration

8 | 9 | ```cpp 10 | max(variable or value 1,variable or value 2); 11 | ``` 12 | 13 |

Example

14 | 15 | ```cpp 16 | #include 17 | #include //for max 18 | using namespace std; 19 | int main () { 20 | cout << max(1,2) << endl; 21 | cout << max('s','m') << endl; 22 | cout << max(1.23,2.34) << endl; 23 | return 0; 24 | } 25 | ``` 26 | Output: 27 | ``` 28 | 2 29 | s 30 | 2.34 31 | ``` 32 | 33 |

Min

34 |

Function

35 | Returns the smallest of a and b. If both are equivalent, a is returned. 36 |

Declaration

37 | 38 | ``` 39 | min(variable or value 1,variable or value 2); 40 | ``` 41 | 42 |

Example

43 | 44 | ```C++ 45 | #include 46 | #include //for min 47 | using namespace std; 48 | int main () { 49 | cout << min(1,2) << endl; 50 | cout << min('s','m') << endl; 51 | cout << min(1.23,2.34) << endl; 52 | return 0; 53 | } 54 | ``` 55 | Output: 56 | ``` 57 | 1 58 | m 59 | 1.23 60 | ``` 61 | -------------------------------------------------------------------------------- /cpp/functions/binary_search.md: -------------------------------------------------------------------------------- 1 |

binary_search()

2 | 3 | 4 | ## Function 5 | 6 | >Returns true if any element in the range [first,last) (first is included, last isn't) is equivalent to value, and false otherwise. 7 | >**The elements in the range shall already be sorted** 8 | 9 | ## Declaration 10 | 11 | ```cpp 12 | binary_search(iterator for start of the range,iterator for end of the range which is not included in range,value to be searched); 13 | ``` 14 | 15 | ## Example 16 | 17 | ```cpp 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | int main() { 24 | int numbers[] = {1,2,3,4,5,4,3,2,1}; 25 | vector v(numbers,numbers+9); 26 | 27 | sort(v.begin(), v.end()); 28 | 29 | cout << "looking for a 3... "; 30 | if (binary_search(v.begin(), v.end(), 3)) 31 | cout << "found!"< is_sorted() 2 | 3 |

Function

4 | 5 | > Returns true if the range [first,last) is sorted into ascending order. 6 | 7 |

Declaration

8 | 9 | ```cpp 10 | is_sorted(first,last); 11 | ``` 12 | where, 13 | **first, last**: 14 | Input iterators to the initial and final positions of the first sorted sequence.The range used is [first,last), which contains all the elements between first1 and last1, including the element pointed by first but not the element pointed by last. 15 | 16 | **Return value**: 17 | 18 | >true if the range [first,last) is sorted into ascending order, false otherwise. 19 | >If the range [first,last) contains less than two elements, the function always returns true. 20 | 21 | 22 |

Example

23 | 24 | ```cpp 25 | // is_sorted example 26 | #include 27 | #include //is_sorted,prev_permutation 28 | #include // array 29 | using namespace std; 30 | int main () { 31 | array arr {2,4,1,3}; 32 | do { 33 | prev_permutation(arr.begin(),arr.end()); 34 | for (int& x:arr) std::cout <<' '<< x; 35 | cout< lower_bound() 2 | 3 | ## Function 4 | 5 | >Returns an iterator pointing to the first element in the range [first,last)(first is included, last isn't) which does not compare less than val 6 | 7 | >Basically the first element in the array which is greater than or equal to the value. 8 | 9 | ## Declaration 10 | 11 | ```cpp 12 | lower_bound(iterator for start of the range,iterator for end of the range which is not included in range,value); 13 | ``` 14 | 15 | ## Example 16 | 17 | ```cpp 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | int main() { 24 | int numbers[] = {1,2,3,4,4,4,5,6,6,6,7,8}; 25 | 26 | vector v(numbers,numbers+12); 27 | vector ::iterator it; 28 | 29 | it = lower_bound(v.begin(),v.end(),4);//first 4 in numbers 30 | 31 | cout<<"lower bound at index : "< max_element() 2 | 3 | ## Function 4 | 5 | >Returns an iterator pointing to the element with the largest value in the range [first,last) (first is included, last isn't). 6 | 7 | ## Declaration 8 | 9 | ```cpp 10 | max_element(iterator for start of the range,iterator for end of the range which is not included in range); 11 | ``` 12 | 13 | ## Example 14 | 15 | ```cpp 16 | #include 17 | #include 18 | using namespace std; 19 | 20 | int main() { 21 | int a[6] = {-1,7,3,6,9,10}; 22 | 23 | cout<<"biggest value in range of first 3 elements : "<<*max_element(a,a+3)< min_element() 2 | 3 | ## Function 4 | 5 | >Returns an iterator pointing to the element with the smallest value in the range [first,last) (first is included, last isn't). 6 | 7 | ## Declaration 8 | 9 | ```cpp 10 | min_element(iterator for start of the range,iterator for end of the range which is not included in range); 11 | ``` 12 | 13 | ## Example 14 | 15 | ```cpp 16 | #include 17 | #include 18 | using namespace std; 19 | 20 | int main() { 21 | int a[6] = {-1,7,3,6,9,10}; 22 | 23 | cout<<"smallest value in range of first 3 elements : "<<*min_element(a,a+3)< next_permutation() 2 | 3 | ## Function 4 | 5 | It rearranges the elements in the range [first,last) (first is included, last isn't) into the **_next lexicographically(dictionary order) greater permutation_**. 6 | 7 | A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according to how they compare lexicographicaly to each other; The first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order. 8 | 9 | If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to the first permutation (sorted in ascending order) and returns false. 10 | 11 | ## Declaration 12 | 13 | ```cpp 14 | next_permutation(iterator for start of the range,iterator for end of the range which is not included in range); 15 | ``` 16 | 17 | ## Example 18 | 19 | ```cpp 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | int main() { 26 | cout<<"String Example"<reverse() 2 | 3 | 4 | ## Function 5 | 6 | >Reverses the order of the elements in the range [first,last).(first is included, last isn't). 7 | 8 | >The function calls iter_swap to swap the elements to their new locations. 9 | 10 | ## Declaration 11 | 12 | ```cpp 13 | reverse(iterator for start of the range,iterator for end of the range which is not included in range); 14 | ``` 15 | 16 | ## Example 17 | 18 | ```cpp 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | int main() { 24 | int numbers[] = {1,2,3,4,5,6,7,8}; 25 | 26 | cout<<"Before Reversing:"< set_difference() 2 | 3 |

Function

4 | 5 | > Constructs a sorted range beginning in the location pointed by result with the set difference of the sorted range [first1,last1) with respect to the sorted range [first2,last2). 6 | 7 | >The difference of two sets is formed by the elements that are present in the first set, but not in the second one. The elements copied by the function come always from the first range, in the same order. 8 | 9 | >For containers supporting multiple occurrences of a value, the difference includes as many occurrences of a given value as in the first range, minus the amount of matching elements in the second, preserving order. 10 | 11 | >The elements in the ranges shall already be sorted and the resulting range is also sorted accordingly. 12 | 13 |

Declaration

14 | 15 | ```cpp 16 | it = set_difference (first1, last1, first2, last2, result); 17 | ``` 18 | where, 19 | **first1, last1**: 20 | Input iterators to the initial and final positions of the first sorted sequence.The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1. 21 | 22 | **first2, last2**: 23 | Input iterators to the initial and final positions of the second sorted sequence.The range used is [first2,last2), which contains all the elements between first2 and last2, including the element pointed by first2 but not the element pointed by last2. 24 | 25 | **result**: 26 | Output iterator to the initial position of the range where the resulting sequence is stored. 27 | 28 | **Return value**: 29 | Returns an iterator past the end of the constructed range. 30 | 31 | 32 |

Example

33 | 34 | ```cpp 35 | #include 36 | #include // set_difference, sort 37 | #include // vector 38 | using namespace std; 39 | int main () { 40 | int first[] = {5,10,15,20,25}; 41 | int second[] = {50,40,30,20,10}; 42 | vector v(10); 43 | vector::iterator it; 44 | sort (first,first+5); // 5 10 15 20 25 45 | sort (second,second+5); // 10 20 30 40 50 46 | it=set_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 0 0 0 0 0 0 0 47 | v.resize(it-v.begin()); // 5 15 25 48 | for (it=v.begin(); it!=v.end(); ++it) cout << ' ' << *it; 49 | return 0; 50 | } 51 | ``` 52 | Output: 53 | ``` 54 | 5 15 25 55 | ``` 56 | -------------------------------------------------------------------------------- /cpp/functions/set_intersection.md: -------------------------------------------------------------------------------- 1 |

set_intersection()

2 | 3 |

Function

4 | 5 | > Constructs a sorted range beginning consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). 6 | 7 | >If some element is found m times in [first1, last1) and n times in [first2, last2), the first x number of elements will be copied from the first range to the destination range where x is the minimum of m and n. 8 | 9 | >The order of equivalent elements is preserved. 10 | 11 | >The resulting range cannot overlap with either of the input ranges. 12 | 13 |

Declaration

14 | 15 | ```cpp 16 | set_intersection(first1,last1,first2,last2,result) 17 | ``` 18 | where, 19 | **first1, last1**: 20 | Input iterators to the initial and final positions of the first sorted sequence.The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1. 21 | 22 | **first2, last2**: 23 | Input iterators to the initial and final positions of the second sorted sequence.The range used is [first2,last2), which contains all the elements between first2 and last2, including the element pointed by first2 but not the element pointed by last2. 24 | 25 | **result**: 26 | Output iterator to the initial position of the range where the resulting sequence is stored. 27 | 28 | **Return value**: 29 | Returns an iterator past the end of the constructed range. 30 | 31 | 32 |

Example

33 | 34 | ```cpp 35 | #include 36 | #include 37 | #include //set_intersection, sort 38 | #include //back_inserter 39 | using namespace std; 40 | int main() 41 | { 42 | vector v1{1,2,3,4,5,6,7,8}; 43 | vector v2{5,7,9,10}; 44 | sort(v1.begin(), v1.end()); 45 | sort(v2.begin(), v2.end()); 46 | vector v_intersection; 47 | set_intersection(v1.begin(), v1.end(),v2.begin(), v2.end(),back_inserter(v_intersection)); 48 | for(int n : v_intersection) cout << n << ' '; 49 | } 50 | ``` 51 | Output: 52 | ``` 53 | 5 7 54 | ``` 55 | -------------------------------------------------------------------------------- /cpp/functions/set_union.md: -------------------------------------------------------------------------------- 1 |

set_union()

2 | 3 |

Function

4 | 5 | > Constructs a sorted range beginning in the location pointed by result with the set union of the two sorted ranges [first1,last1) and [first2,last2). 6 | 7 | >The union of two sets is formed by the elements that are present in either one of the sets, or in both. 8 | 9 | >Elements from the second range that have an equivalent element in the first range are not copied to the resulting range. 10 | 11 | >The elements in the ranges shall already be sorted and the resulting range is also sorted accordingly. 12 | 13 |

Declaration

14 | 15 | ```cpp 16 | it = set_union (first1, last1, first2, last2, result); 17 | ``` 18 | 19 | **first1, last1**: 20 | Input iterators to the initial and final positions of the first sorted sequence. 21 | The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1. 22 | 23 | **first2, last2**: 24 | Input iterators to the initial and final positions of the second sorted sequence. 25 | The range used is [first2,last2), which contains all the elements between first2 and last2, including the element pointed by first2 but not the element pointed by last2. 26 | 27 | **result**: 28 | Output iterator to the initial position of the range where the resulting sequence is stored. 29 | 30 | **Return value**: 31 | Returns an iterator (it) to the end of the constructed range. 32 | 33 | 34 |

Example

35 | 36 | ```cpp 37 | #include 38 | #include // set_union, sort 39 | #include // vector 40 | using namespace std; 41 | int main () { 42 | int first[] = {5,10,15,20,25}; 43 | int second[] = {50,40,30,20,10}; 44 | vector v(10); // 0 0 0 0 0 0 0 0 0 0 45 | vector::iterator it; 46 | sort (first,first+5); // 5 10 15 20 25 47 | sort (second,second+5); // 10 20 30 40 50 48 | it=set_union (first, first+5, second, second+5, v.begin()); // 5 10 15 20 25 30 40 50 0 0 49 | v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50 50 | for (it=v.begin(); it!=v.end(); ++it) cout << ' ' << *it; 51 | cout <sort() 2 | 3 | 4 | ## Function 5 | 6 | >Sorts the elements in the range [first,last) (first is included, last isn't) into ascending order. 7 | 8 | ## Declaration 9 | 10 | ```cpp 11 | sort(iterator for start of the range,iterator for end of the range which is not included in range); 12 | ``` 13 | 14 | ## Example 15 | 16 | ```cpp 17 | #include 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | int main() { 23 | int numbers[] = {1,2,3,12,10,7,4,-2}; 24 | 25 | cout<<"Before Sorting:"<Comparators() 54 | 55 | 56 | ## About 57 | 58 | >Actually the sort() function has three parameters that can be passed into it. The third parameter defines the ordering in which the elements should be sorted. This third parameter is actually a boolean function called Comparator which is used to sort the elements in any other way than the tradional sorting(Elements in Ascending order). It is not mandatory to have a third parameter in sort to have custom sorting . There are (at least) three ways to define an ordering in C++. 59 | 60 | 61 | ### Define operator < ( ) 62 | 63 | >This method can be used if you want objects of a custom class to be able to be sorted naturally. By naturally I mean it is default way to sort objects of this class. For example, you have a class Edge defined like this. 64 | 65 | ```cpp 66 | struct Edge 67 | { 68 | int from, to, weight; 69 | }; 70 | ``` 71 | Assume you want to sort edges of your graph in decreasing order of their weight. So , what you can do here is overwrite the functioning of default comparision that is stored in operator<(). 72 | 73 | ```cpp 74 | struct Edge 75 | { 76 | int from, to, weight; 77 | bool operator<(Edge other) const 78 | { 79 | return weight > other.weight; 80 | } 81 | }; 82 | ``` 83 | More specifically, you define a function with prototype: 84 | 85 | bool operator<(T other) const 86 | that returns true if *this (the current object) must precede other, and false otherwise. Note that the const keyword is required; it means that you cannot modify member variables of the current object. 87 | 88 | If you don’t like this syntax, i.e., a single parameter when you actually are comparing two objects, you can use this alternative syntax instead. 89 | 90 | ```cpp 91 | struct Edge 92 | { 93 | int from, to, weight; 94 | friend bool operator<(Edge a, Edge b) 95 | { 96 | return a.weight > b.weight; 97 | } 98 | }; 99 | ``` 100 | This way it is much clearer that you are comparing a and b, not *this and other. Note also that friend function is like static function; it cannot access member variables. 101 | 102 | An example of classes that implement the natural ordering is STL’s pair. Two objects of type pair will be compared according to their first keys, or if they are equal, compared according to their second keys. 103 | 104 | All built-in types also implements natural ordering (implemented by the compiler). For example, an int a comes before an int b if a is less than b. 105 | 106 | >A class that has natural ordering defined can be used directly in STL functions: 107 | 108 | ```cpp 109 | vector v; 110 | sort(v.begin(), v.end()); 111 | We can also use this class as an underlying type of STL containers: 112 | 113 | priority_queue pq; 114 | set s; 115 | ``` 116 | 117 | ### Define a custom comparison function 118 | >Use this method if you are comparing built-in types, you cannot modify the class you are comparing, or you want to define another ordering besides its natural ordering. 119 | 120 | >Basically, a comparison function is just a function that takes two parameter of the same type and returns a boolean: 121 | 122 | ```cpp 123 | bool name(T a, T b) 124 | ``` 125 | >For example, you want to sort a vector data in ascending order of their occurrences in a text. The number of occurrences of a number is available in vector occurrences. Define a function, say, with name cmp: 126 | 127 | ```cpp 128 | bool cmp(int a, int b) 129 | { 130 | return occurrences[a] < occurrences[b]; 131 | } 132 | ``` 133 | Now you can sort data by specifying the comparison function to use as the additional argument: 134 | 135 | ```cpp 136 | sort(data.begin(), data.end(), cmp); 137 | ``` 138 | 139 | ### Define operator()() 140 | 141 | A functor, or a function object, is an object that can behave like a function. This is done by defining operator()() of the class. In this case, implement operator()() as a comparison function: 142 | 143 | ```cpp 144 | vector occurrences; 145 | struct cmp 146 | { 147 | bool operator()(int a, int b) 148 | { 149 | return occurrences[a] < occurrences[b]; 150 | } 151 | }; 152 | ``` 153 | Now, you pass this class as a template argument to STL containers. The details vary between containers, consult STL reference this. 154 | 155 | ```cpp 156 | set s; 157 | priority_queue, cmp> pq; 158 | ``` 159 | 160 | STL also has some built-in functor classes such as *less*, the default comparison class, and *greater*, the negation of less. 161 | 162 | A functor can be used as an ordinary function by instantiating the class. For this purpose, the simplest way is to append () after the class name. So, for example, if you want to sort a vector data in descending order (that’s the negation of ascending order), you may use: 163 | 164 | ```cpp 165 | sort(data.begin(), data.end(), greater()); 166 | ``` 167 | 168 | ### Bonus Tips 169 | >If your class structure is large, then it is better that the parameters in your comparison function use const keyword and reference operator &. Example: 170 | ```cpp 171 | bool cmp(const Edge& a, const Edge& b) 172 | ``` 173 | >The advantage is that it ensures that you are unable to modify the contents of a and b, and they are passed as reference only, not the whole objects. 174 | -------------------------------------------------------------------------------- /cpp/functions/upper_bound.md: -------------------------------------------------------------------------------- 1 |

upper_bound()

2 | 3 | 4 | ## Function 5 | 6 | >Returns an iterator pointing to the first element in the range [first,last)(first is included, last isn't) which compares greater than val. 7 | 8 | 9 | >Basically the first element in the array which is greater than the value. 10 | 11 | ## Declaration 12 | 13 | ```cpp 14 | upper_bound(iterator for start of the range,iterator for end of the range which is not included in range,value); 15 | ``` 16 | 17 | ## Example 18 | 19 | ```cpp 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | int main() { 26 | int numbers[] = {1,2,3,4,4,4,5,6,6,6,7,8}; 27 | 28 | vector v(numbers,numbers+12); 29 | vector ::iterator it; 30 | 31 | it = upper_bound(v.begin(),v.end(),5);//first 6 in numbers 32 | 33 | cout<<"upper bound at index : "<Introduction 2 | 3 | # Switching from Turbo to Gcc 4 | 5 | Many institutions introduce programming to students by making them use Turbo compiler. 6 | While the interface of Turbo compiler might give you (a beginner) an amazing feeling that you are writing a code, that's all it does. Turbo C++ uses a very old compiler which is outdated and is not in compliance with the latest standards, while the latest compilers are 32-bit or 64-bit and comply to the standards. If you haven't already, it's the right time to switch from TurboC++ to the worldwide used standard compiler like gcc/g++ or mingw-g++/mingw-gcc. 7 | We will cut to the chase by stating most important and valuable features of GCC: 8 | - The GNU Compiler Collection is an open source (GPL) compiler. It's found on a wide variety of systems, ranging from GNU/Linux to every flavor of Unix, to Windows. 9 | - GCC contains support for many languages (C, C++, Fortran, to name but a few). It's highly portable, and widely used, and tends to produce good code. It can also be used as a cross-compiler (compiling for a system other than the one running GCC). 10 | - It's the default compiler choice for most Unix-type systems because most vendors don't bother to write their own compilers anymore - GCC is just too good for general use. 11 | - Under Windows, Microsoft's own dev tools are often preferred because they get support for new technologies quicker. 12 | - In high-performance programming environments (and some embedded environments) you may want a compiler that's more highly tuned to the chip/system in question. 13 | 14 | 15 | # Turbo V/s Gcc 16 | 17 | - The main difference between turbo and GCC compilers is that turbo has not received an update since 2000. So it’s quite out dated. 18 | - In GCC, there are header files such as cstdio which can be used to incorporate the functions of c in c++. 19 | - GCC has namespace std. Namespace is a block which defines the scope of the function which it contains. Std stands for standard i.e. it contains all the standard functions such as cout and cin. Using namespace will eliminate the confusion as to which version of the functions having the same name must be used in the program. 20 | - GCC eliminates the use of .h extension in header files. 21 | 22 | While gcc is extensively used in Linux, mingw-gcc is the Windows version of gcc. Although it's best to code in Linux, but if you're more comfortable with Windows, it is recommended that you use replit. Repl.it is an online compiler (available at https://repl.it/), which supports many languages include c,c++,java,python etc. 23 | 24 | # Installation and Use 25 | Gcc is preinstalled in any unix based system. To invoke gcc to compile C++ files, “g++” command is used. 26 | In Windows 10, one can enable the ubuntu unix terminal by enabling the developer mode in settings. 27 | Say you have a file helloworld.cpp as follows : 28 | ```cpp 29 | #include 30 | #include 31 | using namespace std; 32 | int main () 33 | { 34 | cout<<"Hello World"< ` instead of #include Not accepted. Same goes for iomanip.h. You include iomanip instead. And header files which were originally a 66 | part of C language (like math.h, string.h, stdio.h, time.h, stdlib.h, ctype.h, etc.) must have 'c' as a prefix to them (and shouldn't be having .h at the end). You include them like: 67 | 68 | ```cpp 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | ``` 76 | 77 | - Either you prefix std:: with all cout and cin statements and few other places, or we'd advice you to add the following line outside the main function: using namespace std; 78 | - Do not use void main(), and only int main(), and always return 0 at the end of the main() function. 79 | -------------------------------------------------------------------------------- /cpp/problems/chefcode.cpp: -------------------------------------------------------------------------------- 1 | //Only-backtracking solution 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #define llu long long 16 | #define inf 0x3f3f3f3f 17 | #define pb push_back 18 | #define mp make_pair 19 | #define ipair pair 20 | #define inp(a) scanf("%lld",&a) 21 | #define out(a) printf("%lld\n",a) 22 | #define N 100000 23 | #define m(a,b) (a>b? b : a) 24 | #define M(a,b) (a>b? a : b) 25 | #define mod 1000000007 26 | using namespace std; 27 | llu c=0; 28 | void subselect(llu a[],llu n,llu k,llu s,double prod) 29 | { 30 | double tk=(double)k; 31 | double e,te; 32 | if(s==n-1 && prod<=tk) 33 | { 34 | //cout< 67 | #include 68 | #include 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #define llu long long 79 | #define inf 0x3f3f3f3f 80 | #define pb push_back 81 | #define mp make_pair 82 | #define ipair pair 83 | #define inp(a) scanf("%lld",&a) 84 | #define out(a) printf("%lld\n",a) 85 | #define N 100000000 86 | #define m(a,b) (a>b? b : a) 87 | #define M(a,b) (a>b? a : b) 88 | #define mod 1000000007 89 | using namespace std; 90 | llu c=0; 91 | vector x,y; 92 | vector::iterator p; 93 | void subselect(llu a[],llu n,double k,llu s,double prod,string st) 94 | { 95 | double e,te; 96 | if(s==n-1 && prod<=k) 97 | { 98 | //cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | #define uii long long int 14 | #define it(a) ::iterator a 15 | #define sd(a) double a;scanf("%lf",&a); 16 | #define slld(a) uii a;scanf("%lld",&a) 17 | #define ss(a) scanf("%s",a) 18 | #define plld(a) printf("%lld",a) 19 | #define INF LLONG_MAX 20 | #define MOD 1000000007 21 | #define powOf2(a) !(a&a-1) 22 | #define mod(a) (a>0 ? a : (-1*a)) 23 | #define tc(a) uii a; for(scanf("%lld",&a);a--;) 24 | #define swap(a,b) a = a^b; b = a^b;a = a^b; 25 | #define rep(i,n) for(uii i = 0;i > V[D+1]; 36 | uii count = 0; 37 | for(uii i = 0;i > ::iterator it; 43 | priority_queue< pair > pq; 44 | for(uii i = 1;i<=D;i++) 45 | { 46 | for(it = V[i].begin();it!=V[i].end();it++){ 47 | pq.push((*it)); 48 | } 49 | if(pq.empty()) continue; 50 | pair a = pq.top(); 51 | pq.pop(); 52 | //cout<<"ha"< 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #define llu long long 15 | #define inf 0x3f3f3f3f 16 | #define N 100000 17 | #define m(a,b) (a>b? b : a) 18 | #define M(a,b) (a>b? a : b) 19 | #define mod 1000000007 20 | using namespace std; 21 | vector> v; 22 | vector>::iterator it; 23 | llu a[1001]; 24 | llu co[N+1]; 25 | bool flag[N+1]; 26 | bool comp(pair b,pair d) 27 | { 28 | if(co[b.first]!=co[d.first]) 29 | return co[b.first]>co[d.first]; 30 | else 31 | return b.second>n>>m; 38 | fill_n(co,N+1,0); 39 | fill_n(flag,N+1,false); 40 | for(i=0;i>a[i]; 43 | co[a[i]]++; 44 | } 45 | c=0; 46 | pair p; 47 | for(i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int T; 9 | scanf("%d", &T); 10 | 11 | while (T--) { 12 | int N, M; 13 | scanf("%d %d", &N, &M); 14 | 15 | map m; 16 | 17 | long long c; 18 | for (int i = 0; i < N; i++) { 19 | scanf("%lld", &c); 20 | m[c] = 1; 21 | } 22 | 23 | for (int i = 0; i < M; i++) { 24 | scanf("%lld", &c); 25 | if (m[c]) printf("YES\n"); 26 | else { 27 | m[c] = 1; 28 | printf("NO\n"); 29 | } 30 | } 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /cpp/problems/snakeeat.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #define llu long long 14 | #define inf 0x3f3f3f3f 15 | #define pb push_back 16 | #define mp make_pair 17 | #define ipair pair 18 | #define inp(a) scanf("%lld",&a) 19 | #define out(a) printf("%lld\n",a) 20 | #define allv(a) a.begin(),a.end() 21 | #define alla(a) a,a+n 22 | #define N 100000 23 | #define fi(i,a,b) for(llu i=a;ib? b : a) 25 | #define M(a,b) (a>b? a : b) 26 | #define mod 1000000007 27 | using namespace std; 28 | 29 | int main() 30 | { 31 | llu i,j,k,l,e,n,m,t,f,c; 32 | inp(t); 33 | while(t--) 34 | { 35 | inp(n);inp(m); 36 | llu a[n],sum[n+1]; 37 | fi(i,0,n) 38 | inp(a[i]); 39 | sort(alla(a)); 40 | sum[0]=0; 41 | fi(i,1,n+1) 42 | sum[i]=sum[i-1]+a[i-1]; 43 | fi(i,0,m) 44 | { 45 | inp(k); 46 | llu in=(lower_bound(alla(a),k)-a); 47 | l=0; 48 | llu r=in; 49 | while(lTemplates 2 | 3 | # What are templates? 4 | Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. 5 | # Generic Functions 6 | Many times while programming, there is a need for creating functions which perform the same operations but work with different data types. So C++ provides a feature to create a single generic function instead of many functions which can work with different data type by using the template parameter. 7 | # Template Parameters 8 | The way we use normal parameters to pass as a value to function, in the same manner template parameters can be used to pass type as argument to function. Basically, it tells what type of data is being passed to the function. 9 | 10 | The syntax for creating a generic function: 11 | ```cpp 12 | template return-type function-name (parameter-list) 13 | ``` 14 | Here, ‘type’ is just a placeholder used to store the data type when this function is used you can use any other name instead. Class is used to specify the generic type of template, alternatively typename can be used instead of it. Let’s try to understand it with an example: 15 | 16 | Assume we have to swap two variables of int type and two of float type. Then, we will have to make two functions where one can swap int type variables and the other one can swap float type variables. But if we use a generic function here, then we can simply make one function and can swap both type of variables by passing their different type in the arguments. Let’s implement this: 17 | 18 | ```cpp 19 | #include 20 | using namespace std ; 21 | // creating a generic function ‘swap (parameter-list)’ using template : 22 | template 23 | void swap( X &a, X &b) { 24 | X tp; 25 | tp = a; 26 | a = b; 27 | b = tp; 28 | cout << " Swapped elements values of a and b are " << a << " and " << b << " respectively " << endl; 29 | } 30 | 31 | int main( ) { 32 | int a = 10, b = 20 ; 33 | float c = 10.5, d = 20.5 ; 34 | swap(a , b); // function swapping ‘int’ elements 35 | swap(c , d); // function swapping ‘float’ elements 36 | return 0; 37 | } 38 | ``` 39 | 40 | **Output :** 41 | ``` 42 | Swapped elements values of a and b are 20 and 10 respectively. 43 | Swapped elements values of a and b are 20.5 and 10.5 respectively. 44 | ``` 45 | After creating the generic function, compiler will automatically generate correct code for the type of data used while executing the function. 46 | -------------------------------------------------------------------------------- /problems.md: -------------------------------------------------------------------------------- 1 | # Problems 2 | 3 | 4 | 1. [KRYP6]( https://www.codechef.com/problems/KRYP6 ) [ Java / Cpp ] | [ FLTRCK ](https://www.codechef.com/problems/FLTRCK)[ Python ] 5 | 2. [CVOTE](https://www.codechef.com/problems/CVOTE) 6 | 3. [CLCO01](https://www.codechef.com/problems/CLCO01) 7 | -------------------------------------------------------------------------------- /python/Readme.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Python STL

4 | 5 |
6 | 7 | ### Index 8 | 1. Containers 9 | 1. [Lists](./containers/lists.md) 10 | 2. [Sets](./containers/sets.md) 11 | 3. [Dictionary](./containers/dictionary.md) 12 | 4. [Heapq](./containers/heapq.md) 13 | 2. Methods 14 | 1. [Bisect](./methods/bisect.md) 15 | 2. [Itertools](./methods/itertools.md) 16 | 1. accumulate 17 | 2. count 18 | 3. permutations 19 | 4. combinations 20 | 5. combinations with replacement 21 | 3. [Counters](./methods/Counters.md) 22 | 4. [Miscellaneous]() 23 | 1. GCD 24 | 3. [Miscellaneous]() -------------------------------------------------------------------------------- /python/containers/dictionary.md: -------------------------------------------------------------------------------- 1 | # Dictionary 2 | Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. It is implemented as a **hash table** and hence most operations such as insertion, deletion and query take O(1) time. 3 | 4 | ### clear() 5 | The syntax of clear() is `dict.clear()` 6 | The clear() method removes all items from the dictionary. It doesnt take any parameters and doesnt return any value( returns `None`). 7 | 8 | Example: 9 | ```python 10 | d = {1: "one", 2: "two"} 11 | d.clear() 12 | print('d =', d) 13 | ``` 14 | 15 | Output: 16 | ```python 17 | d = {} 18 | ``` 19 | 20 | Elements can also be removed by assigning empty dictionary `{}` . 21 | However, there is a difference between the two if there is a variable referencing the dictionary. 22 | 23 | Example: 24 | ```python 25 | d = {1: "one", 2: "two"} 26 | d1 = d 27 | d.clear() 28 | print('Removing items using clear()') 29 | print('d =', d) 30 | print('d1 =', d1) 31 | d = {1: "one", 2: "two"} 32 | d1 = d 33 | d = {} 34 | print('Removing items by assigning {}') 35 | print('d =', d) 36 | print('d1 =', d1) 37 | ``` 38 | Output: 39 | ```python 40 | Removing items using clear() 41 | d = {} 42 | d1 = {} 43 | Removing items by assigning {} 44 | d = {} 45 | d1 = {1: 'one', 2: 'two'} 46 | ``` 47 | 48 | 49 | 50 | 51 | ### copy() 52 | The syntax of copy() is `dict.copy()` 53 | They copy() method returns a shallow copy of the dictionary. It doesn't modify the original dictionary. Complexity: O(n) 54 | 55 | Example: 56 | ```python 57 | original = {1:'one', 2:'two'} 58 | new = original.copy() 59 | print('Orignal: ', original) 60 | print('New: ', new) 61 | ``` 62 | 63 | Output: 64 | ```python 65 | Orignal: {1: 'one', 2: 'two'} 66 | New: {1: 'one', 2: 'two'} 67 | ``` 68 | 69 | ### fromkeys() 70 | The syntax of fromkeys() method is: 71 | `dictionary.fromkeys(sequence[, value])` 72 | The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user. 73 | The fromkeys() method takes two parameters: 74 | - sequence - sequence of elements which is to be used as keys for the new dictionary. 75 | - value (Optional) - value which is set to each each element of the dictionary. 76 | 77 | The fromkeys() method returns a new dictionary with the given sequence of elements as the keys of the dictionary. 78 | If the value argument is set, each element of the newly created dictionary is set to the provided value. 79 | 80 | Example: 81 | ```python 82 | keys = {'a', 'e', 'i', 'o', 'u' } 83 | value = 'vowel' 84 | vowels = dict.fromkeys(keys, value) 85 | print(vowels) 86 | ``` 87 | Output: 88 | ```python 89 | {'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e': 'vowel', 'i': 'vowel'} 90 | ``` 91 | 92 | 93 | 94 | ### get() 95 | The syntax of get() is: 96 | `dict.get(key[, value])` 97 | The get() method returns the value for the specified key if key is in dictionary. 98 | The get() method takes maximum of two parameters: 99 | - key - key to be searched in the dictionary. 100 | - value (optional) - Value to be returned if the `key` is not found. The default value is `None`. 101 | 102 | The get() method returns: 103 | the value for the specified key if key is in dictionary. 104 | - `None` if the `key` is not found and value is not specified. 105 | - `value` if the `key` is not found and value is specified. 106 | 107 | Example: 108 | ```python 109 | person = {'name': 'Barney', 'age': 21} 110 | print('Name: ', person.get('name')) 111 | print('Age: ', person.get('age')) 112 | print('Salary: ', person.get('salary')) 113 | print('Salary: ', person.get('salary', 0.0)) 114 | ``` 115 | Output: 116 | ```python 117 | Name: Barney 118 | Age: 21 119 | Salary: None 120 | Salary: 0.0 121 | ``` 122 | 123 | 124 | ### items() 125 | The syntax of items() method is: 126 | `dictionary.items()` 127 | The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs. 128 | 129 | Example: 130 | ```python 131 | abc = { 'One': 1, 'Two': 2, 'Three': 3 } 132 | print(abc.items()) 133 | ``` 134 | Output: 135 | ```python 136 | dict_items([('One', 1), ('Two', 2), ('Three', 3)]) 137 | ``` 138 | 139 | 140 | 141 | ### keys() 142 | The syntax of keys() is: 143 | `dict.keys()` 144 | The keys() method returns a view object that displays a list of all the keys in the dictionary. When the dictionary is changed, the view object also reflect these changes. 145 | 146 | Example: 147 | ```python 148 | person = {'name': 'Abc', 'age': 21, 'salary': 1200.0} 149 | print(person.keys()) 150 | empty_dict = {} 151 | print(empty_dict.keys()) 152 | ``` 153 | Output: 154 | ```python 155 | dict_keys(['name', 'age', 'salary']) 156 | dict_keys([]) 157 | ``` 158 | 159 | ### pop() 160 | The syntax of pop() method is 161 | `dictionary.pop(key[, default])` 162 | The pop() method removes and returns an element from a dictionary having the given key. 163 | The pop() method takes two parameters: 164 | - key - key which is to be searched for removal 165 | - default - value which is to be returned when the key is not in the dictionary 166 | 167 | The pop() method returns: 168 | - If key is found - removed/popped element from the dictionary 169 | - If key is not found - value specified as the second argument (default) 170 | - If key is not found and default argument is not specified - KeyError exception is raised 171 | 172 | Example: 173 | ```python 174 | sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } 175 | element = sales.pop('apple') 176 | print('The popped element is:', element) 177 | print('The dictionary is:', sales) 178 | ``` 179 | Output: 180 | ```python 181 | The popped element is: 2 182 | The dictionary is: {'orange': 3, 'grapes': 4} 183 | ``` 184 | 185 | 186 | ### popitem() 187 | The syntax of popitem() is: 188 | `dict.popitem()` 189 | The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary. 190 | The popitem() 191 | - returns an arbitrary element (key, value) pair from the dictionary. 192 | - removes an arbitrary element (the same element which is returned) from the dictionary. 193 | 194 | Example: 195 | ```python 196 | person = {'name': 'Abc', 'age': 21, 'salary': 1200.0} 197 | result = person.popitem() 198 | print('person = ',person) 199 | print('Return Value = ',result) 200 | ``` 201 | Output: 202 | ```python 203 | person = {'name': 'Abc', 'salary': 1200.0} 204 | result = ('age', 21) 205 | ``` 206 | 207 | The popitem() raises a `KeyError` error if the dictionary is empty. 208 | 209 | ### setdefault() 210 | The syntax of setdefault() is: 211 | `dict.setdefault(key[, default_value])` 212 | The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary. 213 | The setdefault() takes maximum of two parameters: 214 | - key - key to be searched in the dictionary 215 | - default_value (optional) - `key` with a value `default_value` is inserted to the dictionary if key is not in the dictionary. If not provided, the `default_value` will be `None`. 216 | 217 | The setdefault() returns: 218 | - value of the `key` if it is in the dictionary. 219 | - None if key is not in the dictionary and default_value is not specified. 220 | - `default_value` if `key` is not in the dictionary and `default_value` is specified. 221 | 222 | 223 | Example: 224 | ```python 225 | person = {'name': 'Abc', 'age': 21} 226 | age = person.setdefault('age') 227 | print('person = ',person) 228 | print('Age = ',age) 229 | ``` 230 | Output: 231 | ```python 232 | person = {'name': 'Abc', 'age': 21} 233 | Age = 21 234 | ``` 235 | 236 | ### update() 237 | The syntax of update() is: 238 | `dict.update([other])` 239 | The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. It adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value. 240 | The update() method takes either a dictionary or an iterable object of key/value pairs (generally tuples). 241 | If update() is called without passing parameters, the dictionary remains unchanged. 242 | 243 | Example: 244 | ```python 245 | d = {1: "one", 2: "three"} 246 | d1 = {2: "two"} 247 | 248 | d.update(d1) 249 | print(d) 250 | d1 = {3: "three"} 251 | 252 | d.update(d1) 253 | print(d) 254 | ``` 255 | 256 | Output: 257 | ```{1: 'one', 2: 'two'} 258 | {1: 'one', 2: 'two', 3: 'three'} 259 | ``` 260 | 261 | ### values() 262 | The syntax of values() is: 263 | `dictionary.values()` 264 | The values() method returns a view object that displays a list of all the values in the dictionary. 265 | 266 | Example: 267 | ```python 268 | sales = { 'apple': 2, 'orange': 3, 'grapes': 4 } 269 | print(sales.values()) 270 | ``` 271 | Output: 272 | ```python 273 | dict_values([2, 4, 3]) 274 | ``` 275 | 276 | ### all() 277 | The syntax of all() method is: 278 | `all(iterable)` 279 | The all() method takes a single parameter: 280 | - iterable - any iterable (list, tuple, dictionary, etc.) which contains the elements. 281 | 282 | If all keys (not values) are true or the dictionary is empty, all() returns True. Else, it returns false for all other cases. 283 | 284 | Example: 285 | ```python 286 | s = {0: 'False', 1: 'False'} 287 | print(all(s)) 288 | s = {1: 'True', 2: 'True'} 289 | print(all(s)) 290 | s = {1: 'True', False: 0} 291 | print(all(s)) 292 | s = {} 293 | print(all(s)) 294 | 295 | s = {'0': 'True'} 296 | print(all(s)) 297 | ``` 298 | Output: 299 | ``` 300 | False 301 | True 302 | False 303 | True 304 | True 305 | ``` 306 | 307 | 308 | ### any() 309 | The syntax of any() is: 310 | `any(iterable)` 311 | If all keys (not values) are false, any() returns `False`. If at least one key is true, any() returns `True`. 312 | 313 | Example: 314 | ```python 315 | d = {0: 'False'} 316 | print(any(d)) 317 | d = {0: 'False', 1: 'True'} 318 | print(any(d)) 319 | d = {0: 'False', False: 0} 320 | print(any(d)) 321 | d = {} 322 | print(any(d)) 323 | 324 | d = {'0': 'False'} 325 | print(any(d)) 326 | ``` 327 | Output: 328 | ``` 329 | False 330 | True 331 | False 332 | False 333 | True 334 | ``` 335 | 336 | ### len() 337 | The syntax of len() is: 338 | `len(s)` 339 | The len() function returns the number of items (length) of an object. 340 | Failing to pass an argument or passing an invalid argument will raise a `TypeError` exception. 341 | 342 | Example: 343 | ```python 344 | dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} 345 | print ("Length : %d" % len (dict)) 346 | ``` 347 | Output: 348 | ```python 349 | Length : 3 350 | ``` 351 | 352 | ### sorted() 353 | The syntax of sorted() method is: 354 | `sorted(iterable[, key][, reverse])` 355 | sorted() takes two three parameters: 356 | - iterable - collection (dictionary) or any iterator 357 | - reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order) 358 | - key (Optional) - function that serves as a key for the sort comparison 359 | 360 | sorted() method returns a sorted list from the given iterable. 361 | 362 | Example: 363 | ```python 364 | pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5} 365 | print(sorted(pyDict, reverse=True)) 366 | ``` 367 | Output: 368 | ```python 369 | ['u', 'o', 'i', 'e', 'a'] 370 | ``` 371 | 372 | 373 | ### cmp() 374 | The syntax of cmp() method is: 375 | `cmp(dict1, dict2)` 376 | The method cmp() compares two dictionaries based on key and values. This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1 if dict1 > dict2. 377 | Example: 378 | ```python 379 | dict1 = {'Name': 'Zen', 'Age': 7}; 380 | dict2 = {'Name': 'Mac', 'Age': 27}; 381 | print "Return Value : %d" % cmp (dict1, dict2) 382 | ``` 383 | Output: 384 | ```python 385 | Return Value : -1 386 | ``` 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | -------------------------------------------------------------------------------- /python/containers/heapq.md: -------------------------------------------------------------------------------- 1 |

heapq

2 | 3 | ## What are Heaps? 4 | > Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which **heap[k] <= heap[2*k+1]** and **heap[k] <= heap[2*k+2]** 5 | for all k, counting elements from zero. 6 | 7 | > The interesting property of a heap is that its smallest element is always the **root, heap[0]**. 8 | 9 | > The heap discussed above is also called **min-heap**.There is another variation called as **max-heap** where each parent node has a value greater than or equal to any of its children. 10 | 11 |
12 | 13 | ## Functions : 14 | 15 | |
Function
|
What it Does?
|
Complexity
| 16 | |----|:---|:---| 17 | | **heapify(x)** | Transform list x into a heap, in-place | O(N) | 18 | | **heappush(heap, item)** | Push the value item onto the heap | O(LogN) | 19 | | **heappop(heap)** | Pop and return the smallest item from the heap | O(LogN) | 20 | | **heappushpop(heap, item)** | Push item on the heap, then pop and return the smallest item from the heap | O(LogN) | 21 | | **heapreplace(heap, item)** | Pop and return the smallest item from the heap, and also push the new item | O(LogN) | 22 | | **nlargest(n, iterable, key=None)** | Return a list with the n largest elements from the dataset defined by iterable. key | O(N*Logn) | 23 | | **nsmallest(n, iterable, key=None)** | Return a list with the n smallest elements from the dataset defined by iterable. key | O(N*Logn) | 24 | 25 | > **Note** : All the functions maintain the heap invariant. 26 | 27 | 28 | 29 | ## Implementation : 30 | 31 | ```python 32 | from heapq import * 33 | 34 | x = [2,5,11,10,1,3,25] 35 | print("List\n",x) 36 | 37 | heapify(x) 38 | print("Heap\n",x) 39 | 40 | heappush(x,4) 41 | print("Push(4)\n",x) 42 | 43 | val=heappop(x) 44 | print("Pop\n",val,x) 45 | 46 | val=heappushpop(x,7) 47 | print("PushPop(7)\n",val,x) 48 | 49 | val=heapreplace(x,8) 50 | print("Replace(8)\n",val,x) 51 | 52 | print("4 Smallest elements\n",nsmallest(4,x,key=None)) 53 | 54 | print("4 Largest elements\n",nlargest(4,x,key=None)) 55 | ``` 56 | ### Output : 57 | ``` 58 | List 59 | [2, 5, 11, 10, 1, 3, 25] 60 | Heap 61 | [1, 2, 3, 10, 5, 11, 25] 62 | Push(4) 63 | [1, 2, 3, 4, 5, 11, 25, 10] 64 | Pop 65 | 1 [2, 4, 3, 10, 5, 11, 25] 66 | PushPop(7) 67 | 2 [3, 4, 7, 10, 5, 11, 25] 68 | Replace(8) 69 | 3 [4, 5, 7, 10, 8, 11, 25] 70 | 4 Smallest elements 71 | [4, 5, 7, 8] 72 | 4 Largest elements 73 | [25, 11, 10, 8] 74 | ``` 75 | ### Heap Sort : 76 | > A heapsort can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time. 77 | 78 | ```python 79 | def heapsort(arr): 80 | h = [] 81 | for value in arr: 82 | heappush(h, value) 83 | return [heappop(h) for i in range(len(h))] 84 | heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) 85 | ``` 86 | Output: 87 | ``` 88 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 89 | ``` 90 | -------------------------------------------------------------------------------- /python/containers/lists.md: -------------------------------------------------------------------------------- 1 |

Lists

2 | 3 | ## Introduction 4 | 5 | - A list is an ordered collection of zero or more references to Python data objects. Lists are written as comma-delimited values enclosed in square brackets. Lists are heterogeneous, meaning that the data objects need not all be from the same class and the collection can be assigned to a variable. Lists are enclosed in [ ]. 6 | 7 | ## Operations : 8 | 9 | |
Operation Name
|
Explanation
|
Operator
| 10 | |----|:---|:---| 11 | | **indexing** | Access an element |
[]
| 12 | | **concatenation** |combine sequences|
+
| 13 | | **repetition** | Concatenate a repeated number of times |
*
| 14 | | **membership** | to check if a given item is in the sequence |
in
| 15 | | **length** |gives number of elements in sequence|
len
| 16 | 17 | 18 | ## Methods: 19 | 20 | |
Method name
|
Explanation
|
Use
|
Complexity
| 21 | |----|:---|:---|:---| 22 | | **append** | Adds a new item to the end of the list | list.append(item) | O(1) | 23 | | **insert** |Inserts element at ith position in list | list.insert(i, item) | O(n) | 24 | | **pop** | Pop and return the last item from the list | list.pop() | O(1) | 25 | | **sort** | Modifies a list to be sorted | list.sort() | O(nlogn) | 26 | | **reverse** | Modifies a list to be in reverse order | list.reverse() | O(n) | 27 | | **del** |Deletes element in ith position | del l[i] | O(n) | 28 | | **index**|Returns index of first occurrence of item | list.index(item) | O(n) | 29 | | **count** |Returns number of occurrences of item | list.count(item) | O(n) | 30 | | **remove** |Deletes first occurrence of item | list.remove(item) | O(n) | 31 | | **extend** |Adds second list to end of first list | l1.extend(l2) | O(len(l2)) | 32 | 33 | ## Slicing Lists 34 | 35 | #### **Examples** 36 | ```python 37 | l=[1,2,3,4] 38 | l[0] 39 | l[0:1] 40 | l[-1] 41 | l[:-2] 42 | l[::-1] 43 | l[1::-1] 44 | ``` 45 | #### Output: 46 | 47 | ```Python 48 | 1 49 | [1] 50 | 4 51 | [1,2] 52 | [4,3,2,1] 53 | [2,1] 54 | ``` 55 | **x == y checks if x and y have the _same value_ while 56 | x `is` y checks if x and y refer to the same object (_point to the same memory location_)** 57 | 58 | Thus, if 59 | ```Python 60 | l1 = [1,2,4] 61 | l2=l1 62 | l2[0]=5 63 | print(l1) 64 | ``` 65 | Output: 66 | ``` 67 | [5, 2, 3] 68 | ``` 69 | Changing the elements of l2 will cause change in l1 too. 70 | 71 | Thus if we want a new list that has the same elements of another, we have to perform 72 | >l2 = l1[:] 73 | 74 | this creates a copy of l1 75 | 76 | ## Examples: 77 | ## append() 78 | ```python 79 | l = [1, 2] 80 | l.append(3) 81 | print(l) 82 | ``` 83 | Output: 84 | ``` 85 | [1,2,3] 86 | ``` 87 | ## extend() 88 | ```python 89 | l1=[1,2] 90 | l2=[3,4] 91 | l1.extend(l2) 92 | print(l1) 93 | ``` 94 | Output: 95 | ``` 96 | [1,2,3,4] 97 | ``` 98 | ## concatenation 99 | ```python 100 | l1=[1,2,3,4] 101 | l2=[5,6,7,8] 102 | l3 = l1+l2 103 | print(l3) 104 | ``` 105 | Output: 106 | ``` 107 | [1,2,3,4,5,6,7,8] 108 | ``` 109 | 110 | Concatenantion always produces a new list so if 111 | ```python 112 | l1=[1,2,3] 113 | l2=l1 114 | l1=l1+[4] 115 | ``` 116 | l1 will no longer point to the same list (l1 is l2 returns false) 117 | 118 | ## insert() 119 | ```python 120 | l=[1,2,4] 121 | l.insert(2,3) 122 | print(l) 123 | ``` 124 | Output: 125 | ``` 126 | [1,2,3,4] 127 | ``` 128 | 129 | ## delete 130 | ```python 131 | l=[3.14, 42, "baz"] 132 | del l[2] 133 | print(l) 134 | ``` 135 | Output: 136 | ``` 137 | [3.14, 42] 138 | ``` 139 | 140 | ## remove() 141 | ```python 142 | l = [1, 2, 3 , 2] 143 | l.remove(2) 144 | print(l) 145 | ``` 146 | Output: 147 | ``` 148 | [1, 3, 2] 149 | ``` 150 | 151 | To remove **_all_** occurrences of element x in list l, 152 | 153 | ```Python 154 | while x in l: 155 | l.remove(x) 156 | ``` 157 | 158 | ## pop() 159 | 160 | ```python 161 | l=[1,2,3,4] 162 | print(l.pop(2)) 163 | ``` 164 | Output: 165 | ``` 166 | 3 167 | ``` 168 | 169 | #### pop vs. remove vs. del 170 | 171 | >remove removes the first matching value, not a specific index; 172 | >del removes the item at a specific index; 173 | >while pop removes the item at a specific index and returns it. 174 | 175 | ## range() and in: 176 | ```python 177 | l1 = [1, 2, 3, 4] 178 | p=len(l1) 179 | for i in range(1,p,2): #1 included p excluded, step = 2 180 | print(l[i], end = ' ') 181 | print() 182 | l = [4,3,2,5] 183 | for i in l: 184 | i+=1 185 | print(i, end = ' ') 186 | print() 187 | print(l , l1) 188 | ``` 189 | Output: 190 | ``` 191 | 2 4 192 | 5 4 3 6 193 | [4, 3, 2, 5] [1, 2, 3, 4] 194 | ``` 195 | Note how in the second loop **i** was just a copy of each element and thus changing it did not modify the list. 196 | ## count() 197 | ```python 198 | l=["a","b","c","b"] 199 | print(l.count("b")) 200 | ``` 201 | Output: 202 | ``` 203 | 2 204 | ``` 205 | 206 | ## sorting a List 207 | ```python 208 | l=[3,2,9,7] 209 | l2 = [9, 7, 6, 10] 210 | l.sort() #sorts l in place, return type void 211 | a=sorted(l2) #sorts list and creates new list 212 | print(l) 213 | print(l2) 214 | print(a) 215 | ``` 216 | Output: 217 | ``` 218 | [2, 3, 7, 9] 219 | [9, 7, 6, 10] 220 | [6, 7, 9, 10] 221 | ``` 222 | 223 | 224 | 225 | ## Nested Lists 226 | ```python 227 | l = [[2,[37]], 4, ["foo"]] 228 | print(l[0][1][0]) 229 | ``` 230 | Output: 231 | ``` 232 | 37 233 | ``` 234 | -------------------------------------------------------------------------------- /python/containers/sets.md: -------------------------------------------------------------------------------- 1 |

Sets

2 | 3 | ## Introduction 4 | 5 | - A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated. 6 | 7 | - Sets are commonly used for membership testing, removing duplicates entries, and also for operations such as intersection, union, and set difference. 8 | 9 | ## Creating a set 10 | - To create an empty set, set1 = set( ) 11 | - To create a set with a string, set2 = set("Baz") 12 | > set1 = {'b', 'a', 'z'} 13 | - If we create a set with repeated elements: set3=set([1,2,3,2,3,1]) 14 | > set3 = {1,2,3} 15 | ## Functions : 16 | 30 | 31 | ## add() 32 | 33 | - Used to add an element to a set. 34 | - Complexity: O(1) 35 | ```Python 36 | set1 = set([1,2,3,4,5]) 37 | set1.add(6) 38 | print(s1) 39 | ``` 40 | Output: 41 | ``` 42 | {1, 2 , 3, 4 ,5 ,6} 43 | ``` 44 | 45 | - Similarly, we can add a tuple 46 | ```Python 47 | set1 = set([1,2,3,4,5]) 48 | set1.add((6,7)) 49 | print(s1) 50 | ``` 51 | Output: 52 | ``` 53 | {1, 2, 3, 4, 5 ,(6, 7)} 54 | ``` 55 | 56 | ## update() 57 | - adds elements to set; it is an in-place set union operation 58 | - Complexity: O(len(s)+len(t)), where s is the set and t is the iterable to be added. 59 | ```python 60 | set1 = set([1,2,3,4]) 61 | set1.update([5,6]) 62 | print(set1) 63 | set1.update({7,8}) 64 | print(set1) 65 | ``` 66 | Output: 67 | ``` 68 | {1,2,3,4,5,6} 69 | {1,2,3,4,5,6,7,8} 70 | ``` 71 | 72 | ## discard() and remove() 73 | 74 | - Both are used to remove an element from the set. 75 | 76 | - Both discard and remove take a single argument, the element to be deleted from the set. If the value is not present, discard() does not do anything. Whereas, remove will raise a KeyError exception. 77 | 78 | - Complexity: O(1) 79 | ```Python 80 | set1 = set([1,2,3,4,5,6,7]) 81 | set1.discard(7) 82 | print(set1) 83 | set1.remove(6) 84 | print(s1) 85 | set1.discard(8) 86 | print(set1) 87 | set1.remove(8) 88 | ``` 89 | Output: 90 | ``` 91 | {1,2,3,4,5,6} 92 | {1,2,3,4,5} 93 | {1,2,3,4,5} 94 | Traceback (most recent call last): 95 | 96 | File "python", line 1, in 97 | KeyError: 8 98 | ``` 99 | 100 | ## copy() 101 | 102 | - Creates a new set with same elements as original one. 103 | - Complexity: O(n) 104 | ```python 105 | set1 = set([1,2,3,4]) 106 | set2 = set1.copy() 107 | print(set2) 108 | ``` 109 | Output: 110 | ``` 111 | {1,2,3,4} 112 | ``` 113 | 114 | **Using assignment here instead of copy() will create a pointer to the already existing set.** 115 | 116 | ## clear() 117 | - Removes all elements from the set. 118 | ```python 119 | set1 = set([1,2,3,4]) 120 | set1.clear() 121 | print(set1) 122 | ``` 123 | Output: 124 | { } 125 | 126 | ## pop() 127 | - Removes and returns arbitrary set element. 128 | 129 | - Raises KeyError exception if set is empty. 130 | 131 | - Complexity: O(1) 132 | ```python 133 | set1 = set([1]) 134 | set1.pop() #3 135 | set1.pop() # KeyError: 'pop from an empty set' 136 | ``` 137 | 138 | ## difference, intersection, union 139 | 140 | - **intersection()** returns a new set with the elements common in both the sets. 141 | 142 | - **union()** returns new set with all elements from both the sets. 143 | 144 | - **difference()** returns a new set with all items from first set not in second. 145 | ```python 146 | set1 = {1,2,3,4} 147 | set2 = {3,4,5,6} 148 | print(set1.union(set2)) 149 | print(set1.intersection(set2)) 150 | print(set1.difference(set2)) 151 | ``` 152 | Output: 153 | ``` 154 | {1,2,3,4,5,6} 155 | {3,4} 156 | {1,2} 157 | ``` 158 | 159 | ## isdisjoint, issubset, issuperset 160 | 161 | - isdisjoint() returns true if intersection of sets is empty otherwise false. 162 | 163 | - issubset() returns true if setA is subset of setB, False if not. **<=** operator can also be used to test for issubset. To check for proper subset **<** is used. That is `set1 < set2` would check if set1 is a proper subset of set 2 164 | ```python 165 | set1 = {1,2,3,4} 166 | set2 = {1,2,3,4,5,6} 167 | print(set1.isdisjoint(set2)) 168 | print(set1.issubset(set2)) 169 | print(set2.issuperset(set1)) 170 | ``` 171 | Output: 172 | ``` 173 | False 174 | True 175 | True 176 | ``` 177 | 178 | ## symmetric_difference() 179 | 180 | - Returns a set with all the elements that are in the set and the iterable but not both. 181 | ```python 182 | s = set("Hello") 183 | p = set("World") 184 | print s.symmetric_difference(p) 185 | ``` 186 | Output: 187 | ``` 188 | {'H','e','W','r','d'} 189 | ``` 190 | 191 | ## sorting a set 192 | - Returns a list with elemnts of s in sorted order. 193 | - Complexity O(nlogn) 194 | ```python 195 | s = set([3,2,1,5,7,6,4]) 196 | print(sorted(s)) 197 | ``` 198 | Output: 199 | ``` 200 | [1,2,3,4,5,6,7] 201 | ``` 202 | - Note that this returns a list and not a set because sets are not ordered, that is, {2,1} and {1,2} are the same sets. 203 | 204 | 205 | One example where sets might be used is when we want to count the number of distinct numbers in a given list. 206 | ```python 207 | l = [1,2,5,4,2,3,1,5] 208 | s=set(l) 209 | print(len(l)) #number of distinct elements 210 | ``` 211 | 212 | Output: 213 | ``` 214 | 5 215 | ``` 216 | -------------------------------------------------------------------------------- /python/methods/Counters.md: -------------------------------------------------------------------------------- 1 | # Counter 2 | ```python 3 | from collections import Counter 4 | ``` 5 | 6 | **Description** : A Counter is a container that keeps track of how many times equivalent values are added. It can be used to implement the same algorithms for which bag or multiset data structures are commonly used in other languages. 7 | 8 | **Example** 9 | ```python 10 | from collections import Counter 11 | letters = ['a','b','b','c','a','b'] 12 | print(Counter(letters)) 13 | ``` 14 | **Output** : 15 | ```python 16 | Counter({'b': 3, 'a': 2, 'c': 1}) 17 | ``` 18 | 19 | |
Function
|
What it does ?
|
Complexity
| 20 | | :------------- | :------------- | :------------- | 21 | | counter() | Counter is a container that keeps track of how many times equivalent values are added. | O(n) 22 | | update() | Counter can be populated/updated using this. Note that it adds to counter and doesn't replace the value. | O(1) 23 | | most_common() | Used to produce a sequence of the _k_ most frequently encountered input values and their respective counts. | O(n log k) 24 | | elements() | The method returns an iterator that produces all of the items known to the Counter. | O(n) 25 | 26 | ## Implementation : 27 | ```python 28 | from collections import Counter 29 | 30 | c = Counter() #This initialize a empty counter 31 | print('Initial:', c) 32 | 33 | c.update('abcdaab') 34 | print('Sequence:', c) 35 | 36 | c.update({'a':1, 'd':5}) 37 | print('Dict:', c) 38 | 39 | print(c.most_common(3)) 40 | 41 | print(list(c.elements())) 42 | ``` 43 | **Output :** 44 | ```python 45 | Initial : Counter() 46 | Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1}) 47 | Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1}) 48 | [('d', 6), ('a', 4), ('b', 2)] 49 | ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd', 'd'] 50 | ``` 51 | -------------------------------------------------------------------------------- /python/methods/bisect.md: -------------------------------------------------------------------------------- 1 |

bisect

2 | 3 | > It provides support for maintaining a list in sorted order without having to sort the list after each insertion. 4 | 5 | > It uses a basic bisection algorithm to do its work. 6 | > 7 | > Bisection algorithms are, by definition, O(logn) . 8 | 9 | ### Functions 10 | 11 | * **bisect(arr,x,lo=0,hi=len(a))** 12 | 13 | >Locate the insertion point for x in a to maintain sorted order. 14 | 15 | >The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side. 16 | 17 | >If x is not present in list both **bisect_left** and **bisect_right** return the same value,else bisect_left returns the leftmost place in the sorted list to insert x and bisect_right returns the rightmost place. 18 | 19 | ```python 20 | bisect_left([1,2,4,5,7,8],3) 21 | bisect([1,2,4,5,7,8],3) 22 | bisect_left([1,2,4,5,5,7,8],5) 23 | bisect_right([1,2,4,5,5,7,8],5) 24 | bisect([1,2,4,5,5,7,8],5) 25 | ``` 26 | 27 | Output : 28 | ``` 29 | 2 30 | 2 31 | 2 32 | 3 33 | 5 34 | 5 35 | ``` 36 | 37 | * **insort(a,x,lo=0,hi=len(a))** 38 | 39 | >Insert x in a in sorted order. 40 | > 41 | >x is inserted in a after any existing entries of x same as **insort_right()**.But,**insort_left()** inserts x before the existing entries of x. 42 | > 43 | > Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step. 44 | 45 | Example: 46 | ```python 47 | x=[1,2,4,5,6,7] 48 | insort(x,3) 49 | print(x) 50 | ``` 51 | Output: 52 | 53 | ``` 54 | [1,2,3,4,5,6,7] 55 | ``` 56 | > **Note** : The values of lo and hi can be changed to apply the functions on a subset of the list instead 57 | -------------------------------------------------------------------------------- /python/methods/itertools.md: -------------------------------------------------------------------------------- 1 |

Itertools

2 | 3 | > **itertools** is a python module that provides a set of powerful tools that deal with iterators. An iterator is an object that can be iterated upon and returns data items one at a time using its next() method. 4 | > 5 | > Iterator based code is more memory efficient as data is not produced from the iterator until it is needed. 6 | 7 | >Using itertools leads to cleaner and more readable code. 8 | 9 | > To use itertools we must import the module as 10 | ```python 11 | import itertools 12 | ``` 13 | 14 | 15 | ## Functions: 16 | 17 | ### accumulate() 18 | ```python 19 | accumulate(iterable [,func]) 20 | ``` 21 | > The **accumulate** function processes the input iterable and applies function *func* successively to its nth and n+1th element and produces a return value. 22 | > 23 | > If *func* is not provided, it defaults to addition to produce the cummulative sum of the input. If *func* is provided, it must be a function of two arguements. 24 | 25 | Example 1: 26 | ```python 27 | from itertools import * 28 | l = [1, 2, 3, 4, 5] 29 | for e in accumulate(l): # defaults to add 30 | print(e, end=' ') 31 | print() 32 | ``` 33 | 34 | Output: 35 | ``` 36 | 1 3 6 10 15 37 | ``` 38 | 39 | Example 2: 40 | ```python 41 | from itertools import * 42 | l = [1, 2, 3, 4, 5] 43 | for e in accumulate(l, operator.mul): 44 | print(e, end=' ') 45 | print() 46 | ``` 47 | Output: 48 | ``` 49 | 1 2 6 24 120 50 | ``` 51 | 52 | 53 | ### count() 54 | ```python 55 | count(start=0, step=1) 56 | ``` 57 | 58 | > This function makes an iterator that returns evenly spaced values starting from *start* and the spacing is equal to *step*. If not provided, start and step default to **0** and **1** respectively. 59 | > 60 | > This function produces an infinite series. This is useful when we need to iterate over an infinite series, stopping when a condition is met. 61 | 62 | Example 1: 63 | ```python 64 | from itertools import * 65 | for e in count(10, 0.05): 66 | print(e) 67 | ``` 68 | Output: 69 | ``` 70 | Note: this program would print 71 | 10 72 | 10.05 73 | 10.10 74 | 10.15 75 | and so on, looping infinitely. 76 | ``` 77 | 78 | Example 2: 79 | ```python 80 | from itertools import * 81 | c = count(10, 0.25) 82 | print(next(c)) 83 | print(next(c)) 84 | print(next(c)) 85 | ``` 86 | 87 | Output: 88 | ``` 89 | 10 90 | 10.25 91 | 10.5 92 | ``` 93 | 94 | ### permutations() 95 | 96 | ```python 97 | permutations(iterable [,r]) 98 | ``` 99 | > This function returns successive r-length permutations of an iterable. If r is not provided, it defaults to the length of the iterable. The permutations are returned as tuples. 100 | > 101 | > Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order. 102 | 103 | 104 | Example: 105 | ```python 106 | from itertools import * 107 | li = [2, 3, 1] 108 | for e in permutations(li, 2): 109 | print(e) 110 | ``` 111 | Output: 112 | ``` 113 | (2, 3) 114 | (2, 1) 115 | (3, 2) 116 | (3, 1) 117 | (1, 2) 118 | (1, 3) 119 | ``` 120 | 121 | ### combinations() 122 | ```python 123 | combinations(iterable, r) 124 | ``` 125 | > This function returns successive r-length combinations (or subsequences) of an iterable. Note that r is not optional here. 126 | 127 | Example: 128 | ```python 129 | from itertools import * 130 | li = [2, 3, 1] 131 | for e in combinations(li, 2): 132 | print(e) 133 | ``` 134 | Output: 135 | ``` 136 | (2, 3) 137 | (2, 1) 138 | (3, 1) 139 | ``` 140 | 141 | ## combinations_with_replacement() 142 | ```python 143 | combinations_with_replacement(iterable, r) 144 | ``` 145 | > This function is very similar to combinations with the difference being that this one allows an element to be repeated. 146 | 147 | Example: 148 | ```python 149 | from itertools import * 150 | li = [2, 3, 1] 151 | for e in combinations_with_replacement(li, 2): 152 | print(e) 153 | ``` 154 | Output: 155 | ``` 156 | (2, 2) 157 | (2, 3) 158 | (2, 1) 159 | (3, 3) 160 | (3, 1) 161 | (1, 1) 162 | ``` 163 | -------------------------------------------------------------------------------- /python/methods/miscellaneous.md: -------------------------------------------------------------------------------- 1 | # GCD 2 | 3 | ```python 4 | import math 5 | 6 | print(math.gcd(2,4)) 7 | ``` 8 | **Output** : 9 | ```python 10 | 2 11 | ``` 12 | 13 | # Fractions 14 | ```python 15 | from fractions import Fraction 16 | 17 | print(Fraction(16, -10)) 18 | print(Fraction(3, 2)) 19 | ``` 20 | **Output** : 21 | ```python 22 | -8/5 23 | 3/2 24 | ``` 25 | 26 | # Power 27 | ```python 28 | import math 29 | 30 | print(math.pow(16, -10)) 31 | print(math.pow(3, 2)) 32 | ``` 33 | **Output** : 34 | ```python 35 | 9.094947017729282e-13 36 | 9.0 37 | ``` 38 | 39 | -------------------------------------------------------------------------------- /reference.md: -------------------------------------------------------------------------------- 1 | # Reference 2 | -------------------------------------------------------------------------------- /template.md: -------------------------------------------------------------------------------- 1 | ### Title 2 | 3 | #### Subtitle ( if available ) 4 | 5 | > description goes here 6 | 7 | ### examples 8 | 9 | * Function name 1 10 | ``` 11 | code snippet goes here 12 | ``` 13 | * Function name 2 14 | ``` 15 | code snippet goes here 16 | ``` 17 | 18 | **Note** : ( if any ) 19 | 20 | |scenario| Complexity | 21 | |----|:---| 22 | |Worst Case | O(N) | 23 | | Best Case | O(1) | 24 | 25 | 26 | ============================================================ 27 | 28 | Note: 29 | 30 | - use proper file names eg: 01-Deque.md 31 | - use python , cpp ,java for code syntax highlighting snippet 32 | --------------------------------------------------------------------------------