Problem 3178

Abstract / Summary

Given children passing a ball in a circle for a set number of seconds find which child holds the ball at the end.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
11 lines | 334 bytes | submitted July 13, 2024 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (90k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.88 | σ = 1.40

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
20 links | 9 authors | 6 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

7 solutions   July 13, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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