1+ import java .util .HashSet ;
2+
3+ class Solution {
4+ // This solution was inspired by:
5+ // https://www.algodale.com/problems/longest-consecutive-sequence/
6+ //
7+ // I initially believed this algorithm would run in O(n) time,
8+ // but it resulted in a Time Limit Exceeded error.
9+ //
10+ // Although the expected time complexity is O(n),
11+ // repeatedly calling set.iterator().next() might introduce overhead.
12+ // Iterating through the set using a for-loop may be a better approach.
13+ //
14+ // In this case, it seems preferable to follow the approach described here:
15+ // https://www.algodale.com/problems/longest-consecutive-sequence/#%ED%92%80%EC%9D%B4-3
16+
17+ public int oldApproach (int [] nums ) {
18+ int count = 0 ;
19+ HashSet <Integer > set = new HashSet <>();
20+ for (int num : nums ) {
21+ set .add (num );
22+ }
23+
24+ while (set .size () > 0 ) {
25+ int buffer = 1 ;
26+ // This may cause a Time Limit Exceeded error.
27+ Integer curr = set .iterator ().next ();
28+ set .remove (curr );
29+ Integer next = curr + 1 ;
30+ Integer prev = curr - 1 ;
31+
32+ while (set .contains (next )) {
33+ set .remove (next );
34+ next ++;
35+ buffer ++;
36+ }
37+
38+ while (set .contains (prev )) {
39+ set .remove (prev );
40+ prev --;
41+ buffer ++;
42+ }
43+
44+ count = Math .max (count , buffer );
45+ }
46+
47+ return count ;
48+ }
49+
50+ public int longestConsecutive (int [] nums ) {
51+ int count = 0 ;
52+
53+ // The Set has O(n) space complexity,
54+ // because it may store up to n elements in memory.
55+ // Is this the correct way to evaluate space complexity?
56+ HashSet <Integer > set = new HashSet <>();
57+ for (int num : nums ) {
58+ set .add (num );
59+ }
60+
61+ for (int num : set ) {
62+ if (set .contains (num - 1 )) {
63+ continue ;
64+ }
65+
66+ int currentNum = num ;
67+ int currentCount = 1 ;
68+
69+ while (set .contains (currentNum + 1 )) {
70+ currentNum ++;
71+ currentCount ++;
72+ }
73+
74+ count = Math .max (count , currentCount );
75+ }
76+
77+ return count ;
78+ }
79+ }
0 commit comments