Min Elements to Remove to Make Almost Sorted Array
Updated
Problem statement
An array of integers is almost sorted if at most one element can be deleted from it to make it perfectly sorted, ascending.
For example, arrays [2, 1, 7], [13, 9, 2], and [1, 5, 6] are almost sorted because they have 0 or 1 elements out of place.
The arrays [4, 2, 1] and [1, 2, 6, 4, 3] are not because they have more than one element out of place.
Given an array of n unique integers, determine the minimum number of elements to remove so that it becomes almost sorted.
Function
minElementsToRemove(arr: int[]) → intExamples
Example 1
arr = [3, 4, 2, 5, 1]return = 1
Remove 2 to get arr' = [3, 4, 5, 1] or
remove 1 to get arr' = [3, 4, 2, 5], both of which are almost sorted.
The minimum number of elements that must be removed in this case is 1.
More Salesforce interview questions
- Count Subarrays With Product Equal to KOA · Seen Nov 2026
- Get Minimum TimeOA · Seen Nov 2026
- Count Increasing TripletsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Reverse a Sublist of a Linked ListONSITE INTERVIEW · Seen Nov 2026
- Rotting OrangesONSITE INTERVIEW · Seen Nov 2026
- 3Sum SmallerONSITE INTERVIEW · Seen Nov 2026
- Count Zero Request ServersONSITE INTERVIEW · Seen Nov 2026
- Minimum No-Repeat Segments After One Character RemovalOA · Seen Nov 2026
- Get Message StatusOA · Seen Nov 2026
Similar questions at other companies
- Split Array to Minimize the Largest SumInfosys · OAInfosys interview questions
- Split Array Largest SumAuxoAI · OA
- Maximum Non-Decreasing Array LengthVisa · OAVisa interview questions
- Maximize Array Beauty After DeletionsPoint72 · OAPoint72 interview questions
- Allocate Wells for Fair DistributionWells Fargo · OAWells Fargo interview questions
- Longest Increasing Price SubsequenceOpenAI · OAOpenAI interview questions
- Fill a Time Window with SongsMicrosoft · OAMicrosoft interview questions
- Longest Increasing Subsequence from Two ArraysSquarepoint Capital · OASquarepoint Capital interview questions
- Split Array Largest SumLinkedIn · OALinkedIn interview questions
- Longest Increasing SubsequenceAtlassian · OAAtlassian interview questions