1165. Shortest Consecutive Run
A builder owns exactly n bricks and wants to lay a staircase in which the first step uses a bricks, the next a + 1, the next a + 2 and so on, with at least two steps and every step holding at least one brick. All n bricks must be used.
Among all such staircases choose the one with the fewest steps; for a fixed number of steps there is at most one valid staircase, so the choice is unique. Return [first, last], the brick counts of the first and last step, or an empty array if no staircase exists. Here 1 <= n <= 10^12.
Try step counts k = 2, 3, ... while k(k + 1) / 2 <= n and test divisibility, giving O(sqrt(n)) time and O(1) space.
Example 1
- Input:
- n = 9
- Output:
- [4,5]
- Explanation:
9 = 4 + 5 is the shortest run, using two numbers.
Example 2
- Input:
- n = 14
- Output:
- [2,5]
- Explanation:
No run of two or three numbers sums to 14, but 2 + 3 + 4 + 5 = 14, so the answer is [2, 5].
Example 3
- Input:
- n = 16
- Output:
- []
- Explanation:
A power of two has no run of two or more consecutive positive integers, so the answer is empty.
Constraints
1 ≤ n ≤ 1012
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(sqrt(n))
- Space
- O(1)