DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Minimum and Maximum in Array - CA06

My Thinking and Approach


Introduction

In this problem, I was given an array of integers and asked to find the minimum and maximum elements in the array.

This is a basic problem but important for understanding array traversal.


Problem Statement

  • Given an array of integers arr

  • Find:

    • Minimum element
    • Maximum element
  • Return both values


My Initial Thought

At first, I considered:

  • Sorting the array
  • Taking the first element as minimum
  • Taking the last element as maximum

But sorting takes more time and is not necessary.


Key Observation

Instead of sorting:

  • I can traverse the array once
  • Keep track of minimum and maximum values

Optimized Approach

I decided to:

  • Initialize min and max with first element
  • Traverse the array
  • Update values when needed

Logic:

  • If current element < min → update min
  • If current element > max → update max

My Approach (Step-by-Step)

  1. Initialize:
  • min_val = arr[0]
  • max_val = arr[0]

    1. Traverse the array from index 1
    2. For each element:
  • If element < min_val → update min_val

  • If element > max_val → update max_val

    1. Return both values

Code (Python)

Below is the implementation clearly separated inside a code block:

```python id="p5j0ps"
def findMinMax(arr):
min_val = arr[0]
max_val = arr[0]

for i in range(1, len(arr)):
    if arr[i] < min_val:
        min_val = arr[i]
    if arr[i] > max_val:
        max_val = arr[i]

return [min_val, max_val]
Enter fullscreen mode Exit fullscreen mode



---

## Example Walkthrough

### Input:



```text id="htc0zt"
arr = [1, 4, 3, 5, 8, 6]
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Start with min = 1, max = 1
  • Compare with 4 → max = 4
  • Compare with 3 → no change
  • Compare with 5 → max = 5
  • Compare with 8 → max = 8
  • Compare with 6 → no change

Output:

```text id="x4jsm3"
[1, 8]




---

## Complexity Analysis

| Type             | Complexity |
| ---------------- | ---------- |
| Time Complexity  | O(n)       |
| Space Complexity | O(1)       |

---

## Key Takeaways

* No need to sort the array
* Single traversal is enough
* Efficient use of variables improves performance

---

## Conclusion

This problem helped me understand how to find minimum and maximum values efficiently using a single traversal.

It is a basic but important concept in array manipulation.

---
Enter fullscreen mode Exit fullscreen mode

Top comments (0)