Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of series till N-th term whose i-th term is i^k - (i-1)^k
Next article icon

Print the sequence of size N in which every term is sum of previous K terms

Last Updated : 15 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers N and K, the task is to generate a series of N terms in which every term is sum of the previous K terms.
Note: The first term of the series is 1. if there are not enough previous terms, then other terms are supposed to be 0.
Examples: 

Input: N = 8, K = 3 
Output: 1 1 2 4 7 13 24 44 
Explanation: 
Series is generated as follows: 
a[0] = 1 
a[1] = 1 + 0 + 0 = 1 
a[2] = 1 + 1 + 0 = 2 
a[3] = 2 + 1 + 1 = 4 
a[4] = 4 + 2 + 1 = 7 
a[5] = 7 + 4 + 2 = 13 
a[6] = 13 + 7 + 4 = 24 
a[7] = 24 + 13 + 7 = 44
Input: N = 10, K = 4 
Output: 1 1 2 4 8 15 29 56 108 208 

Naive Approach: The idea is to run two loops to generate N terms of series. Below is the illustration of the steps:  

  • Traverse the first loop from 0 to N – 1, to generate every term of the series.
  • Run a loop from max(0, i – K) to i to compute the sum of the previous K terms.
  • Update the sum to the current index of series as the current term.

Below is the implementation of the above approach: 

C++




// C++ implementation to find the
// series in which every term is
// sum of previous K terms
 
#include <iostream>
 
using namespace std;
 
// Function to generate the
// series in the form of array
void sumOfPrevK(int N, int K)
{
    int arr[N];
    arr[0] = 1;
 
    // Pick a starting point
    for (int i = 1; i < N; i++) {
        int j = i - 1, count = 0,
            sum = 0;
        // Find the sum of all
        // elements till count < K
        while (j >= 0 && count < K) {
            sum += arr[j];
            j--;
            count++;
        }
        // Find the value of
        // sum at i position
        arr[i] = sum;
    }
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 10, K = 4;
    sumOfPrevK(N, K);
    return 0;
}
 
 

Java




// Java implementation to find the
// series in which every term is
// sum of previous K terms
 
class Sum {
    // Function to generate the
    // series in the form of array
    void sumOfPrevK(int N, int K)
    {
        int arr[] = new int[N];
        arr[0] = 1;
 
        // Pick a starting point
        for (int i = 1; i < N; i++) {
            int j = i - 1, count = 0,
                sum = 0;
            // Find the sum of all
            // elements till count < K
            while (j >= 0 && count < K) {
                sum += arr[j];
                j--;
                count++;
            }
            // Find the value of
            // sum at i position
            arr[i] = sum;
        }
        for (int i = 0; i < N; i++) {
            System.out.print(arr[i] + " ");
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        Sum s = new Sum();
        int N = 10, K = 4;
        s.sumOfPrevK(N, K);
    }
}
 
 

Python3




# Python3 implementation to find the
# series in which every term is
# sum of previous K terms
 
# Function to generate the
# series in the form of array
def sumOfPrevK(N, K):
    arr = [0 for i in range(N)]
    arr[0] = 1
 
    # Pick a starting point
    for i in range(1,N):
        j = i - 1
        count = 0
        sum = 0
         
        # Find the sum of all
        # elements till count < K
        while (j >= 0 and count < K):
            sum = sum + arr[j]
            j = j - 1
            count = count + 1
 
        # Find the value of
        # sum at i position
        arr[i] = sum
 
    for i in range(0, N):
        print(arr[i])
 
# Driver Code
N = 10
K = 4
sumOfPrevK(N, K)
 
# This code is contributed by Sanjit_Prasad
 
 

C#




// C# implementation to find the
// series in which every term is
// sum of previous K terms
using System;
 
class Sum {
    // Function to generate the
    // series in the form of array
    void sumOfPrevK(int N, int K)
    {
        int []arr = new int[N];
        arr[0] = 1;
  
        // Pick a starting point
        for (int i = 1; i < N; i++) {
            int j = i - 1, count = 0,
                sum = 0;
 
            // Find the sum of all
            // elements till count < K
            while (j >= 0 && count < K) {
                sum += arr[j];
                j--;
                count++;
            }
 
            // Find the value of
            // sum at i position
            arr[i] = sum;
        }
        for (int i = 0; i < N; i++) {
            Console.Write(arr[i] + " ");
        }
    }
  
    // Driver Code
    public static void Main(String []args)
    {
        Sum s = new Sum();
        int N = 10, K = 4;
        s.sumOfPrevK(N, K);
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript implementation to find the
// series in which every term is
// sum of previous K terms
 
// Function to generate the
// series in the form of array
function sumOfPrevK(N, K)
{
    let arr = new Array(N);
    arr[0] = 1;
 
    // Pick a starting point
    for (let i = 1; i < N; i++) {
        let j = i - 1, count = 0, sum = 0;
        // Find the sum of all
        // elements till count < K
        while (j >= 0 && count < K) {
            sum += arr[j];
            j--;
            count++;
        }
        // Find the value of
        // sum at i position
        arr[i] = sum;
    }
    for (let i = 0; i < N; i++) {
        document.write(arr[i] + " ");
    }
}
 
// Driver Code
 
let N = 10, K = 4;
sumOfPrevK(N, K);
 
// This code is contributed by _saurabh_jaiswal
 
</script>
 
 

Output:

1 1 2 4 8 15 29 56 108 208 

Performance analysis: 

  • Time Complexity: O(N * K)
  • Space Complexity: O(N)

Improved Approach: The idea is to store the current sum in a variable and subtract the last Kth term in every step and add the last term into the pre-sum to compute every term of the series.
Below is the implementation of the above approach:  

C++




#include <iostream>
#include <vector>
using namespace std;
 
void sumOfPrevK(int N, int K)
{
    vector<int> arr(N);
    // initialize the 0th index with 1
    arr[0] = 1;
 
    // initialize sliding window and sum
    // the sum stores the sum of the previous window
    int start = 0, end = 1, sum = 1;
 
    while (end < N) {
        // if size of the sliding window exceeds K
        if (end - start > K) {
            // decrease the window size and update the sum
            sum -= arr[start];
            ++start;
        }
        // update the current element by sum of the previous
        // K elements
        arr[end] = sum;
        // Update the sum by adding the current element
        sum += arr[end];
        // increase the window size
        ++end;
    }
 
    for (int i = 0; i < N; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
 
int main()
{
    int N = 10, K = 4;
    sumOfPrevK(N, K);
    return 0;
}
 
 

Java




// Java code to implement the approach
import java.util.*;
 
class GFG {
  static void sumOfPrevK(int N, int K)
  {
    ArrayList<Integer> arr = new ArrayList<Integer>();
    for (int i = 0; i < N; i++)
      arr.add(0);
 
    // initialize the 0th index with 1
    arr.set(0, 1);
 
    // initialize sliding window and sum
    // the sum stores the sum of the previous window
    int start = 0, end = 1, sum = 1;
 
    while (end < N) {
      // if size of the sliding window exceeds K
      if (end - start > K) {
        // decrease the window size and update the
        // sum
        sum -= arr.get(start);
        ++start;
      }
 
      // update the current element by sum of the
      // previous K elements
      arr.set(end, sum);
      // Update the sum by adding the current element
      sum += arr.get(end);
 
      // increase the window size
      ++end;
    }
 
    for (int i = 0; i < N; ++i) {
      System.out.print(arr.get(i) + " ");
    }
    System.out.print("\n");
  }
 
  public static void main(String[] args)
  {
    int N = 10, K = 4;
    sumOfPrevK(N, K);
  }
}
 
// This code is contributed by phasing17
 
 

Python3




# Python3 code to implement the approach
def sumsOfPrevK(N, K):
 
    arr = [0 for _ in range(N)]
    # initialize the 0th index with 1
    arr[0] = 1
 
    # initialize sliding window and sums
    # the sums stores the sums of the previous window
    start = 0
    end = 1
    sums = 1
 
    while (end < N):
        # if size of the sliding window exceeds K
        if (end - start > K):
           
            # decrease the window size and update the sums
            sums -= arr[start]
            start += 1
 
        # update the current element by sums of the previous
        # K elements
        arr[end] = sums
         
        # Update the sums by adding the current element
        sums += arr[end]
         
        # increase the window size
        end += 1
 
    print(*arr)
 
# Driver Code
N = 10
K = 4
sumsOfPrevK(N, K)
 
# This code is contributed by phasing17
 
 

C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
class GFG
{
  static void sumOfPrevK(int N, int K)
  {
    List<int> arr = new List<int>() ;
    for (int i = 0; i < N; i++)
      arr.Add(0);
 
    // initialize the 0th index with 1
    arr[0] = 1;
 
    // initialize sliding window and sum
    // the sum stores the sum of the previous window
    int start = 0, end = 1, sum = 1;
 
    while (end < N) {
      // if size of the sliding window exceeds K
      if (end - start > K) {
        // decrease the window size and update the sum
        sum -= arr[start];
        ++start;
      }
 
      // update the current element by sum of the previous
      // K elements
      arr[end] = sum;
      // Update the sum by adding the current element
      sum += arr[end];
 
      // increase the window size
      ++end;
    }
 
    for (int i = 0; i < N; ++i) {
      Console.Write(arr[i] + " ");
    }
    Console.Write("\n");
  }
 
  public static void Main(string[] args)
  {
    int N = 10, K = 4;
    sumOfPrevK(N, K);
  }
}
 
 
// This code is contributed by phasing17
 
 

Javascript




// JavaScript code to implement the approach
 
 
function sumOfPrevK(N, K)
{
    let arr = new Array(N);
    // initialize the 0th index with 1
    arr[0] = 1;
 
    // initialize sliding window and sum
    // the sum stores the sum of the previous window
    let start = 0, end = 1, sum = 1;
 
    while (end < N) {
        // if size of the sliding window exceeds K
        if (end - start > K) {
            // decrease the window size and update the sum
            sum -= arr[start];
            ++start;
        }
        // update the current element by sum of the previous
        // K elements
        arr[end] = sum;
        // Update the sum by adding the current element
        sum += arr[end];
        // increase the window size
        ++end;
    }
 
    console.log(arr.join(" "))
    
}
 
 
// Driver Code
 
let N = 10, K = 4;
sumOfPrevK(N, K);
 
 
 
// This code is contributed by phasing17
 
 

Complexity analysis: 

  • Time Complexity: O(N)
  • Space Complexity: O(N)

Another Approach: Sliding Window

The idea is to use a fixed-size sliding window of size K to get the sum of previous K elements. 

  • Initialize the answer array with arr[0] = 1 and a variable sum = 1, representing the sum of the last K elements. Initially, the previous sum = 1. (If there are less than K elements in the last window, then the sum will store the sum of all the elements in the window)
  • The sliding window is initialized by making start = 0 and end = 1.
  • If the window size exceeds K, then decrement arr[start] from sum and increment start to update the window size and sum. 
  • Make arr[end] = sum, which will be the sum of the previous K elements, and increment sum by arr[end] for the next iteration. Increment end by 1. 
Output
1 1 2 4 8 15 29 56 108 208 

Complexity analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(N)


Next Article
Sum of series till N-th term whose i-th term is i^k - (i-1)^k
author
_shreya_garg_
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
  • Mathematical
  • series
Practice Tags :
  • Arrays
  • Mathematical
  • series

Similar Reads

  • Nth term of given recurrence relation having each term equal to the product of previous K terms
    Given two positive integers N and K and an array F[] consisting of K positive integers. The Nth term of the recurrence relation is given by: FN = FN - 1 * FN - 2 * FN - 3 *.......* FN - K The task is to find the Nth term of the given recurrence relation. As the Nth term can be very large, print the
    15+ min read
  • Nth term of a sequence formed by sum of current term with product of its largest and smallest digit
    Given two numbers N and K, where K represents the starting term of the sequence. The task is to find the Nth term of a sequence formed by sum of current term with product of largest and smallest digit of current term, i.e., AN+1 = AN + max(digits of AN) * min(digits of AN) Examples: Input: K = 1, N
    6 min read
  • Sum of series till N-th term whose i-th term is i^k - (i-1)^k
    Given value of N and K. The task is to find the sum of series till N-th term whose i-th term is given by Ti = ik + (i - 1)k. Since the sum of the series can be very large, compute its sum modulo 1000000007. Example: Input : n = 5, k = 2 Output: 25 first 5 term of the series : T1 = ( 1 )2 + ( 1 - 1 )
    9 min read
  • Sequences of given length where every element is more than or equal to twice of previous
    Given two integers n and m, the task is to determine the total number of special sequences of length n such that: seq[i+1] >= 2 * seq[i]seq[i] > 0seq[i] <= mExamples : Input: n = 4, m = 10Output: 4Explanation: The sequences are [1, 2, 4, 8], [1, 2, 4, 9], [1, 2, 4, 10], [1, 2, 5, 10] Input:
    15+ min read
  • Find the sum of all the terms in the n-th row of the given series
    Find the sum of all the terms in the nth row of the series given below. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 .......................... ............................ (so on) Examples: Input : n = 2 Output : 18 terms in 2nd row and their sum sum = (3 + 4 + 5 + 6) = 18 Input : n = 4 Outpu
    6 min read
  • Count the occurrence of Nth term in first N terms of Van Eck's sequence
    Prerequisite: Van Eck's sequence Given a positive integer N, the task is to count the occurrences of Nth term in the first N terms of Van Eck's sequence. Examples: Input: N = 5 Output: 1 Explanation: First 5 terms of Van Eck's Sequence 0, 0, 1, 0, 2 Occurrence of 5th term i.e 2 = 1 Input: 11 Output:
    15 min read
  • Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum
    Given two integers N and K, the task is to find the Nth Subset from the sequence of subsets generated from the powers of K i.e. {1, K1, K2, K3, .....} such that the subsets are arranged in increasing order of their sum, the task is to find the Nth subset from the sequence. Examples: Input: N = 5, K
    10 min read
  • Find first K characters in Nth term of the Thue-Morse sequence
    Given two integers N and K, the task is to print the first K bits of the Nth term of the Thue-Morse sequence. The Thue-Morse sequence is a binary sequence. It starts with a "0" as its first term. And then after the next term is generated by replacing "0" with "01" and "1" with "10". Examples: Input:
    6 min read
  • Min Operations for Target Sum in Special Sequence
    Given integer X (1 <= X <= 1018) and integer K (1 <= K <= 109) representing sequence {1, 2, ..., K - 2, K - 1, K, K - 1, K - 2, ....., 2, 1} of size 2 * K - 1, the task for this problem is to find minimum number of operations required to find sum at least X. In one operation remove the f
    12 min read
  • Sum of first N terms of Quadratic Sequence 3 + 7 + 13 + ...
    Given a quadratic series as given below, the task is to find the sum of the first n terms of this series. Sn = 3 + 7 + 13 + 21 + 31 + ..... + upto n terms Examples: Input: N = 3 Output: 23 Input: N = 4 Output: 44 Approach: Let the series be represented as Sn = 3 + 7 + 13 + ... + tn where Sn represen
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences