{"id":426,"date":"2025-06-29T16:03:21","date_gmt":"2025-06-29T10:33:21","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=426"},"modified":"2025-06-29T16:04:12","modified_gmt":"2025-06-29T10:34:12","slug":"longest-consecutive-sequence","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/","title":{"rendered":"Longest Consecutive Sequence | Leetcode 128"},"content":{"rendered":"\n<p>Struggling with the &#8220;Longest Consecutive Sequence&#8221; problem on LeetCode? This blog will help you understand the problem, walk you through three different solutions (Brute Force, Better, and Optimal), and explain every step. Let\u2019s get started!<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/longest-consecutive-sequence\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-cafcdf48-6cd3-419a-927c-3d544ab082e7\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#0-what-does-the-problem-say\" style=\"\">What Does the Problem Say?<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#1-example-1\" style=\"\">Example 1<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#2-example-2\" style=\"\">Example 2<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#3-brute-force-solution\" style=\"\">Brute Force Solution<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#4-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#5-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#6-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#7-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#8-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#9-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#10-better-solution\" style=\"\">Better Solution<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#11-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#12-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#13-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#14-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#15-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#16-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#17-optimal-solution\" style=\"\">Optimal Solution<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#18-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#19-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#20-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#21-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#22-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#23-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/longest-consecutive-sequence\/#24-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-does-the-problem-say\">What Does the Problem Say?<\/h2>\n\n\n\n<p>You are given an unsorted array of integers. Your task is to find the length of the longest sequence of consecutive numbers (numbers that come one after another, like 1, 2, 3, 4) in the array. The sequence elements can be in any order in the input array.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-example-1\">Example 1<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [100, 4, 200,<\/code> 1, 3, 2 ]<\/p>\n\n\n\n<p><strong>Explanation:<\/strong><br>The longest consecutive sequence is `[1, 2, 3, 4] the answer is 4.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-example-2\">Example 2<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [0, 3, 7, 2, 5, 8, 4, 6, 0<\/code>]<\/p>\n\n\n\n<p><code>Explanation: The longest consecutive sequence is&nbsp;<\/code>[0, 1, 2, 3, 4, 5, 6, 7, is 9.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-brute-force-solution\">Brute Force Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s break down the simplest way to solve this problem:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Pick Each Number:<\/strong><br>For every number in the array, try to build the longest consecutive sequence starting from that number.<\/li>\n\n\n\n<li><strong>Count Consecutive Numbers:<\/strong><br>For each starting number, keep checking if the next number (<code>num + 1<\/code>) exists in the array. If yes, increase your count and check for the next number.<\/li>\n\n\n\n<li><strong>Track the Maximum:<\/strong><br>Keep track of the largest count you find for any starting number. This will be your answer.<\/li>\n<\/ol>\n\n\n\n<p><strong>Why does this work?<\/strong><br>We are trying every possible starting point and counting how far we can go consecutively. It\u2019s simple but can be slow for large arrays because we keep searching the array for each next number.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"def longestSuccessiveElements(arr: List[int]) -&gt; int:\n    max_count = 0\n    n = len(arr)\n    for i in range(0, n):\n        num = arr[i]\n        count = 1\n        # Check for the next consecutive numbers\n        while num + 1 in arr:\n            count += 1\n            num += 1\n        max_count = max(max_count, count)\n    return max_count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">longestSuccessiveElements<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    max_count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        num = arr[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Check for the next consecutive numbers<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> num + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> arr:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            num += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        max_count = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(max_count, count)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> max_count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We loop through each element of the array.<\/li>\n\n\n\n<li>For each element, we try to find the next consecutive number (<code>num + 1<\/code>) in the array.<\/li>\n\n\n\n<li>We keep increasing the count as long as we find the next number.<\/li>\n\n\n\n<li>We update the maximum count whenever we find a longer sequence.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [100, 4, 200, with&nbsp;<\/code>100`: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Sequence is just &#8220; (count = 1)<\/li>\n\n\n\n<li>Start with&nbsp;<code>4<\/code>: Sequence is just &#8220; (count = 1)<\/li>\n\n\n\n<li>Start with&nbsp;<code>200<\/code>: Sequence is just &#8220; (count = 1)<\/li>\n\n\n\n<li>Start with&nbsp;<code>1<\/code>: Sequence is `[1, 2, 3,nt = 4)<\/li>\n\n\n\n<li>Start with&nbsp;<code>3<\/code>: Sequence is just `[3,count = 2)<\/li>\n\n\n\n<li>Start with&nbsp;<code>2<\/code>: Sequence is &#8220; (count = 3)<\/li>\n<\/ul>\n\n\n\n<p><strong>Maximum count found is 4.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(N^2)<br>For each element, we may search the whole array to find consecutive numbers.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1)<br>No extra space is used except for a few variables.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The brute force approach is easy to understand but not efficient for large arrays. It will work for small inputs or for understanding the problem.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"10-better-solution\">Better Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s try to make the solution faster:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Sort the Array:<\/strong><br>If the array is sorted, consecutive numbers will be next to each other. This makes it easy to count sequences.<\/li>\n\n\n\n<li><strong>Count Consecutive Runs:<\/strong><br>Go through the sorted array. For each number, if it is exactly one more than the previous number, increase the count. If it\u2019s a duplicate, skip it. If it\u2019s not consecutive, reset the count to 1.<\/li>\n\n\n\n<li><strong>Track the Longest:<\/strong><br>Keep updating the longest sequence found.<\/li>\n<\/ol>\n\n\n\n<p><strong>Why does this work?<\/strong><br>Sorting brings all consecutive numbers together, so we can count them in a single pass.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\ndef longestSuccessiveElements(arr: List[int]) -&gt; int:\n    arr.sort()  # Sort the array so consecutive numbers are next to each other\n    last_smaller = float(&quot;-inf&quot;)  # To keep track of the previous number\n    count = 0  # Current consecutive sequence length\n    longest = 0  # Longest sequence found\n\n    for num in arr:\n        if num - 1 == last_smaller:  # Check if current is consecutive\n            count += 1\n            last_smaller = num\n        elif num != last_smaller:  # Skip duplicates\n            count = 1\n            last_smaller = num\n        longest = max(longest, count)  # Update the answer\n\n    return longest\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">longestSuccessiveElements<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    arr.sort()  <\/span><span style=\"color: #6A9955\"># Sort the array so consecutive numbers are next to each other<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    last_smaller = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)  <\/span><span style=\"color: #6A9955\"># To keep track of the previous number<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    count = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># Current consecutive sequence length<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    longest = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># Longest sequence found<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> arr:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> num - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> == last_smaller:  <\/span><span style=\"color: #6A9955\"># Check if current is consecutive<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            last_smaller = num<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> num != last_smaller:  <\/span><span style=\"color: #6A9955\"># Skip duplicates<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            last_smaller = num<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        longest = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(longest, count)  <\/span><span style=\"color: #6A9955\"># Update the answer<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> longest<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We sort the array first.<\/li>\n\n\n\n<li>We use&nbsp;<code>last_smaller<\/code>&nbsp;to keep track of the last unique number.<\/li>\n\n\n\n<li>If the current number is consecutive to the last, we increase the count.<\/li>\n\n\n\n<li>If it\u2019s a duplicate, we skip.<\/li>\n\n\n\n<li>If it\u2019s not consecutive, we reset the count.<\/li>\n\n\n\n<li>We keep updating the longest sequence found.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [100, 4, 200, sorting:&nbsp;<\/code>[1, 2, 3, 4, 100, start new sequence (count = 1)<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>2<\/code>&nbsp;\u2192 consecutive (count = 2)<\/li>\n\n\n\n<li><code>3<\/code>&nbsp;\u2192 consecutive (count = 3)<\/li>\n\n\n\n<li><code>4<\/code>&nbsp;\u2192 consecutive (count = 4)<\/li>\n\n\n\n<li><code>100<\/code>&nbsp;\u2192 not consecutive, reset (count = 1)<\/li>\n\n\n\n<li><code>200<\/code>&nbsp;\u2192 not consecutive, reset (count = 1)<\/li>\n<\/ul>\n\n\n\n<p><strong>Maximum count found is 4.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(N log N)<br>Because of sorting.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1)<br>No extra space except for a few variables.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The better solution is much faster than brute force for large arrays. It uses sorting to make counting consecutive numbers easy.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"17-optimal-solution\">Optimal Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"18-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Can we solve this problem even faster, without sorting? Yes! Here\u2019s how:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Use a Set:<\/strong><br>Store all numbers in a set. This allows us to check if a number exists in O(1) time.<\/li>\n\n\n\n<li><strong>Find Sequence Starts:<\/strong><br>For each number, check if it could be the start of a sequence (i.e.,&nbsp;<code>num - 1<\/code>&nbsp;is not in the set).<\/li>\n\n\n\n<li><strong>Count the Sequence:<\/strong><br>For each start, count how many consecutive numbers exist by checking&nbsp;<code>num + 1<\/code>,&nbsp;<code>num + 2<\/code>, etc.<\/li>\n\n\n\n<li><strong>Update the Longest:<\/strong><br>Keep updating the longest sequence found.<\/li>\n<\/ol>\n\n\n\n<p><strong>Why does this work?<\/strong><br>We only start counting from the beginning of a sequence, so we never count the same sequence twice. Using a set makes lookups fast.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"19-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\ndef longestSuccessiveElements(arr: List[int]) -&gt; int:\n    my_set = set()\n    # Populate the set with all elements from arr\n    for num in arr:\n        my_set.add(num)\n\n    longest = 0\n\n    # For each number, check if it can start a new sequence\n    for num in my_set:\n        if num - 1 not in my_set:  # indicates a sequence start\n            x = num\n            count = 1\n\n            # Expand the sequence as far as possible\n            while x + 1 in my_set:\n                count += 1\n                x += 1\n\n            # Track the longest run\n            longest = max(longest, count)\n\n    return longest\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">longestSuccessiveElements<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    my_set = <\/span><span style=\"color: #4EC9B0\">set<\/span><span style=\"color: #D4D4D4\">()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># Populate the set with all elements from arr<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> arr:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        my_set.add(num)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    longest = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># For each number, check if it can start a new sequence<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> my_set:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> num - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> my_set:  <\/span><span style=\"color: #6A9955\"># indicates a sequence start<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            x = num<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Expand the sequence as far as possible<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> x + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> my_set:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                x += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Track the longest run<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            longest = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(longest, count)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> longest<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"20-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We store all numbers in a set for fast lookups.<\/li>\n\n\n\n<li>For each number, if&nbsp;<code>num - 1<\/code>&nbsp;is not in the set, it means this number could be the start of a sequence.<\/li>\n\n\n\n<li>We keep checking for&nbsp;<code>num + 1<\/code>,&nbsp;<code>num + 2<\/code>, etc., and count how long the sequence is.<\/li>\n\n\n\n<li>We update the longest sequence found.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"21-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>arr = [100, 4, 200,:&nbsp;<\/code>{1, 2, 3, 4, 100, 200}`<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For&nbsp;<code>1<\/code>:&nbsp;<code>0<\/code>&nbsp;not in set, so start sequence.\n<ul class=\"wp-block-list\">\n<li><code>2<\/code>&nbsp;in set \u2192 count = 2<\/li>\n\n\n\n<li><code>3<\/code>&nbsp;in set \u2192 count = 3<\/li>\n\n\n\n<li><code>4<\/code>&nbsp;in set \u2192 count = 4<\/li>\n\n\n\n<li><code>5<\/code>&nbsp;not in set \u2192 stop<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>For&nbsp;<code>2<\/code>:&nbsp;<code>1<\/code>&nbsp;in set \u2192 skip<\/li>\n\n\n\n<li>For&nbsp;<code>3<\/code>:&nbsp;<code>2<\/code>&nbsp;in set \u2192 skip<\/li>\n\n\n\n<li>For&nbsp;<code>4<\/code>:&nbsp;<code>3<\/code>&nbsp;in set \u2192 skip<\/li>\n\n\n\n<li>For&nbsp;<code>100<\/code>:&nbsp;<code>99<\/code>&nbsp;not in set \u2192 start sequence. Only&nbsp;<code>100<\/code>&nbsp;present (count = 1)<\/li>\n\n\n\n<li>For&nbsp;<code>200<\/code>:&nbsp;<code>199<\/code>&nbsp;not in set \u2192 start sequence. Only&nbsp;<code>200<\/code>&nbsp;present (count = 1)<\/li>\n<\/ul>\n\n\n\n<p><strong>Maximum count found is 4.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"22-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(N)<br>Each number is processed at most twice (once as a possible start, and once in the while loop).<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(N)<br>We use a set to store all numbers.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"23-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The optimal solution is the best for this problem. It uses a set to find sequences quickly and avoids unnecessary work. This is the approach you should use in interviews or for large inputs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"24-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>The &#8220;Longest Consecutive Sequence&#8221; problem is a great example of how to improve your solution step by step. Start with brute force to understand the problem, then use sorting for a better solution, and finally use a set for the most efficient answer.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Struggling with the &#8220;Longest Consecutive Sequence&#8221; problem on LeetCode? This blog will help you understand the problem, walk you through three different solutions (Brute Force, Better, and Optimal), and explain every step. Let\u2019s get started! Here&#8217;s the [Problem Link] to begin with. What Does the Problem Say? You are given an unsorted array of integers.<\/p>\n","protected":false},"author":1,"featured_media":427,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[7,19],"class_list":{"0":"post-426","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-array","10":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/longest-consecutive-sequence-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/426","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=426"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/426\/revisions"}],"predecessor-version":[{"id":429,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/426\/revisions\/429"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/427"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=426"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=426"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=426"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}