Longest Square Streak in an Array — LeetCode 2501 Python Solution

MediumArrayHash TableBinary SearchDynamic ProgrammingSorting
Problem
#2501
Reading time
2 min

The problem

You are given an integer array nums. A subsequence of nums is called a square streak if: The length of the subsequence is at least 2, and after sorting the subsequence, each element (except the first element) is the square of the previous number.

Example

Input
nums = [4,3,6,16,8,2]
Output
3
Explanation
Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].

Python solution

Python
class Solution:
    def longestSquareStreak(self, nums: List[int]) -> int:
        s = set(nums)
        ans = -1
        for x in nums:
            t = 0
            while x in s:
                x *= x
                t += 1
            if t > 1:
                ans = max(ans, t)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log \log M)
SpaceO(n) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 2501. Longest Square Streak in an Array is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2501. Longest Square Streak in an Array?
LeetCode 2501. Longest Square Streak in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2501. Longest Square Streak in an Array?
The Python solution on this page runs in O(n \times \log \log M).
What is the space complexity of LeetCode 2501. Longest Square Streak in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2501. Longest Square Streak in an Array cover?
LeetCode 2501. Longest Square Streak in an Array is tagged Array, Hash Table, Binary Search, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview