LeetCode : Who Reaches First? A Fun Number Line Problem

 

Absolutely, Akilamadhavan! Here's a blog-style write-up that turns your problem into an engaging and informative post for readers interested in programming, logic, or interview prep:

🧭 Who Reaches First? A Fun Number Line Problem in Python

Imagine three people standing on a number line. Person 3 is stationary, while Person 1 and Person 2 race toward them at the same speed. The question is simple: who reaches Person 3 first?

This deceptively straightforward problem is a great way to practice basic logic, conditionals, and understanding time complexity. Let’s break it down.

🧠 Problem Statement

You're given three integers:

  • x: Position of Person 1
  • y: Position of Person 2
  • z: Position of Person 3 (stationary)

Both Person 1 and Person 2 move toward Person 3 at the same speed. Your task is to determine:

  • Return 1 if Person 1 reaches Person 3 first
  • Return 2 if Person 2 reaches Person 3 first
  • Return 0 if both reach at the same time

🔍 Examples

Example 1

Input: x = 2, y = 7, z = 4
Output: 1
Explanation:

  • Person 1 is 2 units away from Person 3
  • Person 2 is 3 units away
  • Person 1 reaches first

Example 2

Input: x = 2, y = 5, z = 6
Output: 2
Explanation:

  • Person 1 is 4 units away
  • Person 2 is 1 unit away
  • Person 2 reaches first

Example 3

Input: x = 1, y = 5, z = 3
Output: 0
Explanation:

  • Both are 2 units away
  • They arrive at the same time

🛠️ Python Solution

Here’s a clean and efficient way to solve it:

class Solution:
    def findClosest(self, x: int, y: int, z: int) -> int:
        dist1 = abs(z - x)
        dist2 = abs(z - y)
       
        if dist1 < dist2:
            return 1
        elif dist1 > dist2:
            return 2
        else:
            return 0


📊 Time & Space Complexity

This solution is lightning-fast because it uses only basic arithmetic and comparisons—no loops, no recursion.

🎯 Why This Matters

This kind of problem is often used in coding interviews to test:

  • Your ability to reason about distances and movement
  • Your understanding of conditional logic
  • Your ability to write clean, readable code

It’s also a great warm-up before diving into more complex algorithms like binary search or graph traversal.

🚀 Want to Go Further?

You could extend this problem by:

  • Handling multiple people in an array
  • Finding the k closest individuals
  • Simulating movement over time
  • Visualizing the number line in a GUI or animation

Let me know if you'd like help building any of those next!

Would you like me to help you publish this on a blog platform or format it for Medium or Dev.to?

Comments