Implement cocktail shaker sort and analyze
Company: UiPath
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of sorting algorithms and algorithmic optimization, specifically implementation and enhancement of cocktail shaker sort, plus analysis of time and space complexity, stability, and counts of comparisons and swaps.
Constraints
- 0 <= len(arr) <= 10^4
- -10^9 <= arr[i] <= 10^9
- Sort in ascending order
- Must be a stable, in-place sort (cocktail shaker / bidirectional bubble sort)
- Do not mutate the caller's input list
Examples
Input: ([5, 1, 4, 2, 8, 0, 2],)
Expected Output: [0, 1, 2, 2, 4, 5, 8]
Explanation: General unsorted array with a duplicate (two 2s); stable sort keeps equal elements' relative order.
Input: ([],)
Expected Output: []
Explanation: Empty array returns empty — guarded by the n <= 1 early return.
Input: ([42],)
Expected Output: [42]
Explanation: Single element is already sorted.
Input: ([3, 3, 3, 3],)
Expected Output: [3, 3, 3, 3]
Explanation: All duplicates: no strict-greater comparisons fire, so early termination exits after one swap-free pass.
Input: ([1, 2, 3, 4, 5],)
Expected Output: [1, 2, 3, 4, 5]
Explanation: Already sorted — best case, terminates after a single forward pass with zero swaps (O(n)).
Input: ([5, 4, 3, 2, 1],)
Expected Output: [1, 2, 3, 4, 5]
Explanation: Reverse sorted — worst case for swaps; bidirectional passes still settle it correctly.
Input: ([-3, -1, -7, 0, 2, -2],)
Expected Output: [-7, -3, -2, -1, 0, 2]
Explanation: Negative and positive mix sorted ascending.
Input: ([2, 1],)
Expected Output: [1, 2]
Explanation: Two-element boundary case requiring exactly one swap.
Hints
- Use a boolean `swapped` flag per full cycle; if a forward pass makes no swaps the array is sorted and you can stop early.
- Track the index of the LAST swap on the forward pass and use it as the new `end`; do the same for the backward pass to set a new `start`. This shrinks the window from both sides.
- The backward pass is what makes this beat plain bubble sort: it moves a small element near the tail many positions toward the front in a single pass, instead of one position per full sweep.