/ Tags: RUBY-CODE / Categories: SOLUTIONS

Find The Longest Consecutive Sequence In An Array In Ruby

Identify the longest run of consecutive integers in an unsorted array — useful for streak detection, range analysis, and data validation.

Description

Sort the array, remove duplicates, then use chunk_while to group consecutive integers (where each next element equals the previous plus one). The longest group is found with max_by(&:length). Alternatively, use a set for O(n) lookup: for each element that starts a sequence (has no predecessor in the set), walk forward until the chain breaks.

Sample input:

  nums = [100, 4, 200, 1, 3, 2, 5, 6]


Sample Output:

  [1, 2, 3, 4, 5, 6]   # length 6

Answer

    nums = [100, 4, 200, 1, 3, 2, 5, 6]

    # chunk_while approach — clean and idiomatic
    longest = nums.sort.uniq
                   .chunk_while { |a, b| b == a + 1 }
                   .max_by(&:length)
    # => [1, 2, 3, 4, 5, 6]

    longest.length   # => 6
    longest.first    # => 1  (start of sequence)
    longest.last     # => 6  (end of sequence)

    # O(n) set approach — faster for large inputs
    require 'set'
    def longest_consecutive(nums)
      set     = nums.to_set
      longest = []
      set.each do |n|
        next if set.include?(n - 1)  # only start from sequence beginnings
        seq = n.step.lazy.take_while { |x| set.include?(x) }.to_a
        longest = seq if seq.length > longest.length
      end
      longest
    end

    longest_consecutive(nums)
    # => [1, 2, 3, 4, 5, 6]

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More