Command acknowledgment handling in Drone Programming - Time & Space Complexity
When a drone receives commands, it often waits for acknowledgments to confirm each step.
We want to understand how the time to handle these acknowledgments grows as the number of commands increases.
Analyze the time complexity of the following code snippet.
function handleCommands(commands) {
for (let i = 0; i < commands.length; i++) {
sendCommand(commands[i]);
waitForAck(commands[i]);
}
}
function sendCommand(cmd) {
// sends command to drone
}
function waitForAck(cmd) {
// waits until drone acknowledges cmd
}
This code sends each command to the drone and waits for its acknowledgment before moving to the next.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sends each command and waits for its acknowledgment.
- How many times: Once for each command in the list.
Each command requires sending and waiting for acknowledgment, so the total time grows as more commands are added.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 send-and-wait cycles |
| 100 | 100 send-and-wait cycles |
| 1000 | 1000 send-and-wait cycles |
Pattern observation: The total time increases directly with the number of commands.
Time Complexity: O(n)
This means the time to handle acknowledgments grows in a straight line as the number of commands increases.
[X] Wrong: "Waiting for all acknowledgments happens at once, so time stays the same no matter how many commands."
[OK] Correct: The code waits for each acknowledgment before sending the next command, so time adds up with each command.
Understanding how waiting for acknowledgments affects time helps you design efficient drone communication and shows you can analyze real-world code timing.
"What if we sent all commands first, then waited for all acknowledgments together? How would the time complexity change?"