Longest Square Streak in an Array - Problem
You're given an integer array nums, and your task is to find the longest square streak within it!
A square streak is a special subsequence where:
- It contains at least 2 elements
- When sorted, each element (except the first) is the perfect square of the previous element
For example, in the sequence [2, 4, 16], we have: 2 → 4 (2²) → 16 (4²)
Goal: Return the length of the longest square streak, or -1 if no valid streak exists.
Note: A subsequence can be formed by removing some elements without changing the order of remaining elements.
Input & Output
example_1.py — Perfect Square Chain
$
Input:
[4, 3, 6, 16, 8, 2]
›
Output:
3
💡 Note:
The longest square streak is [2, 4, 16] with length 3. Chain: 2 → 4 (2²) → 16 (4²)
example_2.py — No Valid Chain
$
Input:
[2, 3, 5, 6, 7]
›
Output:
-1
💡 Note:
No number in the array is a perfect square of another number, so no square streak exists
example_3.py — Single Valid Pair
$
Input:
[4, 16, 256, 65536]
›
Output:
4
💡 Note:
Complete chain: 4 → 16 (4²) → 256 (16²) → 65536 (256²) has length 4
Constraints
- 2 ≤ nums.length ≤ 105
- 2 ≤ nums[i] ≤ 105
- All values in nums are unique
- A subsequence can be formed by removing elements without changing order
Visualization
Tap to expand
Understanding the Visualization
1
Identify Building Blocks
We have blocks: [4, 3, 6, 16, 8, 2]
2
Find Foundation Blocks
Only start from blocks that aren't squares of others: 2 and 3 are foundations
3
Build from Foundation 2
2 → 4 (2²=4) → 16 (4²=16). Tower height: 3
4
Try Foundation 3
3 → ? (3²=9, not available). Tower height: 1
Key Takeaway
🎯 Key Insight: Start building only from 'foundation' numbers - those that aren't perfect squares of existing numbers. This finds each tower exactly once and gives us the optimal solution!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code