In the Find All Good Indices interview question, you are given an array nums and an integer k. An index i is called "good" if:
i are in non-increasing order.i are in non-decreasing order.
You need to return a sorted list of all such good indices.Goldman Sachs and ByteDance use this to test your ability to perform efficient preprocessing. Checking the -neighborhood for every index from scratch would take , which is too slow. It evaluation your proficiency with the Dynamic Programming interview pattern or Prefix Sum interview pattern to precalculate the lengths of monotonic sequences at every position.
This problem uses Precomputation with two arrays:
before[i]: The length of the non-increasing sequence ending at .after[i]: The length of the non-decreasing sequence starting at .
You build these in linear time. For before, if nums[i-1] <= nums[i-2], then before[i] = before[i-1] + 1. Similarly for after. Once you have these arrays, an index is "good" if both before[i] >= k and after[i] >= k.nums = [2, 1, 1, 1, 3, 4, 1], .
before:
after:
before[2]=2, after[2]=3. Since both , index 2 is good.before[3]=2, after[3]=2. Since both , index 3 is good.When a problem requires checking properties of ranges centered at every index, always think: "Can I precalculate this property from the left and from the right separately?" This "Two-Pass" preprocessing is a vital Array interview pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Good Days to Rob the Bank | Medium | Solve | |
| Largest Sum of Averages | Medium | Solve | |
| Maximum Strength of K Disjoint Subarrays | Hard | Solve | |
| Maximum Value of K Coins From Piles | Hard | Solve | |
| Merge Operations for Minimum Travel Time | Hard | Solve |