Leetcode 2501: Longest Square Streak in an Array

grid47
grid47
Exploring patterns and algorithms
Mar 1, 2024 6 min read

You are given an integer array nums. A subsequence of nums is called a square streak if its length is at least 2, and after sorting the subsequence, each element (except the first one) is the square of the previous number. Return the length of the longest square streak in nums, or -1 if no square streak exists.
Problem
Approach
Steps
Complexity
Input: You are given an array nums, where each element is a positive integer.
Example: Input: nums = [9,3,16,2,4,81]
Constraints:
• 2 <= nums.length <= 10^5
• 2 <= nums[i] <= 10^5
Output: Return the length of the longest subsequence that forms a square streak. If no such subsequence exists, return -1.
Example: Output: 3
Constraints:
• If no subsequence satisfies the conditions, return -1.
Goal: Find the longest subsequence where each element (except the first) is the square of the previous one.
Steps:
• 1. Sort the array to easily check the relationship between elements.
• 2. Use dynamic programming to store the longest square streak for each element.
• 3. Iterate over the array, check for the condition where an element is the square of the previous one.
• 4. Keep track of the maximum length of any such subsequence.
Goal: The input array nums follows the given size and element constraints.
Steps:
• The length of nums is between 2 and 10^5.
• Each element in nums is between 2 and 10^5.
Assumptions:
• There are no duplicate numbers in the array.
• The array contains at least two elements.
Input: Input: nums = [9, 3, 16, 2, 4, 81]
Explanation: In this example, the subsequence [4, 16, 81] is a square streak. After sorting, it becomes [4, 16, 81], where 16 = 4 * 4 and 81 = 16 * 16. Therefore, the longest square streak has a length of 3.

Input: Input: nums = [5, 2, 3, 7]
Explanation: There is no subsequence that satisfies the square streak condition, so the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus