Tensorum
YouTubeশেখা শুরু করুন
LeetCode 128 · Hashing / Anagram

Longest Consecutive Sequence

LeetCode 128 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Only expand from run starts (num − 1 not in set).

মাঝারিArrayHash TableUnion-Find
LeetCode-এ খুলুন ↗

আমি Longest Consecutive Sequence (LeetCode 128) এভাবে সমাধান করেছি — Hashing / Anagram প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.

Approach

  1. 1

    Build a set (removes duplicates, O(1) lookups).

  2. 2

    For each num with no predecessor, walk num+1, num+2, … counting length.

  3. 3

    Track the longest run.

আমি কীভাবে সমাধান করেছি

Hash set + run startsPythonO(n) time · O(n) space
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums:
            return 0
        unique_elenents = set(nums) #remove duplicates
        max_length = 1 #single element 
        for num in unique_elenents:
            if num-1 not in unique_elenents:
                length = 1
                while num+1 in unique_elenents:
                    num = num+1
                    length+=1
                max_length=max(max_length,length)
        return max_length
স্টেপ-থ্রু লোড হচ্ছে…

Longest Consecutive Sequence — সাধারণ প্রশ্ন

Longest Consecutive Sequence-এর পেছনে intuition কী?

Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.

Longest Consecutive Sequence (LeetCode 128) কীভাবে সমাধান করবেন?

1. Build a set (removes duplicates, O(1) lookups). 2. For each num with no predecessor, walk num+1, num+2, … counting length. 3. Track the longest run.

Longest Consecutive Sequence-এর time আর space complexity কত?

Time: O(n)। Space: O(n)। (Accepted approach: Hash set + run starts।)

Longest Consecutive Sequence-এ সাধারণ ভুলগুলো কী?

Without the 'is it a start?' check the algorithm degrades to O(n²). Empty input returns 0.