Showing posts with label Hash Table. Show all posts
Showing posts with label Hash Table. Show all posts

Sunday, March 23, 2014

No. 53 - Longest Arithmetic Sequence

Question 1: Given an array, please get the length of the longest arithmetic sequence. The element order in the arithmetic sequence should be same as the element order in the array. For example, in the array {1, 6, 3, 5, 9, 7}, the longest arithmetic sequence is 1, 3, 5, and 7, whose elements have same order as they are in the array, and the length is 4.

Analysis: Every pair of two adjacent numbers in an arithmetic sequence has exactly same difference. For example, 1, 3, 5, and 7 is an arithmetic sequence, and the pairs (1, 3), (3, 5), and (5, 7) have the same difference 2.

There are n(n-1)/2 pairs out of an array with n elements. These pairs can be categorized into a set of groups, of which each group of pairs have the same difference. For example, the pairs of numbers in the array {1, 6, 3, 5, 9, 7} can be categorized into groups:

Difference -1: (6, 5)
Difference 2: (1, 3), (3, 5), (5, 7)
Difference 3: (6, 9)

Therefore, a hash table can be defined for the groups. The key in the hash table is the difference of pairs, and the value in the hash table is a list of pairs with same difference. The code to build the hash table can be implemented in C# as the following:

internal class Pair
{
    public int First { get; set; }
    public int Second { get; set; }
}

private static Dictionary<int, List<Pair>> BuildHashTable(int[] numbers)
{
    var hashTable = new Dictionary<int, List<Pair>>();
    for(int i = 0; i < numbers.Length; ++i)
    {
        for(int j = i + 1; j < numbers.Length; ++j)
        {
            Pair pair = new Pair
            {
                First = i,
                Second = j
            };

            int diff = numbers[j] - numbers[i];
            if(hashTable.Keys.Contains(diff))
            {
                hashTable[diff].Add(pair);
            }
            else
            {
                List<Pair> newValue = new List<Pair>();
                newValue.Add(pair);
                hashTable[diff] = newValue;
            }
        }
    }

    return hashTable;
}

In the code above, the values of the hash table is pairs of indexes, rather than elements themselves of the array. The pairs are sorted according to their first elements.

The next step is to get the length of pairs with each difference. A list of pairs with difference k is got given a key k in the hash table. If an element A[i] is mth element is an arithmetic sequence with a common difference k, and there is a pair (A[i], A[j]) (j>i) in the list of pairs, the element A[j] should be the m+1thelemement in the arithmetic sequence.

Therefore, the code to get the max length of all arithmetic sequences can be implemented as:

private static int Analyze(Dictionary<int, List<Pair>> hashTable, int lengthOfNumbers)
{
    int maxLength = 0;
    foreach(var key in hashTable.Keys)
    {
        int[] lengths = new int[lengthOfNumbers];
        for (int i = 0; i < lengthOfNumbers; ++i)
        {
            lengths[i] = 1;
        }

        foreach(Pair pair in hashTable[key])
        {
            lengths[pair.Second] = lengths[pair.First] + 1;
        }

        foreach(var length in lengths)
        {
            if(length > maxLength)
            {
                maxLength = length;
            }
        }
    }

    return maxLength;
}

public static int GetMaxLengthOfArithmeticSequence(int[] numbers)
{
    var hashTable = BuildHashTable(numbers);
    return Analyze(hashTable, numbers.Length);
}

The source code with unit test cases are shared at: http://ideone.com/jxRDkd.

As mentioned above, there are O(n2) pairs in an array with n elements. Therefore, the time and space efficiencies of this solution is O(n2) given an array with n elements.

Question 2: Given an array, please get the length of the longest arithmetic sequence. The element order in the arithmetic sequence is not necessarily same as the element order in the array. For example, in the array {1, 6, 3, 5, 9, 7}, the longest arithmetic sequence is 1, 3, 5, 7, and 9, and the length is 5.

Analysis: Different from the previous problem, there are no limitations on the order of arithmetic sequence. Consequently, we can sort the array before we try to get the maximal length of arithmetic sequences. The code is almost same as before, except for the revision that there is an additional line of code to sort the array, as listed below:

public static int GetMaxLengthOfArithmeticSequence(int[] numbers)
{
    Array.Sort(numbers);
    var hashTable = BuildHashTable(numbers);
    return Analyze(hashTable, numbers.Length);
}

The source code with unit test cases are shared at: http://ideone.com/lEqNm3.

Question 3: Given an array, please get the length of the longest consecutive sequence. A consecutive sequence is an arithmetic sequence with common difference 1. The element order in the consecutive sequence is not necessarily same as the element order in the array. The solution should not cost more than O(n) time and space if the length of the input array is n. For example, in the array {1, 6, 3, 5, 9, 7}, the longest consecutive sequence is 5, 6, and 7 whose length is 3.

