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.