← Home

829. Consecutive Numbers Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
829

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 829. Consecutive Numbers Sum, the solution in this repository is mainly a two pointers solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • Two pointer + binary search
  • TLE
  • 120 / 170 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are cumsum, consecutiveNumbersSum.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Two pointer + binary search
02//TLE
03//120 / 170 test cases passed.
04class Solution {
05public:
06    long long cumsum(int i, int j){
07        long long a = i+j;
08        long long b = j-i+1;
09        
10        if(a & 1) b >>= 1;
11        else if(b & 1) a >>= 1;
12        
13        return a*b;
14    }
15    
16    int consecutiveNumbersSum(int N) {
17        int count = 0;
18        
19        //find two number i and j s.t. i+(i+1)+...+j = N
20        for(int i = 1; i < N; ++i){
21            /*
22            binary search to find a j s.t.
23            i+(i+1)+...+j = N
24            
25            j's range is [i+1, N-1]
26            */
27            
28            int l = i+1, r = N-1;
29            int j;
30            
31            while(l <= r){
32                j = (l+r) >> 1;
33                
34                // int windowSum = ((i+j)*(j-i+1))>>1;
35                long long windowSum = cumsum(i, j);
36                // cout << "[" << i << ", " << j << "]: " << windowSum << endl;
37                
38                if(windowSum < N){
39                    l = j+1;
40                }else if(windowSum > N){
41                    r = j-1;
42                }else{
43                    ++count;
44                    break;
45                }
46            }
47        }
48        
49        return count+1;
50    }
51};
52
53//Math
54//https://leetcode.com/problems/consecutive-numbers-sum/discuss/129015/5-lines-C%2B%2B-solution-with-detailed-mathematical-explanation.
55//Runtime: 8 ms, faster than 33.16% of C++ online submissions for Consecutive Numbers Sum.
56//Memory Usage: 5.9 MB, less than 71.57% of C++ online submissions for Consecutive Numbers Sum.
57class Solution {
58public:
59    int consecutiveNumbersSum(int N) {
60        int count = 0;
61        
62        /*
63        k terms:
64        x + (x+1) + (x+2) + ... + (x+k-1) = N
65        kx + k*(k-1)/2 = N
66        (N - k*(k-1)/2) % k == 0 means
67        there is a window starting from x with size k sum to N
68
69        upper bound for k:
70        (N - k*(k-1)/2) should be greater than 0,
71        so N > k*(k-1)/2,
72        k*k-k < 2*N,
73        (k-1)*(k-1) < k*k-k < 2*N,
74        k-1 < sqrt(2*N),
75        k < sqrt(2*N)+1
76        */
77        for(int k = 2; k < sqrt(2*N)+1; ++k){
78            /*
79            https://leetcode.com/problems/consecutive-numbers-sum/discuss/129015/5-lines-C++-solution-with-detailed-mathematical-explanation./369550
80            N=15 and k=6,
81            the approximate condition: k < sqrt(2*N)+1 -> (k-1)*(k-1) < 2*N
82            -> 5*5 < 2*15, this allows k=6.
83            but the actual condition: 
84            N - k*(k-1)/2 > 0 -> k*(k-1) < 2*N -> 6*5 < 2*15,
85            this doesn't allow.
86            So our condition "k < sqrt(2*N)+1" is not tight enough. 
87            For N=15 it allows k=6 numbers starting from 0 (0,1,2,3,4,5) to be considered.
88            so we still need to check "k*(k-1) < 2*N"
89            */
90            if((k*(k-1) < 2*N) && ((N - k*(k-1)/2) % k == 0)) ++count;
91        }
92        
93        return count+1;
94    }
95};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.