Remove One Element to Form a Sorted Sequence - Count Valid Removals

viaGlassdoor

Problem: Given an array of integers, you may remove exactly one element. Count how many distinct valid sorted (strictly increasing) sequences can be formed by removing exactly one element.

Constraints: Array can contain duplicates; must reason about ties carefully.

Example: Input: [1,2,3,4,5,4] -> Output: 2 ([1,2,3,4,4] by removing the 5, and [1,2,3,4,5] by removing the second 4) Input: [1,2,3,4,2] -> Output: 1 ([1,2,3,4] by removing the trailing 2) Input: [5,3,4,2] -> Output: 0 (no single removal produces a strictly increasing sequence)

Approach: Find the first index where the strictly-increasing property breaks (arr[i] >= arr[i+1] or a later violation). Try removing arr[i] and check if the rest is strictly increasing; try removing arr[i+1] and check similarly - each is a valid sequence if it works, giving at most 2 candidates from the first violation point. Verify both candidate removals in O(n), for overall O(n) time. Note: the assumption that the answer is always 0, 1, or 2 holds only when the array has at most one 'bad point' - with multiple separate violations elsewhere in the array a single removal generally cannot fix all of them, so the count degrades to 0 in those cases rather than exceeding 2.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account