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: 3
💡 Note: We can form the square streak [2,4,16]: 2² = 4, 4² = 16. The longest streak has length 3.

Constraints

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

Visualization

Tap to expand
Longest Square Streak in an Array INPUT nums = [4, 3, 6, 16, 8, 2] 4 3 6 16 8 2 0 1 2 3 4 5 Hash Set Created: {2, 3, 4, 6, 8, 16} Sorted for Processing: 2 3 4 6 8 16 Highlighted: Square streak elements ALGORITHM STEPS 1 Create Hash Set Store all nums for O(1) lookup 2 Sort Array Process smallest first 3 Find Square Streaks Check if n*n exists in set 4 Track Max Length Update longest streak found Square Chain from 2: 2 4 16 2^2=4 4^2=16 Length = 3 (Longest!) FINAL RESULT Longest Square Streak Found: 3 Winning Streak: 2 --> 4 --> 16 Verification: 2 * 2 = 4 [OK] 4 * 4 = 16 [OK] Output: 3 Key Insight: Using a Hash Set allows O(1) lookup to check if the square of a number exists in the array. By sorting first, we ensure we start chains from smallest numbers, avoiding duplicate calculations. TutorialsPoint - Longest Square Streak in an Array | Hash Set Optimization
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