Longest Square Streak in an Array - 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.

Return the length of the longest square streak in nums, or return -1 if there is no square streak.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Perfect Square Chain
$ Input: nums = [4,3,6,16,8,2]
Output: 3
💡 Note: We can form the square streak [2,4,16]: 2² = 4, 4² = 16. The longest streak has length 3.
Example 2 — No Valid Streak
$ Input: nums = [2,3,5,6,7]
Output: -1
💡 Note: No number in the array has its square also in the array, so no square streak can be formed.
Example 3 — Multiple Short Streaks
$ Input: nums = [2,4,8,16]
Output: 2
💡 Note: We can form [2,4] and [4,16] but not [2,4,16] since 4² = 16 but 2² = 4 ≠ 8. Max length is 2.

Constraints

  • 2 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Longest Square Streak: [4,3,6,16,8,2]4361682Find square relationships: which numbers are squares of others?24162² = 44² = 1616² = 256 ✗Square streak found: 2 → 4 → 16Output: 3 (length of longest streak)
Understanding the Visualization
1
Input Array
Array of integers that may contain square relationships
2
Find Chains
Identify sequences where each number is square of previous
3
Return Length
Length of longest valid chain, or -1 if none exist
Key Takeaway
🎯 Key Insight: Use hash set for O(1) lookups and build chains by squaring numbers until no next square exists
Asked in
Meta 15 Google 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen