Function findMinimum – CTS PATTERN
Fix the logical error in the given code to correctly find the minimum value in an integer array
Understand the Problem
Problem Statement
You are required to fix all logical errors in the given code. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.
Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.
The function findMinimum(int arr[], int len) accepts an integer array arr of length len as the input. The function is supposed to return the smallest integer among the given integers in the array.
The function compiles fine but fails to return the desired result due to logical error.
Your task is to fix the program so that it passes all test cases.
Constraints
- Array length (len) must be greater than 0
- Array length (len) should be a positive integer
- Array elements can be any integer value (positive, negative, or zero)
- The array must contain at least one element
- Time complexity should be O(n) where n is the length of the array
- Space complexity should be O(1) - no additional arrays or data structures
Examples
arr = [5, 2, 8, 1, 9], len = 51The smallest element in the array [5, 2, 8, 1, 9] is 1, so the function should return 1.
arr = [-3, -7, -1, -5], len = 4-7The smallest element in the array [-3, -7, -1, -5] is -7, so the function should return -7.
arr = [10], len = 110When the array has only one element, that element is automatically the minimum, so the function should return 10.
Solution
int findMinimum(int arr[], int len)
{
int index, min = arr[0];
for(index = 1; index < len; index++)
{
if(arr[index] < min)
{
min = arr[index];
}
}
return min;
}Step-by-step explanation of the C solution:
- Initialize minimum: Set
min = arr[0]to use the first element as the initial minimum value - Loop through remaining elements: Start the loop from
index = 1since we've already considered the first element - Compare and update: For each element, check if it's smaller than the current minimum. If yes, update the minimum
- Return result: After checking all elements, return the final minimum value
The key fix is initializing min to arr[0] instead of 0, and starting the loop from index 1.