Analysis: The solution to solve the above problems cost O(n2) time and space. Therefore, we need a new solution to solve this problem.

A consecutive can’t have duplicated elements. A hash set, of which every element is unique, can be built from the input array. When a number is located in the set, we try to locate its consecutive neighbors. For instance, when the number 6 is found in the set, we try to find the number 5 and 7 in the set, and then we get a consecutive sequence 5, 6, and 7.

This solution can be implemented in C# code as listed below:

public static int GetMaxLengthConsecutiveSequence(int[] numbers)
{
    HashSet<int> set = BuildHashSet(numbers);
    return AnalyzeHashSet(set);
}

private static HashSet<int> BuildHashSet(int[] numbers)
{
    var set = new HashSet<int>();
    foreach(int number in numbers)
    {
        set.Add(number);
    }

    return set;
}

private static int AnalyzeHashSet(HashSet<int> set)
{
    int maxCount = 0;
    while(set.Count > 0)
    {
        int number = set.First();
        int count = 0;
        int toDelete = number;

        while(set.Remove(toDelete))
        {
            count++;
            toDelete++;
        }

        toDelete = number - 1;
        while(set.Remove(toDelete))
        {
            count++;
            toDelete--;
        }

        if(count > maxCount)
        {
            maxCount = count;
        }
    }

    return maxCount;
}

Every number in the input array is added into and removed from the array only once, so the time and space efficiency is O(n) if there are n numbers in the array.


The source code with unit tests is shared at http://ideone.com/0oRqLq.

More coding interview questions are discussed in my book< Coding Interviews: Questions, Analysis & Solutions>. You may find the details of this book on Amazon.com, or Apress.

The author Harry He owns all the rights of this post. If you are going to use part of or the whole of this ariticle in your blog or webpages, please add a reference to http://codercareer.blogspot.com/. If you are going to use it in your books, please contact him via zhedahht@gmail.com . Thanks.

Monday, October 24, 2011

No. 13 - First Character Appearing Only Once


Problem: Implement a function to find the first character in a string which only appears once.
For example: It returns ‘b’ when the input is “abaccdeff”.

Analysis: Our native solution for this problem may be scanning the input string from its beginning to end. We compare the current scanned character with every one behind it. If there is no duplication after it, it is a character appearing once. Since it compares each character with O(n) ones behind it, the overall time complexity is O(n2) if there are n characters in a string.

In order to get the numbers of occurrence times of each character in a string, a data container is needed. It is required to get and update the occurrence time of each character in a string, so the data container is used to project a character to a number. Hash tables fulfill this kind of requirement. We can implement a hash table, in which keys are characters and values are their occurrence times in a string.

It is necessary to scan strings twice: When a character is visited, we increase the corresponding occurrence time in the hash table during the first scanning. In second round of scanning, whenever a character is visited we also check its occurrence time in the hash table. The first character with occurrence time 1 is the required output.

Hash tables are complex, and they are not implemented in the C++ standard template library. Therefore, we have to implement one by ourselves.

Characters have 8 bits, so there only 256 variances. We can create an array with 255 numbers, in which indexes are ASCII values of all characters, and numbers are their occurrence times in a string. That is to say, we have a hash table whose size if 256, with ASCII values of characters as keys.

It is time for programming after we get a clear solution. The following are some sample code:

char FirstNotRepeatingChar(char* pString)
{
    if(pString == NULL)
        return '\0';

    const int tableSize = 256;
    unsigned int hashTable[tableSize];
    for(unsigned int i = 0; i<tableSize; ++ i)
        hashTable[i] = 0;

    char* pHashKey = pString;
    while(*(pHashKey) != '\0')
        hashTable[*(pHashKey++)] ++;

    pHashKey = pString;
    while(*pHashKey != '\0')
    {
        if(hashTable[*pHashKey] == 1)
            return *pHashKey;

        pHashKey++;
    }

    return '\0';
}

In the code above, it costs O(1) time to increase the occurrence time for each character. The time complexity for the first scanning is O(n) if the length of string is n. It takes O(1) time to get the occurrence time for each character, so it costs O(n) time for the second scanning. Therefore, the overall time it costs is O(n).

In the meantime, an array with 256 numbers is created, whose size is 1K. Since the size of array is constant, the space complexity of this algorithm is O(1).

The discussion about this problem is included in my book <Coding Interviews: Questions, Analysis & Solutions>, with some revisions. You may find the details of this book on Amazon.com, or Apress.
 
The author Harry He owns all the rights of this post. If you are going to use part of or the whole of this ariticle in your blog or webpages,  please add a referenced to http://codercareer.blogspot.com/. If you are going to use it in your books, please contact me (zhedahht@gmail.com) . Thanks.