|
| 1 | +package depth_first_search; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by gouthamvidyapradhan on 15/12/2017. |
| 7 | + * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. |
| 8 | +
|
| 9 | + For example, |
| 10 | + Given [100, 4, 200, 1, 3, 2], |
| 11 | + The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. |
| 12 | +
|
| 13 | + Your algorithm should run in O(n) complexity. |
| 14 | +
|
| 15 | + Solution: O(n) time and space complexity - Build a graph linking each number which is greater or lesser by one. |
| 16 | + Perform a dfs to count the depth of a graph. |
| 17 | +
|
| 18 | + Dfs using recursion fails due to StackOverFlowError(due to deep recursion) hence used a iterative approach with a |
| 19 | + stack |
| 20 | + */ |
| 21 | +public class LongestConsecutiveSequence { |
| 22 | + |
| 23 | + private Map<Integer, Set<Integer>> graph; |
| 24 | + private Set<Integer> done; |
| 25 | + /** |
| 26 | + * Main method |
| 27 | + * @param args |
| 28 | + * @throws Exception |
| 29 | + */ |
| 30 | + public static void main(String[] args) throws Exception{ |
| 31 | + int[] nums = {-1, 0, -3, -2, 1, 2, 3, 4, 5, 4}; |
| 32 | + System.out.println(new LongestConsecutiveSequence().longestConsecutive(nums)); |
| 33 | + } |
| 34 | + |
| 35 | + public int longestConsecutive(int[] nums) { |
| 36 | + done = new HashSet<>(); |
| 37 | + graph = new HashMap<>(); |
| 38 | + for (int u : nums) { |
| 39 | + graph.putIfAbsent(u, new HashSet<>()); |
| 40 | + if (graph.keySet().contains(u - 1)) { |
| 41 | + graph.get(u - 1).add(u); |
| 42 | + graph.get(u).add(u - 1); |
| 43 | + } |
| 44 | + if (graph.keySet().contains(u + 1)) { |
| 45 | + graph.get(u + 1).add(u); |
| 46 | + graph.get(u).add(u + 1); |
| 47 | + } |
| 48 | + } |
| 49 | + int max = 0; |
| 50 | + for(int i : graph.keySet()){ |
| 51 | + if(!done.contains(i)){ |
| 52 | + Stack<Integer> stack = new Stack<>(); |
| 53 | + stack.add(i); |
| 54 | + max = Math.max(max, dfs(0, stack)); |
| 55 | + } |
| 56 | + } |
| 57 | + return max; |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + private int dfs(int count, Stack<Integer> stack){ |
| 62 | + while(!stack.isEmpty()){ |
| 63 | + int top = stack.pop(); |
| 64 | + count++; |
| 65 | + done.add(top); |
| 66 | + |
| 67 | + Set<Integer> children = graph.get(top); |
| 68 | + if(children != null){ |
| 69 | + children.stream().filter(c -> !done.contains(c)).forEach(stack::push); |
| 70 | + } |
| 71 | + } |
| 72 | + return count; |
| 73 | + } |
| 74 | +} |
0 commit comments