✅ Simple Swift O(n) Solution | Easy To Understand
Approach\nTo solve this problem, we can take the following approach:\n1. Convert the given array into a set. This reduces the time complexity of searching for e
# Approach\nTo solve this problem, we can take the following approach:\n1. Convert the given array into a `set`. This reduces the time complexity of searching for elements in the array from $$O(n)$$ to $$O(1)$$.\n2. Initialize a variable `longestStreak` to `0`, which will store the length of the longest consecutive sequence that we find.\n3. Iterate over the elements in the `set`.\n4. For each element, check if the `set` contains the previous integer `num - 1`. If it does not, then this `num` is the starting point of a consecutive sequence.\n5. Initialize two variables `currentNum` and `currentStreak` to the value of `num` and `1` respectively. `currentStreak` represents the length of the current consecutive sequence that we are examining.\n6. While the `set` contains the next integer `currentNum + 1`, increment `currentNum` and `currentStreak`.\n7. If the `currentStreak` is greater than the `longestStreak`, update the value of `longestStreak` to `currentStreak`.\n8. Repeat steps 4 to 7 for all elements in the `set`.\n9. Return the value of `longestStreak`.\n\n\n# Complexity\nThe *time complexity* of the given solution is $$O(n)$$, where $$n$$ is the number of elements in the input array.\n\nThe *space complexity* of the given solution is $$O(n)$$ where $$n$$ is the number of elements in the input array.\n\n# Code\n```\nclass Solution {\n    func longestConsecutive(_ nums: [Int]) -> Int {\n        let set = Set(nums)\n        var longestStreak = 0\n\n        for num in set {\n            if !set.contains(num - 1) {\n                var currentNum = num\n                var currentStreak = 1\n\n                while set.contains(currentNum + 1) {\n                    currentNum += 1\n                    currentStreak += 1\n                }\n\n                longestStreak = max(longestStreak, currentStreak)\n            }\n        }\n\n        return longestStreak\n    }\n}\n```\n\n# Upvote ^^\n\n![upvote.png](https://assets.leetcode.com/users/images/fca8d363-9250-40c9-87e6-b6cde82d5257_1681816250.3088403.png)\n
['Array', 'Swift']