Python 3178.py
class Solution:
def numberOfChild(self, n: int, k: int) -> int:
# basic simulation, avoid modulo math
child = 0
direction = +1
for _ in range(k):
child += direction
if child == n - 1 or child == 0:
direction = -direction
return child
Difficulty
and has an acceptance rate of about 62% (90k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the position of a child moving back and forth along a line of n children after k steps. The algorithm simulates the movement step by step, updating the current index and reversing direction when the ends of the line are reached. By avoiding modular arithmetic, the code relies on simple integer operations and a conditional direction change, which keeps the inner loop lightweight.
Key Steps
The core of the algorithm consists of three distinct actions performed inside a loop that iterates k times.
The initialization establishes the starting child index and the initial direction of movement.
child = 0
direction = +1
During each iteration the current child index is advanced by the current direction.
child += direction
After moving, the algorithm checks whether the new position is at either extreme of the line (the first or the last child). If so, the direction is inverted to cause the next step to move in the opposite direction.
if child == n - 1 or child == 0:
direction = -direction
When the loop finishes, the final value of child is returned as the result.
return child
Edge Cases Handled
When the number of children n equals one, the line has a single position. The condition child == n - 1 or child == 0 is true at the start, causing the direction to flip each iteration, but the child index remains zero because adding +1 or -1 would move it out of bounds before the next flip. Consequently, the function correctly returns 0 for any k.
When n equals two, the child alternates between the two positions. The direction reversal logic triggers on both ends, ensuring the index toggles between 0 and 1 on each step, which matches the expected back-and-forth pattern.
If k is zero, the loop body never executes. The initial value of child (zero) is returned directly, representing the starting position without any movement.
The code also gracefully handles cases where k is larger than the length of the line. Because the direction is flipped each time an endpoint is reached, the simulation naturally continues the correct oscillation without requiring any additional bookkeeping.
Performance Optimizations
The implementation deliberately avoids using the modulo operator, which can be more expensive than simple arithmetic and conditional checks on many platforms. By maintaining an explicit direction variable that holds either +1 or -1, the algorithm performs only an addition and a couple of comparisons per iteration.
The conditional that determines when to reverse direction checks two equality conditions in a single statement, minimizing branching overhead. Since the loop body consists of a fixed set of primitive operations, the interpreter can execute it efficiently even for large values of k.
Overall, the design emphasizes minimal computational work per step, leveraging straightforward integer arithmetic and a single branch to achieve the required simulation.
ELI5 - Simplified Explanation
Imagine there is a row of children standing in a line, and they are passing a special toy back and forth. The child at the very start of the line passes it to the next friend, and they keep passing it along until they reach the child at the very end of the line. Once the toy reaches the last child, they turn around and start passing it all the way back to the beginning again.
This code acts like a tiny helper that keeps track of where that toy is. First, it starts with the toy at the first child. Then, it follows a simple rule for every passing turn. It looks to see which way the toy is moving, either forward toward the end of the line or backward toward the start. Every single time the toy is passed, it moves one spot in that direction.
If the toy reaches the last person in the line or makes it all the way back to the very first person, the code changes the direction. It does this because those two children are at the ends, so the toy has to bounce back the other way. By repeating this process for every single pass, the final spot of the toy is found.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | Java | Python | C++ | TS | ||
| WalkCCC | Java | Python | C++ | ||||
| leetcode.ca | Java | Python | C++ | Go | TS | ||
| Progiez | Java | Python | C++ | ||||
| github | charles-wangkai | Java | |||||
| everthis | JS | ||||||
| fsq | Python | ||||||
| JoshCrozier | JS | ||||||
| varunu28 | Java | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | Python | ||||||
| JoshCrozier | JavaScript | ||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2582: Pass the Pillow
- problem 2682: Find the Losers of the Circular Game
Solved On The Same Day
- problem 2750: Ways to Split Array Into Good Subarrays
- problem 2762: Continuous Subarrays
- problem 2779: Maximum Beauty of an Array After Applying Operation
- problem 1095: Find in Mountain Array
- problem 1293: Shortest Path in a Grid with Obstacles Elimination
- problem 2449: Minimum Number of Operations to Make Arrays Similar
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality