algoadvance

Leetcode 3028. Ant on the Boundary

Problem Statement

  1. Ant on the Boundary-out

You’re given the width width and the height height of a rectangular grid where the cells are partitioned. An ant starts at the position (x, y) at time t = 0 and moves in a straight path, bouncing off the boundaries of the grid. The ant moves at a speed of one cell per second.

Given the current position of the ant, determine the coordinates of the ant after t seconds.

Clarifying Questions

  1. Boundary Conditions:
    • What happens when the ant hits a boundary? Does it reverse its direction?

    Answer: Yes, when the ant hits a boundary, it bounces back in the opposite direction.

  2. Initial Position:
    • Can the initial position (x, y) be on the boundary?

    Answer: Yes, the initial position can be anywhere within the grid including on the boundaries.

  3. Time t:
    • Is t guaranteed to be a non-negative integer?

    Answer: Yes, t is guaranteed to be a non-negative integer.

  4. Edge Cases:
    • What if the width or height is 1? How should movements be handled?

    Answer: The movements are within the single row or column, and the ant just bounces back and forth, behaving like a 1D motion.

Strategy

To determine the position of the ant after t seconds:

  1. Observe the periodic nature of the ant’s motion:
    • In the x-direction, the ant moves from 0 to width and back, treating the motion as bouncing at the endpoints.
    • Similarly, in the y-direction, the ant moves from 0 to height and back.
  2. X-coordinate Calculation:
    • The effective distance the ant moves horizontally is (x + t) % (2 * width).
    • If this distance exceeds width, the ant is on the bounce-back path.
  3. Y-coordinate Calculation:
    • The effective distance the ant moves vertically is (y + t) % (2 * height).
    • If this distance exceeds height, the ant is on the bounce-back path.

Code

#include <iostream>
#include <vector>

std::vector<int> antPosition(int width, int height, int x, int y, int t) {
    // Calculate the new coordinates
    int x_distance = (x + t) % (2 * width);
    int y_distance = (y + t) % (2 * height);
    
    int new_x = (x_distance < width) ? x_distance : (2 * width - x_distance);
    int new_y = (y_distance < height) ? y_distance : (2 * height - y_distance);
    
    return {new_x, new_y};
}

int main() {
    int width = 5, height = 4;
    int x = 1, y = 0, t = 10;
    std::vector<int> position = antPosition(width, height, x, y, t);
    std::cout << "Position after " << t << " seconds: (" << position[0] << ", " << position[1] << ")" << std::endl;
    return 0;
}

Time Complexity

By following this strategy and implementation, the ant’s new position can be efficiently calculated after any given t seconds.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI