Input: nums =[4,3,6,16,8,2]Output: 3Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].-4=2*2.-16=4*4.Therefore,[4,16,2]is a square streak.It can be shown that every subsequence of length 4is not a square streak.
Example 2:
1
2
3
Input: nums =[2,3,5,6,7]Output: -1Explanation: There is no square streak in nums so return-1.
classSolution:
deflongestSquareStreak(self, nums: List[int]) -> int:
nums.sort()
num_set = set(nums)
ans =-1for num in nums:
if num notin num_set:
continue ln =0 curr = num
while curr in num_set:
ln +=1 num_set.remove(curr)
curr = curr * curr
if curr > (1<<31) -1: # avoid overflow, equivalent to Integer.MAX_VALUEbreakif ln >=2:
ans = max(ans, ln)
return ans
O(n log n) for sorting the array nums and then adding elements to set takes O(n) time, and finally checking subsequence roughly takes O(n) time as we are making quadratic jumps to find the next power.
🧺 Space complexity: O(n), for storing elements in a set.