Leetcode 2420: Find All Good Indices

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

Given an integer array nums of size n and a positive integer k, find all good indices in the array. An index i is considered good if: The k elements just before it are in non-increasing order, and the k elements just after it are in non-decreasing order. Return a list of all good indices in increasing order.
Problem
Approach
Steps
Complexity
Input: You are given an array nums of integers and a positive integer k.
Example: nums = [3,2,2,2,5,6,2], k = 2
Constraints:
• 3 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^6
• 1 <= k <= n / 2
Output: Return an array containing all good indices sorted in increasing order.
Example: Output: [2, 3]
Constraints:
Goal: Identify the indices where the k elements before and after it satisfy the non-increasing and non-decreasing conditions, respectively.
Steps:
• 1. Initialize two arrays dp1 and dp2, where dp1 tracks the length of non-increasing subsequences before each index and dp2 tracks non-decreasing subsequences after each index.
• 2. Traverse the array to fill dp1 and dp2.
• 3. Loop through the indices from k to n-k and check the conditions for good indices.
• 4. Collect and return the indices that satisfy the conditions.
Goal: The solution should work efficiently even for large arrays, up to 100,000 elements.
Steps:
• Ensure the algorithm handles large arrays of up to 100,000 elements efficiently.
Assumptions:
• The array will contain at least 3 elements, and the value of k will be such that k <= n / 2.
Input: Input: nums = [3, 2, 2, 2, 5, 6, 2], k = 2
Explanation: Indices 2 and 3 are good because the elements before them form non-increasing sequences and the elements after them form non-decreasing sequences.

Link to LeetCode Lab


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