Data Structures and Algorithms (DSA)  

🔎 How to Find the Smallest Element in an Array in DSA

🌟 Introduction

Arrays are one of the most basic yet powerful data structures in programming. A common problem in DSA interviews and practice is finding the smallest element in an array.

This problem helps you understand:

  • How to traverse arrays

  • How to compare elements

  • How to use variables to store results

🧠 Problem Statement

Given an array of integers, find the smallest element present in the array.

Example 1

Input: [10, 20, 4, 45, 99]
Output: 4

Example 2

Input: [5, 7, 2, 9, 1]
Output: 1

⚙️ Approach

  1. Initialize a variable min with the first element of the array.

  2. Traverse through the array elements one by one.

  3. Compare each element with min.

    • If the current element is smaller than min, update min.

  4. After the loop ends, min will contain the smallest element.

🔑 Pseudocode

function findMin(arr, n):
    min = arr[0]
    for i = 1 to n-1:
        if arr[i] < min:
            min = arr[i]
    return min

💻 Implementation

✅ C Program

#include <stdio.h>

int findMin(int arr[], int n) {
    int min = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

int main() {
    int arr[] = {10, 20, 4, 45, 99};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Smallest element: %d\n", findMin(arr, n));
    return 0;
}

✅ C++ Program

#include <iostream>
using namespace std;

int findMin(int arr[], int n) {
    int min = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

int main() {
    int arr[] = {10, 20, 4, 45, 99};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Smallest element: " << findMin(arr, n) << endl;
    return 0;
}

✅ Java Program

public class SmallestElement {
    public static int findMin(int[] arr) {
        int min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 4, 45, 99};
        System.out.println("Smallest element: " + findMin(arr));
    }
}

⏱️ Time & Space Complexity

  • Time Complexity: O(n) → We traverse the array once.

  • Space Complexity: O(1) → Only one variable (min) is used for storage.

📌 Key Takeaways

  • The smallest element in an array can be found in a single pass.

  • No extra space is required except for one variable.

  • This problem forms the base for more advanced problems like sorting, searching, and min-heap implementation.

🎯 Conclusion

Finding the smallest element in an array is a fundamental DSA problem. It teaches you how to traverse arrays efficiently and use comparisons logically. Mastering such basics will make advanced concepts like sorting and searching much easier.