Skip to content

Latest commit

 

History

History

2582

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.

  • For example, once the pillow reaches the nth person they pass it to the n - 1th person, then to the n - 2th person and so on.

Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.

 

Example 1:

Input: n = 4, time = 5
Output: 2
Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
Afer five seconds, the pillow is given to the 2nd person.

Example 2:

Input: n = 3, time = 2
Output: 3
Explanation: People pass the pillow in the following way: 1 -> 2 -> 3.
Afer two seconds, the pillow is given to the 3rd person.

 

Constraints:

  • 2 <= n <= 1000
  • 1 <= time <= 1000

Related Topics:
Math, Simulation

Similar Questions:

Solution 1. Math

Say n = 3, what's the pattern?

  • time = 1, result = 2, distance from 1 = 1, left-to-right = true
  • time = 2, result = 3, distance from 1 = 2, left-to-right = true
  • time = 3, result = 2, distance from 3 = 1, left-to-right = false
  • time = 4, result = 1, distance from 3 = 2, left-to-right = false
  • time = 5, result = 2, distance from 1 = 1, left-to-right = true
  • ...

From the distance, we can see that we need to divide or modulos by n - 1 = 2 since it's repeating every 2 steps. The result is {left-to-right} ? 1 + {distance from 1} : 3 - {distance from 3}

Let div = (time - 1) / (n - 1), mod = (time - 1) % (n - 1), {left-to-right} = div % 2 == 0, {distance from 1} = 1 + mod and {distance from 3} = 1 + mod.

So, let dist = 1 + mod, the result is div % 2 ? n - dist : 1 + dist.

// OJ: https://leetcode.com/problems/pass-the-pillow
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int passThePillow(int n, int time) {
        int div = (time - 1) / (n - 1), dist = (time - 1) % (n - 1) + 1;
        return div % 2 ? n - dist : 1 + dist;
    }
};