goto() command for navigation in Drone Programming - Time & Space Complexity
When using the goto() command for navigation, it is important to understand how the time to reach a destination changes as the distance grows.
We want to know how the drone's travel time increases when it moves to farther points.
Analyze the time complexity of the following code snippet.
function goto(x, y) {
while (currentX !== x || currentY !== y) {
if (currentX < x) currentX++;
else if (currentX > x) currentX--;
if (currentY < y) currentY++;
else if (currentY > y) currentY--;
}
}
This code moves the drone step-by-step from its current position to the target coordinates (x, y).
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whileloop that moves the drone one step closer each time. - How many times: The loop runs once for each step needed to reach the target position.
The number of steps depends on how far the drone must travel in the x and y directions.
| Input Size (distance) | Approx. Steps |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps grow roughly in direct proportion to the distance to the target.
Time Complexity: O(n)
This means the time to reach the destination grows linearly with the distance the drone must travel.
[X] Wrong: "The drone can jump instantly to the target, so time does not depend on distance."
[OK] Correct: The goto() command moves step-by-step, so the time depends on how many steps it takes to reach the target.
Understanding how movement commands scale with distance helps you reason about efficiency in navigation tasks, a useful skill in many programming challenges.
"What if the drone could move diagonally in one step? How would the time complexity change?"