Skip to content
Katabench
Try free

Longest Consecutive Sequence

Medium About 20 min Free, no account needed

Find the length of the longest run of consecutive integers hiding in an unsorted array.

The brief

Given an unsorted array of integers nums, return the length of the longest sequence of consecutive integers present in it. The elements may appear in any order; duplicates count once.

  • [100, 4, 200, 1, 3, 2] contains 1, 2, 3, 4, the answer is 4.
  • An empty array has answer 0.

The performance bar

The obvious approach extends a run from every element and answers "is v + 1 present?" by scanning the whole array each time. On the hidden test, 200,000 consecutive values, that nested scanning is far too slow. You will need each value to be visited only a constant number of times, O(n) overall.

Starter code

C#
using System;

public class Solution
{
    // TODO: return the length of the longest run of consecutive integers present in nums.
    public int LongestConsecutive(int[] nums)
    {
        throw new NotImplementedException();
    }
}

How it is graded

Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.

C# coding challenges →

What it practices

Hash maps and sets
Trade memory for constant-time lookups, membership tests and frequency counts.

Related katas