Longest Consecutive Sequence
LeetCode 128 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Only expand from run starts (num − 1 not in set).
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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_lengthLongest 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.