Count unique paths with given sum in an N-ary Tree
Last Updated :
15 Jul, 2025
Given an integer X and integer N, the task is to find the number of unique paths starting from the root in N-ary tree such that the sum of all these paths is equal to X. The N-ary tree satisfies the following conditions:
- All the nodes have N children and the weight of each edge is distinct and lies in the range [1, N].
- The tree is extended up to infinity.
Examples:
Input: N = 3, X = 2

Output: 2
Explanation: the two paths having path sum equal to 2 are {1, 1} and {2}.
Input: N = 3, X = 6
Output: 24
Naive Approach: The simplest approach is to recursively find all possible ways to obtain path sum equal to X and print the count obtained.
Time Complexity: O(N * X)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Follow the steps below to solve the problem:
- Initialize a dp[] array which for every ith index, stores the count of paths adding up to i.
- For every vertex, iterate form strong>1 to min(X, N), i.e. all possible values of its children and find the number of paths possible with given sum from each node considered.
- Add all the paths made using the edges 1 to N and check if count is already computed or not. If already computed, return the value. Otherwise, recursively count the number of paths with sum equal to current value by considering all possible ways to extend the tree from the current vertex.
- Update the dp[] array and return the count obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mod = (int)1e9 + 7;
// Function for counting total
// no of paths possible with
// the sum is equal to X
ll findTotalPath(int X, int n,
vector<int>& dp)
{
// If the path of the sum
// from the root to current
// node is stored in sum
if (X == 0) {
return 1;
}
ll ans = 0;
// If already computed
if (dp[X] != -1) {
return dp[X];
}
// Count different no of paths
// using all possible ways
for (int i = 1; i <= min(X, n); ++i) {
ans += findTotalPath(
X - i, n, dp)
% mod;
ans %= mod;
}
// Return total no of paths
return dp[X] = ans;
}
// Driver Code
int main()
{
int n = 3, X = 2;
// Stores the number of ways
// to obtains sums 0 to X
vector<int> dp(X + 1, -1);
// Function call
cout << findTotalPath(X, n, dp);
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
static int mod = (int)1e9 + 7;
// Function for counting total
// no of paths possible with
// the sum is equal to X
static int findTotalPath(int X, int n,
ArrayList<Integer> dp)
{
// If the path of the sum
// from the root to current
// node is stored in sum
if (X == 0)
{
return 1;
}
int ans = 0;
// If already computed
if (dp.get(X) != -1)
{
return dp.get(X);
}
// Count different no of paths
// using all possible ways
for(int i = 1; i <= Math.min(X, n); ++i)
{
ans += findTotalPath(X - i, n, dp) % mod;
ans %= mod;
}
// Return total no of paths
dp.set(X, ans);
return ans;
}
// Driver Code
public static void main(String[] args)
{
int n = 3, X = 2;
// Stores the number of ways
// to obtains sums 0 to X
ArrayList<Integer> dp = new ArrayList<Integer>(
Collections.nCopies(X + 1, -1));
// Function call
System.out.print(findTotalPath(X, n, dp));
}
}
// This code is contributed by akhilsaini
Python3
# Python3 program for the above approach
mod = int(1e9 + 7)
# Function for counting total
# no of paths possible with
# the sum is equal to X
def findTotalPath(X, n, dp):
# If the path of the sum
# from the root to current
# node is stored in sum
if (X == 0):
return 1
ans = 0
# If already computed
if (dp[X] != -1):
return dp[X]
# Count different no of paths
# using all possible ways
for i in range(1, min(X, n) + 1):
ans = ans + findTotalPath(X - i, n, dp) % mod;
ans %= mod;
# Return total no of paths
dp[X] = ans
return ans
# Driver Code
if __name__ == '__main__':
n = 3
X = 2
# Stores the number of ways
# to obtains sums 0 to X
dp = [-1] * (X + 1)
# Function call
print(findTotalPath(X, n, dp))
# This code is contributed by akhilsaini
C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static int mod = (int)1e9 + 7;
// Function for counting total
// no of paths possible with
// the sum is equal to X
static int findTotalPath(int X, int n, int[] dp)
{
// If the path of the sum
// from the root to current
// node is stored in sum
if (X == 0)
{
return 1;
}
int ans = 0;
// If already computed
if (dp[X] != -1)
{
return dp[X];
}
// Count different no of paths
// using all possible ways
for(int i = 1; i <= Math.Min(X, n); ++i)
{
ans += findTotalPath(X - i, n, dp) % mod;
ans %= mod;
}
// Return total no of paths
dp[X] = ans;
return ans;
}
// Driver Code
public static void Main()
{
int n = 3, X = 2;
// Stores the number of ways
// to obtains sums 0 to X
int[] dp = new int[X + 1];
Array.Fill(dp, -1);
// Function call
Console.WriteLine(findTotalPath(X, n, dp));
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// Javascript program for the above approach
var mod = 1000000007;
// Function for counting total
// no of paths possible with
// the sum is equal to X
function findTotalPath(X, n, dp)
{
// If the path of the sum
// from the root to current
// node is stored in sum
if (X == 0) {
return 1;
}
var ans = 0;
// If already computed
if (dp[X] != -1) {
return dp[X];
}
// Count different no of paths
// using all possible ways
for (var i = 1; i <= Math.min(X, n); ++i) {
ans += findTotalPath(
X - i, n, dp)
% mod;
ans %= mod;
}
// Return total no of paths
return dp[X] = ans;
}
// Driver Code
var n = 3, X = 2;
// Stores the number of ways
// to obtains sums 0 to X
var dp = Array(X + 1).fill(-1);
// Function call
document.write( findTotalPath(X, n, dp));
</script>
Time Complexity: O(min (N, X))
Auxiliary Space: O(X)
Another approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a Dp array to store the solution of the subproblems.
- Initialize the Dp with base cases
- Fill up the Dp iteratively and get the current value from previous computation.
- Return the final solution stored in dp[X].
Implementation :
C++
// C++ program to count total
// no of paths possible with
// the sum is equal to X
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mod = (int)1e9 + 7;
// Function for counting total
// no of paths possible with
// the sum is equal to X
ll findTotalPath(int X, int n)
{
// Stores the number of ways
// to obtains sums 0 to X
vector<int> dp(X + 1);
// Base case
dp[0] = 1;
// Fill the DP table iteratively
for (int i = 1; i <= X; ++i) {
for (int j = 1; j <= min(i, n); ++j) {
dp[i] += dp[i - j];
dp[i] %= mod;
}
}
// Return total no of paths
return dp[X];
}
// Driver Code
int main()
{
int n = 3, X = 2;
// Function call
cout << findTotalPath(X, n);
}
// this code is contributed by bhardwajji
Java
import java.util.*;
public class Main {
// Function for counting total
// no of paths possible with
// the sum is equal to X
static long findTotalPath(int X, int n) {
// Stores the number of ways
// to obtains sums 0 to X
int mod = (int)1e9 + 7;
int[] dp = new int[X + 1];
// Base case
dp[0] = 1;
// Fill the DP table iteratively
for (int i = 1; i <= X; ++i) {
for (int j = 1; j <= Math.min(i, n); ++j) {
dp[i] += dp[i - j];
dp[i] %= mod;
}
}
// Return total no of paths
return dp[X];
}
// Driver Code
public static void main(String[] args) {
int n = 3, X = 2;
// Function call
System.out.println(findTotalPath(X, n));
}
}
Python3
# Python program to count total
# no of paths possible with
# the sum is equal to X
# Function for counting total
# no of paths possible with
# the sum is equal to X
def findTotalPath(X, n):
# Stores the number of ways
# to obtains sums 0 to X
dp = [0] * (X + 1)
# Base case
dp[0] = 1
# Fill the DP table iteratively
for i in range(1, X + 1):
for j in range(1, min(i, n) + 1):
dp[i] += dp[i - j]
dp[i] %= int(1e9 + 7)
# Return total no of paths
return dp[X]
# Driver Code
if __name__ == "__main__":
n = 3
X = 2
# Function call
print(findTotalPath(X, n))
JavaScript
// Function for counting total
// no of paths possible with
// the sum is equal to X
function findTotalPath(X, n)
{
// Stores the number of ways
// to obtains sums 0 to X
const mod = 1e9 + 7;
const dp = new Array(X + 1).fill(0);
// Base case
dp[0] = 1;
// Fill the DP table iteratively
for (let i = 1; i <= X; ++i) {
for (let j = 1; j <= Math.min(i, n); ++j) {
dp[i] += dp[i - j];
dp[i] %= mod;
}
}
// Return total no of paths
return dp[X];
}
// Driver Code
const n = 3, X = 2;
// Function call
console.log(findTotalPath(X, n));
C#
using System;
public class Program
{
public static int mod = (int)1e9 + 7;
public static long FindTotalPath(int X, int n)
{
// Stores the number of ways
// to obtains sums 0 to X
int[] dp = new int[X + 1];
// Base case
dp[0] = 1;
// Fill the DP table iteratively
for (int i = 1; i <= X; ++i)
{
for (int j = 1; j <= Math.Min(i, n); ++j)
{
dp[i] += dp[i - j];
dp[i] %= mod;
}
}
// Return total no of paths
return dp[X];
}
public static void Main()
{
int n = 3, X = 2;
// Function call
Console.WriteLine(FindTotalPath(X, n));
}
}
//THIS CODE IS CONTRIBUTED BY ZAID
Output:
2
Time Complexity: O( X * min (N, X))
Auxiliary Space: O(X)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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