TRICK TO REDUCE TIME COMPLEXITY USING HASH CONCEPT [DICTIONARY] Today, I learned a new way to know the indices of characters in a string. Example: If you have a string containing alphabets, and while doing some problem, inside a for loop, you need to access a particular alphabet's index in that string , you will definitely use string.index(k) function, where 'k' represents alphabet. But, it takes O(N) time, as it searches the whole string and returns the index as soon as it finds that particular alphabet. As we are performing this operation inside another for loop , this logic takes O(N^2) for implementation. But, we can know the index of that particular alphabet in O(1) time. Let us see HOW? Here, in the above code, we use the dictionary to store the alphabets in a string as keys and the corresponding indices as values. As the dictionary uses the hash table concept for accessing the value of a particular key, it takes a constant time, i.e., O(1). So, now if we use t...
A website about how to code