Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Angle Between Hands of a Clock

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1344" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand. Answers within 10-5 of the actual value will be accepted as correct. Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5 Constraints: 1 <= hour <= 12 0 <= minutes <= 59

Explanation

Here's an efficient solution to calculate the smaller angle between the hour and minute hands:

  • Calculate Angles: Determine the angles of the hour and minute hands relative to the 12 o'clock position.
  • Find Difference: Calculate the absolute difference between the two angles.
  • Minimize Angle: Ensure the returned angle is the smaller of the two possible angles (<= 180 degrees).

  • Runtime Complexity: O(1), Storage Complexity: O(1)

Code

    def angleClock(hour: int, minutes: int) -> float:
    """
    Calculates the smaller angle between the hour and minute hands of a clock.

    Args:
        hour: The hour (1-12).
        minutes: The minutes (0-59).

    Returns:
        The smaller angle in degrees between the hour and minute hands.
    """

    # Calculate the angle of the minute hand
    minute_angle = minutes * 6  # 360 degrees / 60 minutes = 6 degrees/minute

    # Calculate the angle of the hour hand
    # Each hour is 30 degrees (360 / 12)
    # Plus, the hour hand moves a fraction of 30 degrees based on the minutes
    hour_angle = (hour % 12 + minutes / 60) * 30

    # Calculate the absolute difference between the two angles
    angle_difference = abs(hour_angle - minute_angle)

    # Return the smaller angle
    return min(angle_difference, 360 - angle_difference)

More from this blog

C

Chatmagic blog

2894 posts