Problem Description
Given an integer array nums, find the length of the longest square streak. A square streak is defined as a subsequence of at least two numbers that, after sorting the subsequence, forms a sequence where each element (except the first) is the square of the previous one. If no such streak exists, return -1.
Key Insights
- Convert nums into a set for O(1) lookups.
- For each number, build a chain by repeatedly squaring the current number if the square exists in the set.
- To avoid redundant computation, only consider a number as a starting point if it is not the square of another number present in the set.
- Since the maximum chain length is naturally limited by exponential growth, the algorithm runs efficiently even with large inputs.
Space and Time Complexity
Time Complexity: O(n * k) where n is the number of unique elements and k is the maximum chain length (which is small due to exponential growth).
Space Complexity: O(n) due to using a set for lookups.
Solution
We first create a set from nums to allow fast existence checks. Then for each unique number, we check if it can be a starting point by verifying that it is not the square of another number already present in the set. Starting from each valid candidate, we form a sequence by repeatedly checking and moving to its square. We keep track of the maximum length found. If the maximum is at least 2, we return it; otherwise, we return -1.