Challenge - 5 Problems
Array Deletion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after deleting the last element from the array?
Consider the following C# code that deletes the last element from an array by creating a new smaller array. What will be printed?
DSA C#
int[] arr = {10, 20, 30, 40, 50}; int n = arr.Length; int[] newArr = new int[n - 1]; for (int i = 0; i < n - 1; i++) { newArr[i] = arr[i]; } foreach (int val in newArr) { Console.Write(val + " "); }
Attempts:
2 left
💡 Hint
The new array has one less element, copying all except the last.
✗ Incorrect
The code copies all elements except the last one (index n-1) into newArr, so the output is the first four elements.
❓ Predict Output
intermediateWhat happens if we try to delete the last element from an empty array?
Given this C# code snippet, what will happen when it runs?
DSA C#
int[] arr = {}; int n = arr.Length; int[] newArr = new int[n - 1]; for (int i = 0; i < n - 1; i++) { newArr[i] = arr[i]; } Console.WriteLine(newArr.Length);
Attempts:
2 left
💡 Hint
Array size cannot be negative.
✗ Incorrect
The code tries to create an array with size n-1 = -1, which is invalid and throws an exception.
🔧 Debug
advancedWhy does this code throw an exception when deleting the last element?
Analyze the code below. It aims to delete the last element from an array but throws an exception. What is the cause?
DSA C#
int[] arr = {1, 2, 3}; int n = arr.Length; int[] newArr = new int[n]; for (int i = 0; i < n - 1; i++) { newArr[i] = arr[i]; } Console.WriteLine(newArr[n - 1]);
Attempts:
2 left
💡 Hint
Check array size and initialization of elements.
✗ Incorrect
The newArr has same size as arr but last element is not assigned, so it defaults to 0. No exception occurs; output is 0.
🧠 Conceptual
advancedWhat is the time complexity of deleting the last element from a fixed-size array by copying?
If you delete the last element from an array by creating a new array and copying all elements except the last, what is the time complexity?
Attempts:
2 left
💡 Hint
Consider how many elements are copied.
✗ Incorrect
Copying n-1 elements requires time proportional to n, so complexity is O(n).
🚀 Application
expertAfter deleting the last element from this array, what is the printed output?
Given the code below, what will be printed?
DSA C#
int[] arr = {5, 10, 15, 20, 25}; int n = arr.Length; int[] newArr = new int[n - 1]; Array.Copy(arr, newArr, n - 1); for (int i = 0; i < newArr.Length; i++) { Console.Write(newArr[i] + " -> "); } Console.Write("null");
Attempts:
2 left
💡 Hint
Array.Copy copies specified number of elements from source to destination.
✗ Incorrect
Array.Copy copies first n-1 elements (5 elements - 1 = 4) from arr to newArr, so last element 25 is excluded.
