easy
0 views

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

Example 1
Input
arr = [5, 2, 8, 1, 9], len = 5
Output
1
Explanation

The smallest element in the array [5, 2, 8, 1, 9] is 1, so the function should return 1.

Example 2
Input
arr = [-3, -7, -1, -5], len = 4
Output
-7
Explanation

The smallest element in the array [-3, -7, -1, -5] is -7, so the function should return -7.

Example 3
Input
arr = [10], len = 1
Output
10
Explanation

When 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;
}
Time:O(n) - We iterate through the array exactly once
Space:O(1) - We only use a constant amount of extra space (two integer variables)
Approach:

Step-by-step explanation of the C solution:

  1. Initialize minimum: Set min = arr[0] to use the first element as the initial minimum value
  2. Loop through remaining elements: Start the loop from index = 1 since we've already considered the first element
  3. Compare and update: For each element, check if it's smaller than the current minimum. If yes, update the minimum
  4. 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.

Visual Explanation

Loading diagram...