Longest Consecutive Sequence

Problem

Read an unsorted array. Print the length of the longest group of numbers that follow each other (like 1, 2, 3, 4). The numbers do not need to be next to each other in the array. Do it in O(n) time.

Constraints

  • 1 <= n <= 10^5

Examples

Input

6
100 4 200 1 3 2

Output

4

Solutions

Best approachTime O(n)Space O(n)

Sorting would cost O(n log n). With a set, we start counting only at numbers that have no smaller neighbour. Then every number is visited at most twice, so the time is O(n).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The longest length.
 * Approach: Use a set and start only at sequence beginnings.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a) {
        // Step 1: Put all numbers in a set. A set finds a number in constant time.
        java.util.Set<Integer> numbers = new java.util.HashSet<>();
        for (int value : a) {
            numbers.add(value);
        }

        int best = 0;
        for (int value : numbers) {
            // Step 2: Only start counting at the beginning of a sequence (value - 1 is missing).
            if (!numbers.contains(value - 1)) {
                int end = value;

                // Step 3: Walk to the right while the next number exists.
                while (numbers.contains(end + 1)) {
                    end++;
                }
                best = Math.max(best, end - value + 1);
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. Why do we only start at numbers where value - 1 is missing?