Leetcode 3178: Find the Child Who Has the Ball After K Seconds

grid47
grid47
Exploring patterns and algorithms
Dec 25, 2023 5 min read

You are given two positive integers, n and k. There are n children numbered from 0 to n - 1, standing in a queue from left to right. Initially, child 0 holds a ball and the direction of passing the ball is towards the right. After each second, the child holding the ball passes it to the next child in the queue. If the ball reaches the first or last child, the direction of passing the ball reverses. You need to determine which child will have the ball after k seconds.
Problem
Approach
Steps
Complexity
Input: The input consists of two integers, `n` (the number of children) and `k` (the number of seconds after which the ball will be passed).
Example: Example 1: Input: n = 4, k = 3 Output: 1 Explanation: After 3 seconds, the ball will be with child 1.
Constraints:
• 2 <= n <= 50
• 1 <= k <= 50
Output: Return the number of the child who will hold the ball after `k` seconds.
Example: Example 2: Input: n = 5, k = 6 Output: 2 Explanation: After 6 seconds, the ball will be with child 2.
Constraints:
• The output will be an integer between 0 and n-1, inclusive.
Goal: The goal is to simulate the passing of the ball for `k` seconds and track which child holds it.
Steps:
• Initialize the ball at child 0, and the direction of passing the ball as right (towards child 1).
• For each second, check if the ball should change direction (i.e., if the ball reaches the first or last child).
• Update the ball's position accordingly and repeat until `k` seconds have elapsed.
Goal: The input should satisfy the following constraints.
Steps:
• n is between 2 and 50 (inclusive).
• k is between 1 and 50 (inclusive).
Assumptions:
• The ball passes to the next child every second.
• The ball's direction is reversed when it reaches the first or last child.
Input: Example 1:
Explanation: For `n = 4` and `k = 3`, the ball starts at child 0 and moves to child 1 after 1 second. After 2 seconds, it moves to child 2. After 3 seconds, it moves back to child 1. Therefore, the output is 1.

Input: Example 2:
Explanation: For `n = 5` and `k = 6`, the ball starts at child 0 and moves right until child 4. After 5 seconds, it reverses direction and moves back to child 1. Finally, after 6 seconds, it reaches child 2. Hence, the output is 2.

Input: Example 3:
Explanation: For `n = 3` and `k = 2`, the ball moves from child 0 to child 1 after 1 second and then to child 2 after 2 seconds. Therefore, the output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus