Number of ways to write N as a sum of K non-negative integers
Last Updated :
12 Jul, 2025
Given two positive integers N and K, the task is to count the number of ways to write N as a sum of K non-negative integers.
Examples:
Input: N = 2, K = 3
Output: 6
Explanation:
The total ways in which 2 can be split into K non-negative integers are:
1. (0, 0, 2)
2. (0, 2, 0)
3. (2, 0, 0)
4. (0, 1, 1)
5. (1, 0, 1)
6. (1, 1, 0)
Input: N = 3, K = 2
Output: 4
Explanation:
The total ways in which can be split 3 into 2 non-negative integers are:
1. (0, 3)
2. (3, 0)
3. (1, 2)
4. (2, 1)
Approach: This problem can be solved using Dynamic Programming. Below are the steps:
- Initialize a 2D array as dp[K+1][N+1] where rows correspond to the number of the element we pick and columns correspond to the corresponding sum.
- Start filling the first row and column with taking sum as K in the above table dp[][].
- Suppose we reach at ith row and jth column, i.e i elements we can pick and we need to get sum j. To calculate the number of ways till dp[i][j] choose first (i - 1) elements and next (j - x) where x is the sum of first (i - 1) elements.
- Repeat the above steps to fill the dp[][] array.
- The value dp[n][m] will give the required result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
int countWays(int n, int m)
{
// Initialise dp[][] array
int dp[m + 1][n + 1];
// Only 1 way to choose the value
// with sum K
for (int i = 0; i <= n; i++) {
dp[1][i] = 1;
}
// Initialise sum
int sum;
for (int i = 2; i <= m; i++) {
for (int j = 0; j <= n; j++) {
sum = 0;
// Count the ways from previous
// states
for (int k = 0; k <= j; k++) {
sum += dp[i - 1][k];
}
// Update the sum
dp[i][j] = sum;
}
}
// Return the final count of ways
return dp[m][n];
}
// Driver Code
int main()
{
int N = 2, K = 3;
// Function call
cout << countWays(N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m)
{
// Initialise dp[][] array
int [][]dp = new int[m + 1][n + 1];
// Only 1 way to choose the value
// with sum K
for(int i = 0; i <= n; i++)
{
dp[1][i] = 1;
}
// Initialise sum
int sum;
for(int i = 2; i <= m; i++)
{
for(int j = 0; j <= n; j++)
{
sum = 0;
// Count the ways from previous
// states
for(int k = 0; k <= j; k++)
{
sum += dp[i - 1][k];
}
// Update the sum
dp[i][j] = sum;
}
}
// Return the final count of ways
return dp[m][n];
}
// Driver Code
public static void main(String[] args)
{
int N = 2, K = 3;
// Function call
System.out.print(countWays(N, K));
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
# Function to count the number of ways
# to write N as sum of k non-negative
# integers
def countWays(n, m):
# Initialise dp[][] array
dp = [[ 0 for i in range(n + 1)]
for i in range(m + 1)]
# Only 1 way to choose the value
# with sum K
for i in range(n + 1):
dp[1][i] = 1
# Initialise sum
sum = 0
for i in range(2, m + 1):
for j in range(n + 1):
sum = 0
# Count the ways from previous
# states
for k in range(j + 1):
sum += dp[i - 1][k]
# Update the sum
dp[i][j] = sum
# Return the final count of ways
return dp[m][n]
# Driver Code
if __name__ == '__main__':
N = 2
K = 3
# Function call
print(countWays(N, K))
# This code is contributed by Mohit Kumar
C#
// C# program for the above approach
using System;
class GFG{
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m)
{
// Initialise [,]dp array
int [,]dp = new int[m + 1, n + 1];
// Only 1 way to choose the value
// with sum K
for(int i = 0; i <= n; i++)
{
dp[1, i] = 1;
}
// Initialise sum
int sum;
for(int i = 2; i <= m; i++)
{
for(int j = 0; j <= n; j++)
{
sum = 0;
// Count the ways from previous
// states
for(int k = 0; k <= j; k++)
{
sum += dp[i - 1, k];
}
// Update the sum
dp[i, j] = sum;
}
}
// Return the readonly count of ways
return dp[m, n];
}
// Driver Code
public static void Main(String[] args)
{
int N = 2, K = 3;
// Function call
Console.Write(countWays(N, K));
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// Javascript program for the above approach
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
function countWays(n, m)
{
// Initialise dp[][] array
var dp = Array.from(Array(m+1), ()=>Array(n+1));
// Only 1 way to choose the value
// with sum K
for (var i = 0; i <= n; i++) {
dp[1][i] = 1;
}
// Initialise sum
var sum;
for (var i = 2; i <= m; i++) {
for (var j = 0; j <= n; j++) {
sum = 0;
// Count the ways from previous
// states
for (var k = 0; k <= j; k++) {
sum += dp[i - 1][k];
}
// Update the sum
dp[i][j] = sum;
}
}
// Return the final count of ways
return dp[m][n];
}
// Driver Code
var N = 2, K = 3;
// Function call
document.write( countWays(N, K));
</script>
Time Complexity: O(K*N2)
Auxiliary Space Complexity: O(N*K)
Optimized Approach: The idea of calculating the sum and then storing the count increases the time complexity. We can decrease it by storing the sum in the above dp[][] table.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
int countWays(int n, int m)
{
// Initialise dp[][] array
int dp[m + 1][n + 1];
// Fill the dp[][] with sum = m
for (int i = 0; i <= n; i++) {
dp[1][i] = 1;
if (i != 0) {
dp[1][i] += dp[1][i - 1];
}
}
// Iterate the dp[][] to fill the
// dp[][] array
for (int i = 2; i <= m; i++) {
for (int j = 0; j <= n; j++) {
// Condition for first column
if (j == 0) {
dp[i][j] = dp[i - 1][j];
}
// Else fill the dp[][] with
// sum till (i, j)
else {
dp[i][j] = dp[i - 1][j];
// If reach the end, then
// return the value
if (i == m && j == n) {
return dp[i][j];
}
// Update at current index
dp[i][j] += dp[i][j - 1];
}
}
}
}
// Driver Code
int main()
{
int N = 2, K = 3;
// Function call
cout << countWays(N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m)
{
// Initialise dp[][] array
int [][]dp = new int[m + 1][n + 1];
// Fill the dp[][] with sum = m
for (int i = 0; i <= n; i++)
{
dp[1][i] = 1;
if (i != 0)
{
dp[1][i] += dp[1][i - 1];
}
}
// Iterate the dp[][] to fill the
// dp[][] array
for (int i = 2; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
// Condition for first column
if (j == 0)
{
dp[i][j] = dp[i - 1][j];
}
// Else fill the dp[][] with
// sum till (i, j)
else
{
dp[i][j] = dp[i - 1][j];
// If reach the end, then
// return the value
if (i == m && j == n)
{
return dp[i][j];
}
// Update at current index
dp[i][j] += dp[i][j - 1];
}
}
}
return Integer.MIN_VALUE;
}
// Driver Code
public static void main(String[] args)
{
int N = 2, K = 3;
// Function call
System.out.print(countWays(N, K));
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 program for the above approach
# Function to count the number of ways
# to write N as sum of k non-negative
# integers
def countWays(n, m):
# Initialise dp[][] array
dp = [[0 for i in range(n + 1)]
for j in range(m + 1)]
# Fill the dp[][] with sum = m
for i in range(n + 1):
dp[1][i] = 1
if (i != 0):
dp[1][i] += dp[1][i - 1]
# Iterate the dp[][] to fill the
# dp[][] array
for i in range(2, m + 1):
for j in range(n + 1):
# Condition for first column
if (j == 0):
dp[i][j] = dp[i - 1][j]
# Else fill the dp[][] with
# sum till (i, j)
else:
dp[i][j] = dp[i - 1][j]
# If reach the end, then
# return the value
if (i == m and j == n):
return dp[i][j]
# Update at current index
dp[i][j] += dp[i][j - 1]
# Driver Code
N = 2
K = 3
# Function call
print(countWays(N, K))
# This code is contributed by ShubhamCoder
C#
// C# program for the above approach
using System;
class GFG{
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m)
{
// Initialise dp[][] array
int [,]dp = new int[m + 1, n + 1];
// Fill the dp[][] with sum = m
for (int i = 0; i <= n; i++)
{
dp[1, i] = 1;
if (i != 0)
{
dp[1, i] += dp[1, i - 1];
}
}
// Iterate the dp[][] to fill the
// dp[][] array
for (int i = 2; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
// Condition for first column
if (j == 0)
{
dp[i, j] = dp[i - 1, j];
}
// Else fill the dp[][] with
// sum till (i, j)
else
{
dp[i, j] = dp[i - 1, j];
// If reach the end, then
// return the value
if (i == m && j == n)
{
return dp[i, j];
}
// Update at current index
dp[i, j] += dp[i, j - 1];
}
}
}
return Int32.MinValue;
}
// Driver Code
public static void Main()
{
int N = 2, K = 3;
// Function call
Console.Write(countWays(N, K));
}
}
// This code is contributed by Code_Mech
JavaScript
<script>
// JavaScript program for the above approach
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
function countWays(n,m)
{
// Initialise dp[][] array
let dp = new Array(m + 1);
for(let i=0;i<m+1;i++)
{
dp[i]=new Array(n+1);
for(let j=0;j<n+1;j++)
dp[i][j]=0;
}
// Fill the dp[][] with sum = m
for (let i = 0; i <= n; i++)
{
dp[1][i] = 1;
if (i != 0)
{
dp[1][i] += dp[1][i - 1];
}
}
// Iterate the dp[][] to fill the
// dp[][] array
for (let i = 2; i <= m; i++)
{
for (let j = 0; j <= n; j++)
{
// Condition for first column
if (j == 0)
{
dp[i][j] = dp[i - 1][j];
}
// Else fill the dp[][] with
// sum till (i, j)
else
{
dp[i][j] = dp[i - 1][j];
// If reach the end, then
// return the value
if (i == m && j == n)
{
return dp[i][j];
}
// Update at current index
dp[i][j] += dp[i][j - 1];
}
}
}
return Number.MIN_VALUE;
}
// Driver Code
let N = 2, K = 3;
// Function call
document.write(countWays(N, K));
// This code is contributed by patel2127
</script>
Time Complexity: O(K*N)
Auxiliary Space: O(N*K)
Efficient Approach : using array instead of 2d matrix to optimize space complexity
In previous code we can se that dp[i][j] is dependent upon dp[i-1][j] or dp[i][j-1] so we can assume that dp[i-1] is previous row and dp[i] is current row.
Implementations Steps :
- Create two vectors prev and curr each of size n+1, where n is a given number.
- Initialize them with base cases.
- Now In previous code change dp[i] to curr and change dp[i-1] to prev to keep track only of the two main rows.
- After every iteration update previous row to current row to iterate further.
Implementation :
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
int countWays(int n, int m)
{
// initialize 2 vectors determining 2 rows of DP
vector<int>prev(n+1 , 0);
vector<int>curr(n+1 , 0);
// Base case initialize the prev vector
for (int i = 0; i <= n; i++) {
prev[i] = 1;
if (i != 0) {
prev[i] += prev[i - 1];
}
}
// fill curr vector by the help of prev vector
for (int i = 2; i <= m; i++) {
for (int j = 0; j <= n; j++) {
// Condition for first column
if (j == 0) {
curr[j] = prev[j];
}
// Else fill the curr with
// sum till (i, j)
else {
curr[j] = prev[j];
// If reach the end, then
// return the value
if (i == m && j == n) {
return curr[j];
}
// Update at current index
curr[j] += curr[j - 1];
}
}
prev = curr;
}
}
// Driver Code
int main()
{
int N = 2, K = 3;
// Function call
cout << countWays(N, K);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m) {
// initialize 2 vectors determining 2 rows of DP
int[] prev = new int[n + 1];
int[] curr = new int[n + 1];
// Base case initialize the prev vector
for (int i = 0; i <= n; i++) {
prev[i] = 1;
if (i != 0) {
prev[i] += prev[i - 1];
}
}
// fill curr vector by the help of prev vector
for (int i = 2; i <= m; i++) {
for (int j = 0; j <= n; j++) {
// Condition for first column
if (j == 0) {
curr[j] = prev[j];
}
// Else fill the curr with
// sum till (i, j)
else {
curr[j] = prev[j];
// If reach the end, then
// return the value
if (i == m && j == n) {
return curr[j];
}
// Update at current index
curr[j] += curr[j - 1];
}
}
// Update prev array
prev = curr.clone();
}
return curr[n];
}
// Driver Code
public static void main(String[] args) {
int N = 2, K = 3;
// Function call
System.out.println(countWays(N, K));
}
}
Python3
# Define a function to count the number of ways to write N as sum of K non-negative integers
def countWays(n, m):
# initialize 2 lists determining 2 rows of DP
prev = [0] * (n + 1)
curr = [0] * (n + 1)
# Base case initialize the prev list
for i in range(n + 1):
prev[i] = 1
if i != 0:
prev[i] += prev[i - 1]
# fill curr list by the help of prev list
for i in range(2, m + 1):
for j in range(n + 1):
# Condition for first column
if j == 0:
curr[j] = prev[j]
# Else fill the curr with sum till (i, j)
else:
curr[j] = prev[j]
# If reach the end, then return the value
if i == m and j == n:
return curr[j]
# Update at current index
curr[j] += curr[j - 1]
prev = curr.copy()
# Driver Code
N = 2
K = 3
# Function call
print(countWays(N, K))
C#
using System;
class GFG
{
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
static int countWays(int n, int m)
{
// Initialize 2 vectors determining 2 rows of DP
int[] prev = new int[n + 1];
int[] curr = new int[n + 1];
// Base case initialize the prev vector
for (int i = 0; i <= n; i++)
{
prev[i] = 1;
if (i != 0)
{
prev[i] += prev[i - 1];
}
}
// Fill curr vector by the help of prev vector
for (int i = 2; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
// Condition for first column
if (j == 0)
{
curr[j] = prev[j];
}
// Else fill the curr with
// sum till (i, j)
else
{
curr[j] = prev[j];
// If reach the end, then
// return the value
if (i == m && j == n)
{
return curr[j];
}
// Update at current index
curr[j] += curr[j - 1];
}
}
prev = curr;
}
return curr[n];
}
// Driver Code
static void Main()
{
int N = 2, K = 3;
// Function call
Console.WriteLine(countWays(N, K));
}
}
JavaScript
// Function to count the number of ways
// to write N as sum of k non-negative
// integers
function countWays(n, m) {
// initialize 2 arrays determining 2 rows of DP
let prev = new Array(n + 1).fill(0);
let curr = new Array(n + 1).fill(0);
// Base case initialize the prev array
for (let i = 0; i <= n; i++) {
prev[i] = 1;
if (i != 0) {
prev[i] += prev[i - 1];
}
}
// fill curr array by the help of prev array
for (let i = 2; i <= m; i++) {
for (let j = 0; j <= n; j++) {
// Condition for first column
if (j == 0) {
curr[j] = prev[j];
}
// Else fill the curr with
// sum till (i, j)
else {
curr[j] = prev[j];
// If reach the end, then
// return the value
if (i == m && j == n) {
return curr[j];
}
// Update at current index
curr[j] += curr[j - 1];
}
}
prev = [...curr];
}
}
// Driver Code
let N = 2,
K = 3;
// Function call
console.log(countWays(N, K));
Time Complexity: O(K*N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem