Leetcode 3178. Find the Child Who Has the Ball After K Seconds
You are given a list of n
children who are playing a game. In this game, there is a ball that starts with the first child initially. The children pass the ball to the next child one by one until they reach the last child, after which the ball is again passed to the first child. This process continues indefinitely. You are required to determine which child has the ball after k
seconds. The list of children is numbered starting from 0 to n-1
.
Constraints:
1 <= n <= 10^9
0 <= k <= 10^9
k
seconds.k % n
.k
seconds, the position of the ball will be (0 + k) % n
, where n
is the total number of children.Here’s the C++ code solving the problem:
#include <iostream>
int findChildWithBall(int n, int k) {
// Compute the child who has the ball after k seconds
return k % n;
}
int main() {
int n, k;
std::cout << "Enter number of children and seconds respectively: ";
std::cin >> n >> k;
int result = findChildWithBall(n, k);
std::cout << "The child with the ball after " << k << " seconds is: " << result << std::endl;
return 0;
}
O(1)
, because the modulo operation is performed in constant time.O(1)
as no additional space proportional to the input size is used.This implementation efficiently computes the index of the child holding the ball after k
seconds, handling large values of n
and k
effectively due to the use of simple arithmetic operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?