Wednesday, July 20, 2016

Longest Consecutive Sequence in unsorted Array

First time to see such an algorithm and think it is elegant. It uses hash map to check existence of adjacent numbers, so that it is O(1) on checking and by going through a list of n numbers, it would also finished checking the length of consecutive numbers. overall O(n) time.

Problem

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Code:
public int longestConsecutive(int[] num) {
    int res = 0;
    HashMap map = new HashMap();
    for (int n : num) {
        if (!map.containsKey(n)) {
            int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;
            int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;
            // sum: length of the sequence n is in
            int sum = left + right + 1;
            map.put(n, sum);
            
            // keep track of the max length 
            res = Math.max(res, sum);
            
            // extend the length to the boundary(s)
            // of the sequence
            // will do nothing if n has no neighbors
            map.put(n - left, sum);
            map.put(n + right, sum);
        }
        else {
            // duplicates
            continue;
        }
    }
    return res;
}

No comments: