← Salesforce Interview Insights
The core scan isn't hard once you know to go right to left looking for a drop.
To find the lexicographically largest permutation strictly smaller than the input using exactly one swap, scan from right to left to find the first position where a smaller element exists to its right. Then, swap it with the largest element to its right that is still smaller than it, ensuring the result is as large as possible while remaining smaller. If no such position exists, return the original array.
Pro tip: Clarify that the swap must be exactly one swap and the result must be strictly smaller; this avoids off-by-one errors and ensures you handle edge cases like already minimal permutations. Also, mention that the algorithm runs in O(n) time, which is optimal.
Restate the problem: find the lexicographically largest permutation strictly smaller than the input using exactly one swap. Confirm that if no such permutation exists, return the original array.
Scan the array from right to left to find the first index i where there exists an element to its right that is smaller than arr[i]. This is the position where a swap can produce a smaller permutation.
Among elements to the right of i, find the largest element that is still smaller than arr[i]. If there are duplicates, choose the rightmost occurrence to maximize the resulting permutation.
Swap arr[i] with the chosen element. The resulting array is the lexicographically largest permutation strictly smaller than the input. If no such i exists, return the original array.
Discuss time complexity O(n) and space O(1). Mention edge cases: array of size 1, strictly increasing array (no swap possible), and arrays with duplicates.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.