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

मी 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.