What is the main reason the original order of equal length strings might not be preserved?
medium
A. Strings cannot be sorted by length
B. JavaScript's sort is unstable in some engines
C. The comparator function is incorrect
D. The array contains duplicates
Solution
Step 1: Check comparator correctness
The comparator (a, b) => a.length - b.length correctly compares string lengths.
Step 2: Understand JavaScript sort stability
JavaScript's sort is stable in modern engines but may be unstable in older engines, causing order change.
Final Answer:
JavaScript's sort is unstable in some engines -> Option B
Quick Check:
Unstable sort breaks equal element order [OK]
Hint: Old JS engines have unstable sort, losing order [OK]
Common Mistakes:
Blaming comparator function
Thinking strings can't be sorted by length
Assuming duplicates cause instability
5. You have a list of student records with name and score. You want to sort by score ascending but keep the original order for students with the same score. Which sorting algorithm should you choose and why?
hard
A. MergeSort, because it is stable and sorts efficiently
B. QuickSort, because it is fast but unstable
C. HeapSort, because it uses less memory
D. BubbleSort, because it is simple and stable
Solution
Step 1: Identify need for stability
We want to keep original order for equal scores, so stability is required.
Step 2: Choose algorithm with stability and efficiency
MergeSort is stable and efficient (O(n log n)), suitable for this task.
Step 3: Compare other options
QuickSort is fast but unstable; HeapSort is unstable; BubbleSort is stable but inefficient.
Final Answer:
MergeSort, because it is stable and sorts efficiently -> Option A
Quick Check:
Stable + efficient = MergeSort [OK]
Hint: Stable and efficient sort for equal keys: MergeSort [OK]
Common Mistakes:
Choosing QuickSort ignoring instability
Picking BubbleSort despite inefficiency
Confusing HeapSort as stable
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.