Longest substring without repeating characters

    by nikoo28

    Question: Given a string, find the length of the longest substring without repeating characters.
    Input: “abcabcbb”
    Output: “abc”

    Input: “bbbb”
    Output: “b”

    The longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3.
    For “bbbbb” the longest substring is “b”, with the length of 1.

    We definitely have the brute-force method, where we find each string and then compare. But we want to speed up the process.

    How can we can look up if a character had existed in the substring instantaneously? The answer is using a simple table to store the characters that have appeared. As you traverse through the string, update by using its ASCII value as index to the table.

    The next question is to ask yourself what happens when you found a repeated character? For example, if the string is “abcdcedf”, what happens when you reach the second appearance of ‘c’?

    When you have found a repeated character (let’s say at index j), it means that the current substring (excluding the repeated character of course) is a potential maximum, so update the maximum if necessary. It also means that the repeated character must have appeared before at an index i, where i is less than j.

    Since you know that all substrings that start before or at index i would be less than your current maximum, you can safely start to look for the next substring with head which starts exactly at index i+1.

    Therefore, you would need two indices to record the head and the tail of the current substring. Since i and j both traverse at most n steps, the worst case would be 2n steps, which the run time complexity must be O(n).

    Below is the implementation in C++. Beware of the common mistake of not updating the maximum after the main loop, which is easy to forget.

    int lengthOfLongestSubstring(string s)
    {
    	//Get the length of string
    	int n = s.length();
    	
    	int i = 0, j = 0;
    	int maxLen = 0;
    	
    	// Set all characters as not-existing
    	bool exist[256] = { false };
    	
    	while (j < n)
    	{
    		// Check if the character exists
    		if (exist[s[j]])
    		{
    			maxLen = max(maxLen, j-i);
    			while (s[i] != s[j])
    			{
    				exist[s[i]] = false;
    				i++;
    			}
    			
    			i++;
    			j++;
    		}
    		else
    		{
    			exist[s[j]] = true;
    			j++;
    		}
    	}
    	
    	maxLen = max(maxLen, n-i);
    	return maxLen;
    }
    
    2 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Make a fair coin from a biased coin.

    by nikoo28
    2 minutes read

    Question: You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with 50% probability each. Your function should use only foo(), no other library method. We know foo() returns 0 with 60% probability. How can we ensure that 0 and 1 are returned with 50% probability? If we can somehow get two cases with equal probability, then we are done. We call foo() two times. …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Trees

    Find the left view of a binary tree.

    by nikoo28
    2 minutes read

    Question: Given the root pointer to a binary tree, find the left view of the tree. Input: Sample Tree (Pointer to node 1 is given). Output: 1, 2, 4 At a single glance of the problem, we can understand that we need to perform a level order traversal on the tree. This is similar to finding the number of levels in a tree. At the start of each level, we just print the first element. This can be done with the algorithm below:- void leftViewOfBinaryTree(struct binaryTreeNode * root) { // …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    Symbol Table Implementations

    by nikoo28
    2 minutes read

    Symbol Tables can be implemented in many ways and here are some of them. Unordered Array Implementation With this method, just maintaining an array is enough. It needs O(n) time for searching, insertion and deletion in the worst case. Ordered [Sorted] Array Implementation In this we maintain a sorted array of keys and values. Store in sorted order by key keys[i] = ith largest key values[i] = value associated with ith largest key Since the elements are sorted and stored in arrays, we can use simple binary search for finding …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    Symbol Tables

    by nikoo28
    2 minutes read

    Since childhood, we have all used a dictionary, and many of us have used a word processor (say Microsoft WORD) which comes with a spell checker. The spell checker is also a dictionary but limited. There are many real time examples for dictionaries and few of them are:- Spelling checker The data dictionary found in database management applications Symbol tables generated by loaders, assemblers, and compilers Routing tables in networking companies (DNS Lookup) In computer science, we generally use the term symbol table rather than dictionary, when referring to the …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More