#829

Consecutive Numbers Sum

Hard
MathEnumerationMathematical EnumerationTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(sqrt(n))
Space
O(1)
O(1)
💡

Intuition

Time O(sqrt(n))Space O(1)

The optimal approach leverages the mathematical properties of consecutive sums. We can express n as a sum of k consecutive integers starting from a number x, which leads to a formula that can be rearranged to find valid sequences efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a count variable to 0.
  2. 2Step 2: Loop through possible lengths k from 1 to sqrt(2*n).
  3. 3Step 3: For each k, check if (n - k*(k-1)/2) is divisible by k.
  4. 4Step 4: If it is divisible, increment the count.
  5. 5Step 5: Return the count.
solution.py8 lines
1def consecutiveNumbersSum(n):
2    count = 0
3    k = 1
4    while k * (k + 1) // 2 <= n:
5        if (n - k * (k - 1) // 2) % k == 0:
6            count += 1
7        k += 1
8    return count

Complexity note: The time complexity is O(sqrt(n)) because we only loop through potential lengths k up to the square root of n, which is much more efficient than the brute force approach.

  • 1The number of ways to express n as a sum of consecutive integers is related to the divisors of n.
  • 2Each valid sequence can be represented with a starting point and a length, leading to a mathematical formula.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.