← TCS bank

TCS · Question 1 · Arrays

Find Maximum and Minimum Element

ArraysC++code⏱ O(n)💾 O(1)
Service-based

Problem

Given an array of integers, find the maximum and minimum elements.

Approach

We initialize both min and max with the first element. Then we iterate through the array and update min if a smaller value is found, or max if a larger value is found.

Time O(n)Space O(1)

How it works

  1. 1Seed min and max with the first element.
  2. 2Update each on a smaller or larger find in one pass.

Sample input / output

Input:
arr = [3, 5, 4, 1, 9]
Output:
[1, 9]

Constraints

Non-empty array of integers.

Solution — read it, then walk it

Time O(n)Space O(1)Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
STARTinclude <iostream>include <vector>include <utility>using namespace stdpair<int, int>findMinMax(constvector<int>& arr)DEFINE main()vector<int> arr = {3, 5, 4,1, 9}auto p = findMinMax(arr)cout << "[" << p.first <<", " << p.second << "]" <<endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/11

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits