✅ Explained step by step | Beats 100% | ✅ Working 28.10.2024
\npython3 []\nclass Solution:\n    def longestSquareStreak(self, nums: List[int]) ->int:\n        # Convert nums to a sorted set to remove duplicates and have o
\n```python3 []\nclass Solution:\n    def longestSquareStreak(self, nums: List[int]) ->int:\n        # Convert nums to a sorted set to remove duplicates and have ordered numbers\n        nums = sorted(set(nums))\n        \n        # Create a set for O(1) lookup time\n        num_set = set(nums)\n        \n        # Track the maximum streak length found\n        max_length = 0\n        \n        # Iterate through each number in sorted order\n        for num in nums:\n            # Initialize streak length for current number\n            length = 0\n            # Start with current number\n            current = num\n            \n            # Keep squaring the number while it exists in our set\n            while current in num_set:\n                length += 1\n                current = current ** 2\n            \n            # Only update max_length if we found a streak of length > 1\n            if length > 1:\n                max_length = max(max_length, length)\n        \n        # Return max_length if we found a valid streak, otherwise return -1\n        return max_length if max_length > 1 else -1\n```\n```cpp []\nclass Solution {\npublic:\n    int longestSquareStreak(vector<int>& nums) {\n        // Convert nums to a sorted set to remove duplicates and have ordered numbers\n        set<long long> num_set;\n        for (int num : nums) {\n            num_set.insert(num);\n        }\n        \n        // Track the maximum streak length found\n        int max_length = 0;\n        \n        // Iterate through each number in sorted order\n        for (long long num : num_set) {\n            // Initialize streak length for current number\n            int length = 0;\n            // Start with current number\n            long long current = num;\n            \n            // Keep squaring the number while it exists in our set\n            while (num_set.find(current) != num_set.end()) {\n                length++;\n                if (current > 100000) break; // Prevent overflow\n                current = current * current;\n            }\n            \n            // Only update max_length if we found a streak of length > 1\n            if (length > 1) {\n                max_length = max(max_length, length);\n            }\n        }\n        \n        // Return max_length if we found a valid streak, otherwise return -1\n        return max_length > 1 ? max_length : -1;\n    }\n};\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n    public int longestSquareStreak(int[] nums) {\n        // Convert array to TreeSet to remove duplicates and have ordered numbers\n        TreeSet<Integer> sortedSet = new TreeSet<>();\n        for (int num : nums) {\n            sortedSet.add(num);\n        }\n        \n        // Create HashSet for O(1) lookup time\n        HashSet<Integer> numSet = new HashSet<>(sortedSet);\n        \n        // Track the maximum streak length found\n        int maxLength = 0;\n        \n        // Iterate through each number in sorted order\n        for (int num : sortedSet) {\n            // Initialize streak length for current number\n            int length = 0;\n            // Start with current number\n            long current = num;\n            \n            // Keep squaring the number while it exists in our set\n            while (current <= Integer.MAX_VALUE && numSet.contains((int)current)) {\n                length++;\n                current = current * current;\n            }\n            \n            // Only update maxLength if we found a streak of length > 1\n            if (length > 1) {\n                maxLength = Math.max(maxLength, length);\n            }\n        }\n        \n        // Return maxLength if we found a valid streak, otherwise return -1\n        return maxLength > 1 ? maxLength : -1;\n    }\n}\n```\n```csharp []\npublic class Solution {\n    public int LongestSquareStreak(int[] nums) {\n        // Convert nums to a sorted set to remove duplicates and have ordered numbers\n        var numSet = new HashSet<int>(nums);\n        var sortedNums = numSet.OrderBy(x => x).ToList();\n        \n        // Track the maximum streak length found\n        int maxLength = 0;\n        \n        // Iterate through each number in sorted order\n        foreach (int num in sortedNums) {\n            // Initialize streak length for current number\n            int length = 0;\n            // Start with current number\n            long current = num;\n            \n            // Keep squaring the number while it exists in our set\n            while (current <= int.MaxValue && numSet.Contains((int)current)) {\n                length++;\n                current = current * current;\n            }\n            \n            // Only update maxLength if we found a streak of length > 1\n            if (length > 1) {\n                maxLength = Math.Max(maxLength, length);\n            }\n        }\n        \n        // Return maxLength if we found a valid streak, otherwise return -1\n        return maxLength > 1 ? maxLength : -1;\n    }\n}\n```\n```golang []\nfunc longestSquareStreak(nums []int) int {\n    // Create a map for O(1) lookup time\n    numSet := make(map[int]bool)\n    \n    // Remove duplicates and add to map\n    for _, num := range nums {\n        numSet[num] = true\n    }\n    \n    // Track the maximum streak length found\n    maxLength := 0\n    \n    // Iterate through each number\n    for num := range numSet {\n        length := 0\n        current := num\n        \n        // Keep squaring the number while it exists in our map\n        for numSet[current] {\n            length++\n            // Check if squaring would overflow int\n            if current > 46340 { // sqrt(MaxInt32) \u2248 46340\n                break\n            }\n            current *= current\n        }\n        \n        // Only update maxLength if we found a streak of length > 1\n        if length > 1 {\n            maxLength = max(maxLength, length)\n        }\n    }\n    \n    // Return maxLength if we found a valid streak, otherwise return -1\n    if maxLength > 1 {\n        return maxLength\n    }\n    return -1\n}\n\n// Helper function for max\nfunc max(a, b int) int {\n    if a > b {\n        return a\n    }\n    return b\n}\n```\n```swift []\nclass Solution {\n    func longestSquareStreak(_ nums: [Int]) -> Int {\n        // Convert nums to a sorted set to remove duplicates and have ordered numbers\n        let sortedNums = Array(Set(nums)).sorted()\n        \n        // Create a set for O(1) lookup time\n        let numSet = Set(nums)\n        \n        // Track the maximum streak length found\n        var maxLength = 0\n        \n        // Iterate through each number in sorted order\n        for num in sortedNums {\n            // Initialize streak length for current number\n            var length = 0\n            // Start with current number\n            var current = num\n            \n            // Keep squaring the number while it exists in our set\n            while numSet.contains(current) {\n                length += 1\n                // Need to handle potential integer overflow\n                let nextSquare = current * current\n                if nextSquare > Int.max {\n                    break\n                }\n                current = nextSquare\n            }\n            \n            // Only update maxLength if we found a streak of length > 1\n            if length > 1 {\n                maxLength = max(maxLength, length)\n            }\n        }\n        \n        // Return maxLength if we found a valid streak, otherwise return -1\n        return maxLength > 1 ? maxLength : -1\n    }\n}\n```\n```javascript [JS]\n// JavaScript\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSquareStreak = function(nums) {\n    // Convert nums to a sorted set to remove duplicates and have ordered numbers\n    const numSet = new Set(nums);\n    \n    // Track the maximum streak length found\n    let maxLength = 0;\n    \n    // Iterate through each number in the set\n    for (let num of numSet) {\n        // Initialize streak length for current number\n        let length = 0;\n        // Start with current number\n        let current = num;\n        \n        // Keep squaring the number while it exists in our set\n        while (numSet.has(current)) {\n            length++;\n            if (current > 100000) break; // Prevent overflow\n            current = current * current;\n        }\n        \n        // Only update maxLength if we found a streak of length > 1\n        if (length > 1) {\n            maxLength = Math.max(maxLength, length);\n        }\n    }\n    \n    // Return maxLength if we found a valid streak, otherwise return -1\n    return maxLength > 1 ? maxLength : -1;\n};\n```\n```typescript [TS]\n// TypeScript\n\n\n\nfunction longestSquareStreak(nums: number[]): number {\n    // Convert nums to a sorted set to remove duplicates and have ordered numbers\n    const numSet = new Set(nums);\n    const sortedNums = Array.from(numSet).sort((a, b) => a - b);\n    \n    // Track the maximum streak length found\n    let maxLength = 0;\n    \n    // Iterate through each number in sorted order\n    for (const num of sortedNums) {\n        // Initialize streak length for current number\n        let length = 0;\n        // Start with current number\n        let current = num;\n        \n        // Keep squaring the number while it exists in our set\n        while (numSet.has(current)) {\n            length++;\n            current = current ** 2;\n            \n            // Add safety check for numbers getting too large\n            if (current > 100000) break;\n        }\n        \n        // Only update maxLength if we found a streak of length > 1\n        if (length > 1) {\n            maxLength = Math.max(maxLength, length);\n        }\n    }\n    \n    // Return maxLength if we found a valid streak, otherwise return -1\n    return maxLength > 1 ? maxLength : -1;\n}\n```\n```rust []\nuse std::collections::HashSet;\n\nimpl Solution {\n    pub fn longest_square_streak(nums: Vec<i32>) -> i32 {\n        // Convert to HashSet and sort\n        let mut unique_nums: Vec<i64> = nums.into_iter()\n            .map(|x| x as i64)\n            .collect::<HashSet<_>>()\n            .into_iter()\n            .collect();\n        unique_nums.sort_unstable();\n        \n        // Create HashSet for O(1) lookup\n        let num_set: HashSet<i64> = unique_nums.iter().cloned().collect();\n        \n        // Track maximum streak length\n        let mut max_length = 0;\n        \n        // Check each number\n        for &num in &unique_nums {\n            let mut length = 0;\n            let mut current = num;\n            \n            // Keep squaring while number exists in set\n            while num_set.contains(&current) {\n                length += 1;\n                // Check if squaring would overflow\n                if current > (1i64 << 31) {\n                    break;\n                }\n                current *= current;\n            }\n            \n            // Update max_length if streak length > 1\n            if length > 1 {\n                max_length = max_length.max(length);\n            }\n        }\n        \n        if max_length > 1 {\n            max_length\n        } else {\n            -1\n        }\n    }\n}\n```\n```ruby []\n# @param {Integer[]} nums\n# @return {Integer}\ndef longest_square_streak(nums)\n    # Convert nums to a sorted set to remove duplicates and have ordered numbers\n    nums = nums.uniq.sort\n    \n    # Create a set for O(1) lookup time\n    num_set = nums.to_set\n    \n    # Track the maximum streak length found\n    max_length = 0\n    \n    # Iterate through each number in sorted order\n    nums.each do |num|\n        # Initialize streak length for current number\n        length = 0\n        # Start with current number\n        current = num\n        \n        # Keep squaring the number while it exists in our set\n        while num_set.include?(current)\n            length += 1\n            current = current ** 2\n        end\n        \n        # Only update max_length if we found a streak of length > 1\n        if length > 1\n            max_length = [max_length, length].max\n        end\n    end\n    \n    # Return max_length if we found a valid streak, otherwise return -1\n    max_length > 1 ? max_length : -1\nend\n```\n\n\n### Complexity \n- Time complexity: O(n * log m)\n\n- Space complexity: O(n)\n\n\n![image.png](https://assets.leetcode.com/users/images/9dc1b265-b175-4bf4-bc6c-4b188cb79220_1728176037.4402142.png)\n\n\n## Explained step by step\n\n---\n\n1. Input Processing:\n```\nnums = sorted(set(nums))\nnum_set = set(nums)\n```\n\n- Converts input array to a sorted set to remove duplicates\n- Creates a separate set for O(1) lookups\n2. Initialization:\n```\nmax_length = 0\n```\n\n- Sets up a variable to track the longest valid streak found\n3. Main Logic:\n```\nfor num in nums:\n    length = 0\n    current = num\n    while current in num_set:\n        length += 1\n        current = current ** 2\n```\n\n\n- Iterates through each number\n- For each number, keeps squaring it while the result exists in the set\n- Counts the length of the streak\n4. Streak Validation:\n```\nif length > 1:\n    max_length = max(max_length, length)\n```\n- Only considers streaks with length > 1\n- Updates max_length if current streak is longer\n5. Final Result:\n```\nreturn max_length if max_length > 1 else -1\n```\n\n- Returns the longest streak if found (> 1)\n- Returns -1 if no valid streak exists\n\n---\n\n![image.png](https://assets.leetcode.com/users/images/19ec92eb-d554-40ee-a31b-cab8c26b03e6_1730074848.810665.png)\n![image.png](https://assets.leetcode.com/users/images/e00c463d-1fe1-4a51-8d5a-ac51865d1544_1730075525.0950522.png)\n\n
['Swift', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']