Code Logo

Check Parking Fee

Published at19 Apr 2026
Logic & Conditionals Easy 7 views
Like0

Calculate the total parking fee based on the number of hours parked. The first 2 hours cost a flat rate of 5. Each additional hour beyond 2 costs 3 per hour. If the parking time is 0 hours, the fee is 0.

For example, parking for 1 hour costs 5 (flat rate). Parking for 2 hours costs 5. Parking for 3 hours costs 5 + 1 × 3 = 8. Parking for 5 hours costs 5 + 3 × 3 = 14.

This problem teaches piecewise pricing logic — a common real-world pattern used in parking garages, toll roads, subscription plans, and utility billing. The solution requires conditional logic: if the hours are 2 or less, return the flat rate. Otherwise, return the flat rate plus the extra hours multiplied by the per-hour rate.

The algorithm first checks if hours is 0 and returns 0 immediately (no parking, no fee). Then it calculates the base fee of 5 for the first 2 hours. If hours exceed 2, it adds 3 for each extra hour beyond 2.

Edge cases include 0 hours (return 0), exactly 2 hours (return the flat rate only), and very long parking durations where the fee grows linearly with time.

Learn about our pseudocode specification
Guide

Example Input & Output

Example 1
Input
hours = 4
Output
11
Explanation

The first two hours cost 5, and the extra two hours add 6.

Example 2
Input
hours = 2
Output
5
Explanation

Exactly 2 hours still uses the base fee.

Example 3
Input
hours = 1
Output
5
Explanation

A short stay still uses the flat parking fee.

Algorithm Flow

Recommendation Algorithm Flow for Check Parking Fee
Recommendation Algorithm Flow for Check Parking Fee

Solution Approach

Apply the flat rate for the first 2 hours, then add the hourly rate for any additional hours.

function parkingFee(hours)
  if hours == 0 then return 0
  fee = 5
  if hours > 2 then
    fee = fee + (hours - 2) * 3
  return fee

Start by handling 0 hours and returning 0 immediately. Set the base fee to 5, which covers up to 2 hours. If the parking duration exceeds 2 hours, calculate the extra hours (hours - 2) and multiply by the per-hour rate of 3, adding the result to the base fee. Return the total fee.

Time complexity is O(1). Space complexity is O(1).

Best Answers

Pseudocode - Approach 1
program check_parking_fee
dictionary
   hours, fee, extra_hours: integer
algorithm
   input(hours)
   if hours <= 2 then
      fee <- 5
   else
      extra_hours <- hours - 2
      fee <- 5 + (extra_hours * 3)
   endif
   output(fee)
endprogram