Simple O(n) solution
IntuitionPut all numbers into map with counter.For each number we calc it's double (next) and sqrt (previous) elements.If we already had previous or next number
# Intuition

Put all numbers into map with counter.

For each number we calc it's double (next) and sqrt (previous) elements.

If we already had previous or next numbers: we get their counts, sum and store back into map.

Resulting counter will always converge to needed sequence length no matter the order of when numbers appear.

*Note: this only works because max sequence length is 5*

# Complexity
- Time complexity: **O(n)**

- Space complexity: **O(n)**

# Code
```java []
class Solution {
    public int longestSquareStreak(int[] nums) {
        var map = new HashMap<Integer, Integer>(); // [number, sequenceLength]
        int res = 0;
        for (var num : nums) {
            if (map.containsKey(num)) { // no need to evaluate already processed number
                continue;
            }

            int numDouble = 0;
            if ((long)num * num < 100001) { // prevent overflow
                numDouble = num * num;
            }

            int sqrt = 0;
            double tmp2 = Math.sqrt(num);
            if (tmp2 == (int)tmp2) {
                sqrt = (int)tmp2;
            }

            int count = 1;
            if (numDouble != 0) count += map.getOrDefault(numDouble,0);
            if (sqrt != 0) count += map.getOrDefault(sqrt,0);
            map.put(num, count);

            // store counter only for values that exist in map
            if (numDouble != 0 && map.containsKey(numDouble)) map.put(numDouble, count);
            if (sqrt != 0 && map.containsKey(sqrt)) map.put(sqrt, count);
            res = Math.max(res, count);
        }
        return res == 1 ? -1 : res;
    }
}

```
['Java']