Find the Length of Longest Consecutive Integer Sequence from Unsorted Array

package org.wesome.dsalgo;

import java.util.Arrays;
import java.util.HashSet;

public class longestSequence {
    public static int longestSequence(int[] nums) {
        final HashSet<Integer> hSet = new HashSet<>();
//        Add all elements in HashSet
        Arrays.stream(nums).forEach(num -> hSet.add(num));
        int longest_sequence_len = 0;
        for (int i : nums) { // loop all elements of array
            int length = 1;
            // check if list contains no less than current
            for (int j = i - 1; hSet.contains(j); --j) {
                hSet.remove(j);
                ++length;
            }
            // check if list contains no more than current
            for (int j = i + 1; hSet.contains(j); ++j) {
                hSet.remove(j);
                ++length;
            }
            longest_sequence_len = Math.max(longest_sequence_len, length);
        }
        return longest_sequence_len;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.wesome.dsalgo.longestSequence.longestSequence;

public class longestSequenceTest {
    @Test
    void longestSequence1() {
        int[] arr = {49, 1, 3, 2, 4, 5};
        System.out.print("Array elements are: " + Arrays.toString(arr));
        int longestSequence = longestSequence(arr);
        System.out.println("The new length of the array is: " + longestSequence);
        Assertions.assertEquals(5, longestSequence);
    }

    @Test
    void longestSequence2() {
        int[] arr = {49, 1, 3, 3, 2, 4, 5};
        System.out.print("Array elements are: " + Arrays.toString(arr));
        int longestSequence = longestSequence(arr);
        System.out.println("longestSequence = " + longestSequence);
        Assertions.assertEquals(5, longestSequence);
    }

    @Test
    void longestSequence3() {
        int[] arr = {49, 1, 3, 8, 2, 4, 5};
        System.out.print("Array elements are: " + Arrays.toString(arr));
        int longestSequence = longestSequence(arr);
        System.out.println("longestSequence = " + longestSequence);
        Assertions.assertEquals(5, longestSequence);
    }

    @Test
    void longestSequence4() {
        int[] arr = {1, 20, 2, 19, 3, 18, 4, 17, 5};
        System.out.print("Array elements are: " + Arrays.toString(arr));
        int longestSequence = longestSequence(arr);
        System.out.println("longestSequence = " + longestSequence);
        Assertions.assertEquals(5, longestSequence);
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

repositories {
    mavenCentral()
}
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on