Загрузка...

leetcode problem 128 |Longest Consecutive Sequence | O(n) Solution | c++

In this video, I explain the Longest Consecutive Sequence problem in the simplest way.
We use a map-based O(n) technique,
I show the idea, examples, full dry run, and line-by-line C++ code explanation.
Perfect for beginners!

100, 4, 200, 1, 3, 2]
Consecutive sequences inside this:

100 → alone → length = 1

200 → alone → length = 1

1, 2, 3, 4 → all in order → length = 4 ✔

So the answer is:

Output: 4
Because the longest ordered group is:
➡️ 1, 2, 3, 4

Rules:

If a number already exists in the map → skip it

Check its left: (n-1)

Check its right: (n+1)

Total length = left + 1 + right

Update the boundaries:

left boundary becomes: n - left

right boundary becomes: n + right

Store total length in both boundaries

Keep track of the longest sequence

This allows us to solve the problem in O(n) time.
#LeetCode128
#LongestConsecutiveSequence
#ArrayProblems
#HashSet
#CPlusPlus
#CodingInterview
#DataStructures
#OptimalSolution
#LeetCode
#SequenceProblems

Видео leetcode problem 128 |Longest Consecutive Sequence | O(n) Solution | c++ канала izumicode
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять