Longest Square Streak in an Array — LeetCode 2501 Python Solution
- Problem
- #2501
- Pattern
- Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log \log M) |
| Space | O(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.