Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2016 from MikeQCarr/longest-consecutiv…
Browse files Browse the repository at this point in the history
…e-sequence

Update: 0128-longest-consecutive-sequence.rb
  • Loading branch information
tahsintunan authored Jan 16, 2023
2 parents 3dd039d + 3340ef1 commit 8f92dbd
Showing 1 changed file with 11 additions and 49 deletions.
60 changes: 11 additions & 49 deletions ruby/0128-longest-consecutive-sequence.rb
Original file line number Diff line number Diff line change
@@ -1,52 +1,14 @@
def longest_consecutive(nums)
return 0 if nums.empty?

hash = {}
nums.each { |num| hash[num] = true }
longest = 0
nums.each do |num|
next if hash[num - 1]

challenger = 1
loop do
if hash[num + challenger]
challenger += 1
else
break
end
end
longest = challenger if challenger > longest
end

longest
end

# Another way to do it.
def longest_consecutive(nums)
return 0 if nums.empty?

hash = {}
nums.each { |num| hash[num] = -1 }
nums.each do |num|
next unless hash[num] == -1

longest_consec = 1
loop do
val = hash[num + longest_consec]
case val
when -1
hash[num + longest_consec] = -2
longest_consec += 1
when nil
hash[num] = longest_consec
break
else
longest_consec += hash[num + longest_consec]
hash[num] = longest_consec
break
end
set = Set.new(nums)
set.reduce(0) do |longest, num|
if !set.include?(num-1)
length = 0
while set.include?(num + length) do
length += 1
end
next(longest > length ? longest : length)
end

longest
end
end

hash.max_by { |_k, v| v }[1]
end

0 comments on commit 8f92dbd

Please sign in to comment.