Program to find number of optimal steps needed to reach destination by baby and giant steps in Python

Suppose we have a list of queries Q, where each query Q[i] contains a triplet [a_i, b_i, d_i]. Consider we are at position (0, 0) initially, then in one step we can move from some position (x1, y1) to (x2, y2) where Euclidean distance between these two points is at least a and at most b. Now for each query we have to find minimum number of steps needed to reach (d_i, 0) from (0, 0).

For example, if the input is Q = [(2,3,1), (1,2,0), (3,4,11)], then the output will be [2, 0, 3].

Algorithm Steps

To solve this problem, we will follow these steps ?

  • Define a function steps() that takes parameters a, b, d
  • mmin := minimum of a, b
  • mmax := maximum of a, b
  • If d is 0, return 0
  • If d equals either mmin or mmax, return 1
  • If d < mmax, return 2
  • Otherwise, return the ceiling of (d / mmax)

Implementation

Let us see the following implementation to get better understanding ?

from math import ceil

def steps(a, b, d):
    mmin = min(a, b)
    mmax = max(a, b)
    
    if d == 0:
        return 0
    if d in [mmin, mmax]:
        return 1
    if d < mmax:
        return 2
    return ceil(d / mmax)

def solve(Q):
    res = []
    for q in Q:
        a, b, d = q
        res.append(steps(a, b, d))
    return res

# Test the function
Q = [(2, 3, 1), (1, 2, 0), (3, 4, 11)]
result = solve(Q)
print(result)

The output of the above code is ?

[2, 0, 3]

How It Works

The algorithm works by analyzing different cases ?

  • Case 1: If destination is 0, no steps needed
  • Case 2: If destination equals minimum or maximum step size, only 1 step needed
  • Case 3: If destination is less than maximum step size, we can reach in 2 steps
  • Case 4: For larger destinations, we divide by maximum step size and take ceiling

Example Walkthrough

For the query (3, 4, 11) ?

from math import ceil

a, b, d = 3, 4, 11
mmin = min(a, b)  # 3
mmax = max(a, b)  # 4

# Since d = 11 > mmax = 4, we use ceil(d / mmax)
steps_needed = ceil(11 / 4)
print(f"Steps needed: {steps_needed}")
Steps needed: 3

Conclusion

This algorithm efficiently calculates the minimum steps needed by considering the step size constraints. The key insight is that we can always reach any destination in at most ceil(d / max_step_size) steps.

Updated on: 2026-03-26T15:10:23+05:30

474 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements