✅☑[C++/C/Java/Python/JavaScript]  || Beats 100% || 3 Approaches || EXPLAINED🔥
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approach\n(Also explained in the code)\n\n#### Approach 1:   Sorting || Iteration\n\n1. If the input vector nums is emp
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approach\n***(Also explained in the code)***\n\n#### ***Approach 1:   Sorting || Iteration***\n\n1. If the input vector `nums` is empty (`n == 0`), it returns 0 because there are no consecutive elements in an empty vector.\n\n1. The code starts by sorting the `nums` vector in ascending order to make it easier to identify consecutive elements.\n\n1. It uses two variables, `cnt` and `maxi`, to keep track of the current consecutive sequence length and the maximum consecutive sequence length encountered so far.\n\n1. It iterates through the sorted vector and checks if the current element is different from the previous one. If it\'s different:\n\n    - If the current element is consecutive to the previous one, the `cnt` counter is incremented.\n    - If the current element is not consecutive, the code updates `maxi` with the maximum of `maxi` and `cnt` and resets `cnt` to 1 to start counting the next potential consecutive sequence.\n\n1. After processing the entire sorted vector, the code returns the maximum of `maxi` and `cnt` as the result, ensuring that it correctly returns the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(nlogn)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int n = nums.size();\n        \n        // Base case: If the input vector is empty, there are no consecutive elements.\n        if (n == 0) {\n            return 0;\n        }\n\n        // Step 1: Sort the input vector in ascending order.\n        sort(nums.begin(), nums.end());\n\n        int cnt = 1;    // Initialize a counter for the current consecutive sequence length.\n        int maxi = 0;   // Initialize a variable to store the maximum consecutive sequence length.\n\n        // Step 2: Iterate through the sorted vector.\n        for (int i = 1; i < n; i++) {\n            // Step 3: Check if the current element is different from the previous one.\n            if (nums[i] != nums[i - 1]) {\n                // Step 4: If the current element is consecutive to the previous one, increment the counter.\n                if (nums[i] == nums[i - 1] + 1) {\n                    cnt++;\n                } else {\n                    // Step 5: If the current element is not consecutive, update \'maxi\' and reset \'cnt\'.\n                    maxi = max(maxi, cnt);\n                    cnt = 1;\n                }\n            }\n        }\n\n        // Step 6: Return the maximum of \'maxi\' and \'cnt\' as the result.\n        return max(maxi, cnt);\n    }\n};\n\n```\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n\nint compare(const void *a, const void *b) {\n    return (*(int*)a - *(int*)b);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n    if (numsSize == 0) {\n        return 0;\n    }\n\n    qsort(nums, numsSize, sizeof(int), compare);\n\n    int cnt = 1;\n    int maxi = 0;\n\n    for (int i = 1; i < numsSize; i++) {\n        if (nums[i] != nums[i - 1]) {\n            if (nums[i] == nums[i - 1] + 1) {\n                cnt++;\n            } else {\n                maxi = (maxi > cnt) ? maxi : cnt;\n                cnt = 1;\n            }\n        }\n    }\n\n    return (maxi > cnt) ? maxi : cnt;\n}\n\nint main() {\n    int nums[] = {100, 4, 200, 1, 3, 2};\n    int numsSize = sizeof(nums) / sizeof(nums[0]);\n    printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n    return 0;\n}\n\n\n```\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n    public int longestConsecutive(int[] nums) {\n        int n = nums.length;\n        \n        if (n == 0) {\n            return 0;\n        }\n\n        Arrays.sort(nums);\n\n        int cnt = 1;\n        int maxi = 0;\n\n        for (int i = 1; i < n; i++) {\n            if (nums[i] != nums[i - 1]) {\n                if (nums[i] == nums[i - 1] + 1) {\n                    cnt++;\n                } else {\n                    maxi = Math.max(maxi, cnt);\n                    cnt = 1;\n                }\n            }\n        }\n\n        return Math.max(maxi, cnt);\n    }\n}\n\n\n```\n```python []\nclass Solution:\n    def longestConsecutive(self, nums: List[int]) -> int:\n        n = len(nums)\n        \n        if n == 0:\n            return 0\n\n        nums.sort()\n\n        cnt = 1\n        maxi = 0\n\n        for i in range(1, n):\n            if nums[i] != nums[i - 1]:\n                if nums[i] == nums[i - 1] + 1:\n                    cnt += 1\n                else:\n                    maxi = max(maxi, cnt)\n                    cnt = 1\n\n        return max(maxi, cnt)\n\n```\n```Javascript []\nvar longestConsecutive = function(nums) {\n    const n = nums.length;\n    \n    if (n === 0) {\n        return 0;\n    }\n\n    nums.sort((a, b) => a - b);\n\n    let cnt = 1;\n    let maxi = 0;\n\n    for (let i = 1; i < n; i++) {\n        if (nums[i] !== nums[i - 1]) {\n            if (nums[i] === nums[i - 1] + 1) {\n                cnt++;\n            } else {\n                maxi = Math.max(maxi, cnt);\n                cnt = 1;\n            }\n        }\n    }\n\n    return Math.max(maxi, cnt);\n};\n\n```\n\n---\n#### ***Approach 2: Sorting || Iteration***\n\n1. It starts by sorting the `nums` vector in ascending order to make it easier to identify consecutive elements.\n\n1. It handles the base case when the vector is empty (size `n` is 0), returning 0 because there are no consecutive elements.\n\n1. Inside the loop, it checks if the current number is consecutive to the previous one (`nums[i] - 1 == last_number`) and increments the counter `cnt`.\n\n1. If the current number is not consecutive, it resets the counter `cnt` to 1 and updates `last_number` with the current number.\n\n1. It updates the `longest` variable with the maximum of its current value and the `cnt` counter.\n\n1. After processing the entire sorted vector, it returns `longest` as the result, representing the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(nlogn)$$\n\n- **Space complexity:**\n$$O(1)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int n = nums.size();\n        \n        // Step 1: Sort the input vector in ascending order.\n        sort(nums.begin(), nums.end());\n        \n        // Step 2: Handle the base case when the vector is empty.\n        if (n == 0) {\n            return 0;\n        }\n        \n        int last_number = INT_MIN;  // Initialize a variable to track the last processed number.\n        int cnt = 0;                // Initialize a counter for the current consecutive sequence length.\n        int longest = 1;            // Initialize a variable to store the maximum consecutive sequence length.\n\n        // Step 3: Iterate through the sorted vector.\n        for (int i = 0; i < n; i++) {\n            if (nums[i] - 1 == last_number) {\n                // Step 4: If the current number is consecutive to the previous one, increment the counter.\n                cnt++;\n                last_number = nums[i];\n            } else if (nums[i] != last_number) {\n                // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n                cnt = 1;\n                last_number = nums[i];\n            }\n            \n            // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n            longest = max(longest, cnt);\n        }\n\n        // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n        return longest;\n    }\n};\n\n\n```\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\nint compare(const void *a, const void *b) {\n    return (*(int*)a - *(int*)b);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n    // Step 1: Sort the input array in ascending order.\n    qsort(nums, numsSize, sizeof(int), compare);\n\n    // Step 2: Handle the base case when the array is empty.\n    if (numsSize == 0) {\n        return 0;\n    }\n\n    int last_number = INT_MIN;  // Initialize a variable to track the last processed number.\n    int cnt = 0;                // Initialize a counter for the current consecutive sequence length.\n    int longest = 1;            // Initialize a variable to store the maximum consecutive sequence length.\n\n    // Step 3: Iterate through the sorted array.\n    for (int i = 0; i < numsSize; i++) {\n        if (nums[i] - 1 == last_number) {\n            // Step 4: If the current number is consecutive to the previous one, increment the counter.\n            cnt++;\n            last_number = nums[i];\n        } else if (nums[i] != last_number) {\n            // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n            cnt = 1;\n            last_number = nums[i];\n        }\n\n        // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n        if (cnt > longest) {\n            longest = cnt;\n        }\n    }\n\n    // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n    return longest;\n}\n\nint main() {\n    int nums[] = {100, 4, 200, 1, 3, 2};\n    int numsSize = sizeof(nums) / sizeof(nums[0]);\n    printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n    return 0;\n}\n\n```\n```Java []\n\nimport java.util.Arrays;\n\nclass Solution {\n    public int longestConsecutive(int[] nums) {\n        // Step 1: Sort the input array in ascending order.\n        Arrays.sort(nums);\n\n        // Step 2: Handle the base case when the array is empty.\n        if (nums.length == 0) {\n            return 0;\n        }\n\n        int last_number = Integer.MIN_VALUE; // Initialize a variable to track the last processed number.\n        int cnt = 0;                         // Initialize a counter for the current consecutive sequence length.\n        int longest = 1;                     // Initialize a variable to store the maximum consecutive sequence length.\n\n        // Step 3: Iterate through the sorted array.\n        for (int num : nums) {\n            if (num - 1 == last_number) {\n                // Step 4: If the current number is consecutive to the previous one, increment the counter.\n                cnt++;\n                last_number = num;\n            } else if (num != last_number) {\n                // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n                cnt = 1;\n                last_number = num;\n            }\n\n            // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n            longest = Math.max(longest, cnt);\n        }\n\n        // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n        return longest;\n    }\n}\n\n\n```\n```python []\nclass Solution:\n    def longestConsecutive(self, nums: List[int]) -> int:\n        # Step 1: Sort the input list in ascending order.\n        nums.sort()\n\n        # Step 2: Handle the base case when the list is empty.\n        if not nums:\n            return 0\n\n        last_number = float(\'-inf\')  # Initialize a variable to track the last processed number.\n        cnt = 0                      # Initialize a counter for the current consecutive sequence length.\n        longest = 1                  # Initialize a variable to store the maximum consecutive sequence length.\n\n        # Step 3: Iterate through the sorted list.\n        for num in nums:\n            if num - 1 == last_number:\n                # Step 4: If the current number is consecutive to the previous one, increment the counter.\n                cnt += 1\n                last_number = num\n            elif num != last_number:\n                # Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n                cnt = 1\n                last_number = num\n\n            # Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n            longest = max(longest, cnt)\n\n        # Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n        return longest\n\n\n```\n```Javascript []\n\nvar longestConsecutive = function(nums) {\n    // Step 1: Sort the input array in ascending order.\n    nums.sort((a, b) => a - b);\n\n    // Step 2: Handle the base case when the array is empty.\n    if (nums.length === 0) {\n        return 0;\n    }\n\n    let last_number = Number.MIN_SAFE_INTEGER; // Initialize a variable to track the last processed number.\n    let cnt = 0;                               // Initialize a counter for the current consecutive sequence length.\n    let longest = 1;                           // Initialize a variable to store the maximum consecutive sequence length.\n\n    // Step 3: Iterate through the sorted array.\n    for (let num of nums) {\n        if (num - 1 === last_number) {\n            // Step 4: If the current number is consecutive to the previous one, increment the counter.\n            cnt++;\n            last_number = num;\n        } else if (num !== last_number) {\n            // Step 5: If the current number is not consecutive, update \'cnt\' and \'last_number\'.\n            cnt = 1;\n            last_number = num;\n        }\n\n        // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n        longest = Math.max(longest, cnt);\n    }\n\n    // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n    return longest;\n};\n\n\n```\n\n---\n\n#### ***Approach 3: With  Unordered Set***\n\n1. It handles the base case when the vector is empty (size `n` is 0), returning 0 because there are no consecutive elements.\n\n1. It uses an unordered set `s` to store unique elements from the input vector, ensuring efficient lookup.\n\n1. It iterates through the elements of the unordered set and checks if each element `a` is the start of a sequence (no `a-1` in `s`).\n\n1. If `a` is the start of a sequence, it resets the counter `cnt` to 1 and initializes `x` to `a`. Then, it iterates to find consecutive elements by incrementing `x`.\n\n1. It updates the `longest` variable with the maximum of its current value and the `cnt` counter.\n\n1. After processing all elements in the unordered set, it returns `longest` as the result, representing the length of the longest consecutive sequence.\n\n#### Complexity\n- **Time complexity:**\n$$O(n)$$\n\n- **Space complexity:**\n$$O(n)$$\n\n#### Code\n```C++ []\nclass Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int n = nums.size();\n        \n        // Step 1: Handle the base case when the vector is empty.\n        if (n == 0) {\n            return 0;\n        }\n\n        unordered_set<int> s;   // Create an unordered set to store unique elements.\n        int cnt = 1;            // Initialize a counter for the current consecutive sequence length.\n        int longest = 1;        // Initialize a variable to store the maximum consecutive sequence length.\n\n        // Step 2: Insert all elements of \'nums\' into the unordered set \'s\'.\n        for (int i = 0; i < n; i++) {\n            s.insert(nums[i]);\n        }\n        \n        int x = 0;  // Initialize a variable to keep track of the current element being processed.\n\n        // Step 3: Iterate through the elements of the unordered set.\n        for (auto a : s) {\n            // Step 4: If the current element \'a\' is the start of a sequence (no \'a-1\' in \'s\'),\n            if (s.find(a - 1) == s.end()) {\n                cnt = 1;  // Reset the counter.\n                x = a;    // Update \'x\' to the current element \'a\'.\n\n                // Step 5: While consecutive elements exist in \'s\', increment \'cnt\' and \'x\'.\n                while (s.find(x + 1) != s.end()) {\n                    cnt++;\n                    x = x + 1;\n                }\n            }\n            \n            // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n            longest = max(longest, cnt);\n        }\n\n        // Step 7: Return \'longest\' as the result, representing the length of the longest consecutive sequence.\n        return longest;\n    }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\nstruct SetNode {\n    int key;\n    struct SetNode* next;\n};\n\nstruct HashSet {\n    struct SetNode** buckets;\n    int capacity;\n};\n\nstruct HashSet* createHashSet(int capacity) {\n    struct HashSet* set = (struct HashSet*)malloc(sizeof(struct HashSet));\n    set->capacity = capacity;\n    set->buckets = (struct SetNode**)malloc(sizeof(struct SetNode*) * capacity);\n    for (int i = 0; i < capacity; i++) {\n        set->buckets[i] = NULL;\n    }\n    return set;\n}\n\nint hash(int key, int capacity) {\n    return key % capacity;\n}\n\nvoid insert(struct HashSet* set, int key) {\n    int index = hash(key, set->capacity);\n    struct SetNode* newNode = (struct SetNode*)malloc(sizeof(struct SetNode));\n    newNode->key = key;\n    newNode->next = set->buckets[index];\n    set->buckets[index] = newNode;\n}\n\nint contains(struct HashSet* set, int key) {\n    int index = hash(key, set->capacity);\n    struct SetNode* current = set->buckets[index];\n    while (current != NULL) {\n        if (current->key == key) {\n            return 1;\n        }\n        current = current->next;\n    }\n    return 0;\n}\n\nvoid freeHashSet(struct HashSet* set) {\n    for (int i = 0; i < set->capacity; i++) {\n        struct SetNode* current = set->buckets[i];\n        while (current != NULL) {\n            struct SetNode* next = current->next;\n            free(current);\n            current = next;\n        }\n    }\n    free(set->buckets);\n    free(set);\n}\n\nint longestConsecutive(int* nums, int numsSize) {\n    // Step 1: Handle the base case when the array is empty.\n    if (numsSize == 0) {\n        return 0;\n    }\n\n    struct HashSet* set = createHashSet(numsSize);\n\n    // Step 2: Insert all elements of \'nums\' into the hash set \'set\'.\n    for (int i = 0; i < numsSize; i++) {\n        insert(set, nums[i]);\n    }\n\n    int cnt = 1;        // Initialize a counter for the current consecutive sequence length.\n    int longest = 1;    // Initialize a variable to store the maximum consecutive sequence length.\n\n    // Step 3: Iterate through the elements of \'nums\'.\n    for (int i = 0; i < numsSize; i++) {\n        int num = nums[i];\n        // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'set\'),\n        if (!contains(set, num - 1)) {\n            int x = num; // Update \'x\' to the current element \'num\'.\n\n            // Step 5: While consecutive elements exist in \'set\', increment \'cnt\' and \'x\'.\n            while (contains(set, x + 1)) {\n                cnt++;\n                x = x + 1;\n            }\n        }\n        \n        // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n        longest = (cnt > longest) ? cnt : longest;\n    }\n\n    // Step 7: Free the hash set and return \'longest\' as the result.\n    freeHashSet(set);\n    return longest;\n}\n\nint main() {\n    int nums[] = {100, 4, 200, 1, 3, 2};\n    int numsSize = sizeof(nums) / sizeof(nums[0]);\n    printf("Longest consecutive sequence length: %d\\n", longestConsecutive(nums, numsSize));\n    return 0;\n}\n\n```\n```Java []\nimport java.util.HashSet;\n\nclass Solution {\npublic int longestConsecutive(int[] nums) {\n// Step 1: Handle the base case when the array is empty.\nif (nums.length == 0) {\nreturn 0;\n}\n\n    HashSet<Integer> set = new HashSet<>();\n\n    // Step 2: Insert all elements of \'nums\' into the hash set \'set\'.\n    for (int num : nums) {\n        set.add(num);\n    }\n\n    int cnt = 1;        // Initialize a counter for the current consecutive sequence length.\n    int longest = 0;    // Initialize a variable to store the maximum consecutive sequence length.\n\n    // Step 3: Iterate through the elements of \'nums\'.\n    for (int num : nums) {\n        // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'set\'),\n        if (!set.contains(num - 1)) {\n            int x = num; // Update \'x\' to the current element \'num\'.\n            cnt = 1;\n            // Step 5: While consecutive elements exist in \'set\', increment \'cnt\' and \'x\'.\n            while (set.contains(x + 1)) {\n                cnt++;\n                x = x + 1;\n            }\n        }\n        \n        // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n        longest = Math.max(longest, cnt);\n    }\n\n    // Step 7: Return \'longest\' as the result.\n    return longest;\n}\n}\n\n\n```\n```python []\nclass Solution:\n    def longestConsecutive(self, nums: List[int]) -> int:\n        # Step 1: Handle the base case when the list is empty.\n        if not nums:\n            return 0\n\n        num_set = set(nums)\n\n        cnt = 1           # Initialize a counter for the current consecutive sequence length.\n        longest = 1       # Initialize a variable to store the maximum consecutive sequence length.\n\n        # Step 3: Iterate through the elements of \'nums\'.\n        for num in nums:\n            # Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'num_set\'),\n            if num - 1 not in num_set:\n                x = num      # Update \'x\' to the current element \'num\'.\n\n                # Step 5: While consecutive elements exist in \'num_set\', increment \'cnt\' and \'x\'.\n                while x + 1 in num_set:\n                    cnt += 1\n                    x += 1\n            \n            # Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n            longest = max(longest, cnt)\n\n        # Step 7: Return \'longest\' as the result.\n        return longest\n\n\n```\n```Javascript []\nvar longestConsecutive = function(nums) {\n    // Step 1: Handle the base case when the array is empty.\n    if (nums.length === 0) {\n        return 0;\n    }\n\n    let numSet = new Set(nums);\n\n    let cnt = 1;        // Initialize a counter for the current consecutive sequence length.\n    let longest = 1;    // Initialize a variable to store the maximum consecutive sequence length.\n\n    // Step 3: Iterate through the elements of \'nums\'.\n    for (let num of nums) {\n        // Step 4: If the current element \'num\' is the start of a sequence (no \'num-1\' in \'numSet\'),\n        if (!numSet.has(num - 1)) {\n            let x = num;  // Update \'x\' to the current element \'num\'.\n\n            // Step 5: While consecutive elements exist in \'numSet\', increment \'cnt\' and \'x\'.\n            while (numSet.has(x + 1)) {\n                cnt++;\n                x++;\n            }\n        }\n        \n        // Step 6: Update \'longest\' with the maximum of \'longest\' and \'cnt\'.\n        longest = Math.max(longest, cnt);\n    }\n\n    // Step 7: Return \'longest\' as the result.\n    return longest;\n};\n\n\n```\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---
['Array', 'Hash Table', 'Union Find', 'C', 'Ordered Set', 'Python', 'C++', 'Java', 'JavaScript']