Challenge - 5 Problems
Sorting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Sorted Array After Custom Sort
What is the output of the following C# code that sorts an array of integers in descending order?
DSA C#
int[] numbers = {5, 3, 8, 1, 2}; Array.Sort(numbers, (a, b) => b.CompareTo(a)); foreach (var num in numbers) { Console.Write(num + " "); }
Attempts:
2 left
💡 Hint
Think about how the comparison function affects the sorting order.
✗ Incorrect
The Array.Sort method with a custom comparer sorts the array in descending order because it compares b to a, reversing the usual ascending order.
🧠 Conceptual
intermediateWhy is Sorting Important Before Binary Search?
Why must an array be sorted before performing a binary search on it?
Attempts:
2 left
💡 Hint
Think about how binary search decides which half of the array to search next.
✗ Incorrect
Binary search relies on the array being sorted to decide whether to search the left or right half based on comparisons with the middle element.
❓ Predict Output
advancedOutput After Sorting List of Strings by Length
What is the output of this C# code that sorts a list of strings by their length in ascending order?
DSA C#
List<string> words = new List<string> {"apple", "dog", "banana", "cat"};
words.Sort((x, y) => x.Length.CompareTo(y.Length));
foreach (var word in words) {
Console.Write(word + " ");
}Attempts:
2 left
💡 Hint
Look at the length of each word and how the comparer sorts them.
✗ Incorrect
The Sort method orders the list by string length from shortest to longest: dog (3), cat (3), apple (5), banana (6). Since dog and cat have the same length, their relative order is preserved.
🔧 Debug
advancedIdentify the Error in Sorting Code
What error will this C# code produce when trying to sort an array of integers?
DSA C#
int[] arr = {4, 2, 7, 1}; Array.Sort(arr, (a, b) => a - b); foreach (var num in arr) { Console.Write(num + " "); }
Attempts:
2 left
💡 Hint
Check the type expected by Array.Sort for the comparison delegate.
✗ Incorrect
Array.Sort expects a Comparison delegate that returns an int indicating order. Using subtraction can cause overflow or incorrect results, leading to incorrect sorting output.
🚀 Application
expertHow Sorting Enables Efficient Duplicate Removal
Given an unsorted array of integers, which approach best uses sorting to remove duplicates efficiently?
Attempts:
2 left
💡 Hint
Think about how sorting groups duplicates together.
✗ Incorrect
Sorting groups duplicates next to each other, so a single pass can identify and skip duplicates efficiently.
