QUESTION #028

Time Validator

Easy

📋 Problem Statement

Write a program to check whether the given time is valid or not.

⏰ Time Format Rules (HH:MM:SS)

  • Hours (HH): 0 to 23 (24-hour format)
  • Minutes (MM): 0 to 59
  • Seconds (SS): 0 to 59
  • All values must be within their valid ranges
Time Validation Logic
Valid Time Ranges:
┌─────────────┬─────────────┬─────────────┐
│   Hours     │   Minutes   │   Seconds   │
│   0 - 23    │   0 - 59    │   0 - 59    │
└─────────────┴─────────────┴─────────────┘

Example: 11:45:45
         ↓   ↓   ↓
        11  45  45
         ✓   ✓   ✓
    (0≤11≤23)(0≤45≤59)(0≤45≤59)
         
    Result: Valid ✓

Example: 08:60:60
         ↓   ↓   ↓
         8  60  60
         ✓   ✗   ✗
    (0≤8≤23)(60>59)(60>59)
         
    Result: Not Valid ✗

📥 Input Format

Accept three integer as a input as colon(:) separated.

📤 Output Format

Print the time is "Valid" or "Not Valid"

💡 Examples

Example 1:
Input: 08:60:60
Output: Not Valid
Validation:
• Hours: 08 → Valid (0 ≤ 8 ≤ 23) ✓
• Minutes: 60 → Invalid (60 > 59) ✗
• Seconds: 60 → Invalid (60 > 59) ✗
Conclusion: Minutes and seconds are out of range, so time is Not Valid
Example 2:
Input: 11:45:45
Output: Valid
Validation:
• Hours: 11 → Valid (0 ≤ 11 ≤ 23) ✓
• Minutes: 45 → Valid (0 ≤ 45 ≤ 59) ✓
• Seconds: 45 → Valid (0 ≤ 45 ≤ 59) ✓
Conclusion: All components are within valid ranges
Example 3 (Midnight):
Input: 00:00:00
Output: Valid
Validation:
• 00:00:00 represents midnight in 24-hour format
• All values are at their minimum valid values
Conclusion: Valid time
Example 4 (End of Day):
Input: 23:59:59
Output: Valid
Validation:
• 23:59:59 is one second before midnight
• All values are at their maximum valid values
Conclusion: Valid time
Example 5 (Invalid Hour):
Input: 24:00:00
Output: Not Valid
Validation:
• Hours: 24 → Invalid (24 > 23) ✗
• In 24-hour format, hours go from 0-23, not 1-24
Conclusion: Hour is out of range

⚠️ Constraints

0 <= INPUT <= 10^15

✅ Solution

#include <iostream>
using namespace std;

int main() {
    int hours, minutes, seconds;
    char colon1, colon2;
    
    cin >> hours >> colon1 >> minutes >> colon2 >> seconds;
    
    // Check if all components are within valid ranges
    if (hours >= 0 && hours <= 23 && 
        minutes >= 0 && minutes <= 59 && 
        seconds >= 0 && seconds <= 59) {
        cout << "Valid" << endl;
    } else {
        cout << "Not Valid" << endl;
    }
    
    return 0;
}

📖 Understanding Colon-Separated Input

How does cin handle "08:60:60"?

// Input: 08:60:60

cin >> hours >> colon1 >> minutes >> colon2 >> seconds;
       ↓         ↓         ↓          ↓         ↓
      08        :         60         :         60

// Variables after reading:
hours = 8      // Leading zero ignored
colon1 = ':'   // Character variable stores ':'
minutes = 60
colon2 = ':'
seconds = 60

Why use char for colons?

  • The colon ':' is a separator, not a number
  • Using char variables "consumes" the colons from input
  • This allows cin to correctly parse the numbers
  • We don't need to validate the colons in this problem

🕐 Understanding 24-Hour Format

12-Hour Format 24-Hour Format Description
12:00 AM 00:00 Midnight
1:00 AM 01:00 Early morning
12:00 PM 12:00 Noon
1:00 PM 13:00 Afternoon
11:59 PM 23:59 Last minute of day

Key Differences:

  • 24-hour: Hours go from 0-23 (no AM/PM needed)
  • 12-hour: Hours go from 1-12 with AM/PM indicator
  • Midnight: 00:00 (24-hour) vs 12:00 AM (12-hour)
  • Noon: 12:00 (24-hour) vs 12:00 PM (12-hour)

✅ Validation Logic Breakdown

// The compound condition checks ALL three components:

if (hours >= 0 && hours <= 23 &&      // Hours must be 0-23
    minutes >= 0 && minutes <= 59 &&  // Minutes must be 0-59
    seconds >= 0 && seconds <= 59)    // Seconds must be 0-59

// This is equivalent to:
bool validHours = (hours >= 0 && hours <= 23);
bool validMinutes = (minutes >= 0 && minutes <= 59);
bool validSeconds = (seconds >= 0 && seconds <= 59);

if (validHours && validMinutes && validSeconds) {
    // All components are valid
}

// The && operator requires ALL conditions to be true
// If even ONE is false, the entire expression is false

⚠️ Common Mistakes to Avoid

1. Using 1-24 instead of 0-23 for hours:

// ❌ WRONG: Hours from 1-24
if (hours >= 1 && hours <= 24) 

// ✅ CORRECT: Hours from 0-23
if (hours >= 0 && hours <= 23)

2. Using OR (||) instead of AND (&&):

// ❌ WRONG: This would accept if ANY component is valid
if (validHours || validMinutes || validSeconds)

// ✅ CORRECT: ALL components must be valid
if (validHours && validMinutes && validSeconds)

3. Forgetting the lower bound (≥ 0):

// ❌ INCOMPLETE: Doesn't check for negative values
if (hours <= 23 && minutes <= 59 && seconds <= 59)

// ✅ COMPLETE: Checks both lower and upper bounds
if (hours >= 0 && hours <= 23 && ...)

🔑 Key Concepts Learned

  • Range Validation: Checking if values fall within specific bounds
  • Compound Conditions: Using && to combine multiple checks
  • Input Parsing: Reading formatted input with separators
  • 24-Hour Format: Understanding time representation (0-23 hours)
  • Character Variables: Using char to consume separator characters
  • Boolean Logic: All conditions must be true for valid time

🌍 Real-world Applications

  • Form Validation: Validating time inputs in web/mobile apps
  • Scheduling Systems: Ensuring appointment times are valid
  • Alarm Clocks: Validating user-set alarm times
  • Time Tracking: Validating clock-in/clock-out times
  • Event Management: Checking event start/end times
  • Database Validation: Ensuring time data integrity
  • API Input Validation: Validating time parameters in requests
  • IoT Devices: Validating time settings in smart devices

💪 Extension Challenges

  • Level 1: Add validation to check if colons are present
  • Level 2: Support 12-hour format validation (with AM/PM)
  • Level 3: Convert valid 24-hour time to 12-hour format
  • Level 4: Calculate time difference between two valid times
  • Level 5: Add validation for milliseconds (HH:MM:SS.mmm)
  • Level 6: Validate time zones (e.g., HH:MM:SS+05:30)
  • Level 7: Parse and validate ISO 8601 time format
  • Bonus: Create a complete date-time validator

💡 Practice Tips

  • Test Boundaries: Try 00:00:00, 23:59:59, 24:00:00, -1:00:00
  • Test Each Component: Invalid hours, invalid minutes, invalid seconds
  • Understand Input: Practice reading colon-separated values
  • Draw Truth Tables: Map out when time is valid/invalid
  • Compare Formats: Practice converting 12-hour ↔ 24-hour
  • Use Debugger: Step through to see how cin parses input
  • Learn Standards: Research ISO 8601 time format standards