Code Logo

Find Cheapest Taxi Fare

Published at19 Apr 2026
Calculations & Math Easy 6 views
Like0

Given an array of taxi fare quotes from different companies, find the cheapest fare. Return the minimum fare from the list. If the array is empty, return 0.

For example, the cheapest fare from [25, 18, 30, 22] is 18. From [40] it is 40. An empty array returns 0.

Finding the minimum value is the mirror image of finding the maximum and equally fundamental. Comparing prices to find the best deal is a ubiquitous real-world application: flight tickets, hotel rates, insurance premiums, and grocery prices all use this pattern.

The solution tracks a running minimum by comparing each fare against the current best. Initialize min to the first fare and update it whenever a lower fare is encountered. Return min after examining all options.

Edge cases include an empty array (return 0), a single fare (return it), and all equal fares (return that value). The algorithm correctly handles any ordering of the input.

Learn about our pseudocode specification
Guide

Example Input & Output

Example 1
Input
fares = [45, 30, 38, 50]
Output
30
Explanation

30 is the lowest fare in the list.

Example 2
Input
fares = [22]
Output
22
Explanation

With one taxi option, that fare is automatically the cheapest.

Example 3
Input
fares = []
Output
-1
Explanation

No fares means there is no valid answer.

Algorithm Flow

Recommendation Algorithm Flow for Find Cheapest Taxi Fare
Recommendation Algorithm Flow for Find Cheapest Taxi Fare

Solution Approach

Iterate through the array while tracking the minimum fare seen so far.

function cheapestFare(fares)
  if fares is empty then return 0
  min = fares[0]
  for each f in fares
    if f < min then min = f
  return min

Handle the empty case by returning 0 immediately to avoid index errors. Initialize min to the first fare. Loop through each fare; if the current fare is less than min, update min. After examining all fares, return the minimum value found.

Time complexity is O(n), space complexity is O(1). The algorithm examines each fare exactly once, making it optimal.

Best Answers

Pseudocode - Approach 1
program find_cheapest_taxi_fare
dictionary
   fares: array[1..100] of integer
   cheapest, i, n: integer
algorithm
   input(fares)
   n <- fares.length
   if n = 0 then
      output(-1)
   else
      cheapest <- fares[0]
      for i <- 1 to n - 1 do
         if fares[i] < cheapest then
            cheapest <- fares[i]
         endif
      endfor
      output(cheapest)
   endif
endprogram