How to Optimize Auxiliary Space Of a DP Solution.
Last Updated :
23 Jul, 2025
Space Optimization in Dynamic Programming Problems:
This is a way to optimize the Auxlillary space of a solution which also produces the same correct result as before optimization.
How to Optimize Space in the DP Solution:
The idea is to store only the values that are necessary to generate the result for the current state of the DP solution.
Avoid storing the states that do not contribute to the current state.
Follow the below steps to optimize the space of any DP solution:
- Identify the transition of states and observe clearly what states are needed to calculate the current state.
- Store all the previous states that are needed to calculate the current state separately in variables or arrays.
- After calculating the current state, update the previous states for the next state that is to be calculated.
- The result is stored in the first previous state if there are multiple previous states.
Let's see these steps with examples,
Space optimization from O(N)Linear to O(1)Constant:
Calculate the nth Fibonacci number:
State: f[i] --> Denotes the ith Fibonacci number.
Transition: f[i] = f[i-1] + f[i-2]
Code:
C++
// C++ program for Fibonacci Series
// using Dynamic Programming
#include <bits/stdc++.h>
using namespace std;
class GFG {
public:
int fib(int n)
{
// Declare an array to store
// Fibonacci numbers.
// 1 extra to handle
// case, n = 0
int f[n + 2];
int i;
// 0th and 1st number of the
// series are 0 and 1
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
// Add the previous 2 numbers
// in the series and store it
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}
};
// Driver code
int main()
{
GFG g;
int n = 9;
cout << g.fib(n);
return 0;
}
Java
public class Fibonacci {
public int fib(int n) {
// Declare an array to store Fibonacci numbers.
// 1 extra to handle case, n = 0
int[] f = new int[n + 2];
int i;
// 0th and 1st number of the series are 0 and 1
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
// Add the previous 2 numbers in the series and store it
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}
// Driver code
public static void main(String[] args) {
Fibonacci fibonacci = new Fibonacci();
int n = 9;
System.out.println(fibonacci.fib(n));
}
}
C#
using System;
public class Fibonacci
{
public int Fib(int n)
{
// Declare an array to store Fibonacci numbers.
// 1 extra to handle case, n = 0
int[] f = new int[n + 2];
int i;
// 0th and 1st number of the series are 0 and 1
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
{
// Add the previous 2 numbers in the series and store it
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}
// Driver code
public static void Main(string[] args)
{
Fibonacci fibonacci = new Fibonacci();
int n = 9;
Console.WriteLine(fibonacci.Fib(n));
}
}
Javascript
class Fibonacci {
fib(n) {
// Declare an array to store Fibonacci numbers.
// 1 extra to handle case, n = 0
const f = new Array(n + 2);
let i;
// 0th and 1st number of the series are 0 and 1
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
// Add the previous 2 numbers in the series and store it
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}
}
// Driver code
const fibonacci = new Fibonacci();
const n = 9;
console.log(fibonacci.fib(n));
Python3
class GFG:
def fib(self, n):
# Declare a list to store Fibonacci numbers.
# 1 extra to handle the case, n = 0
f = [0] * (n + 2)
# 0th and 1st number of the series are 0 and 1
f[0] = 0
f[1] = 1
for i in range(2, n + 1):
# Add the previous 2 numbers
# in the series and store it
f[i] = f[i - 1] + f[i - 2]
return f[n]
# Driver code
if __name__ == "__main__":
g = GFG()
n = 9
print(g.fib(n))
Time Complexity: O(N)
Auxiliary space: O(N)
Steps To Optimise the Space in action for above problem:
- If we observe clearly, To generate the f[i] we need only two previous states that is f[i-1] and f[i-2].
- Store previous two states in prev1 and prev2 and current in curr.
- After calculating the curr, update the prev2 as prev1 and prev1 as curr.
- At the end, result is stored in the prev1.
Space Optimised Code:
C++
// Fibonacci Series using Space Optimized Method
#include <bits/stdc++.h>
using namespace std;
int fib(int n)
{
int prev2 = 0;
if (n == 0)
return prev2;
int prev1 = 1;
int curr;
for (int i = 2; i <= n; i++) {
curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
// Driver code
int main()
{
int n = 9;
cout << fib(n);
return 0;
}
Java
public class FibonacciSeries {
public static int fib(int n) {
int prev2 = 0;
if (n == 0)
return prev2;
int prev1 = 1;
int curr;
for (int i = 2; i <= n; i++) {
curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
public static void main(String[] args) {
int n = 9;
System.out.println(fib(n));
}
}
C#
using System;
class Program {
// Function to calculate the Fibonacci number at index n
static int Fibonacci(int n)
{
int prev2 = 0;
if (n == 0)
return prev2;
int prev1 = 1;
int curr;
for (int i = 2; i <= n; i++) {
curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
// Main method
static void Main(string[] args)
{
int n = 9; // Index of the Fibonacci number to find
Console.WriteLine(Fibonacci(
n)); // Print the Fibonacci number at index n
}
}
Javascript
// Function to calculate the Fibonacci series using space-optimized method
function fib(n) {
let prev2 = 0; // Initialize the first Fibonacci number (0)
if (n === 0) return prev2; // If n is 0, return the first Fibonacci number
let prev1 = 1; // Initialize the second Fibonacci number (1)
let curr; // Initialize the current Fibonacci number
for (let i = 2; i <= n; i++) { // Loop through from the 3rd Fibonacci number to the nth Fibonacci number
curr = prev1 + prev2; // Calculate the current Fibonacci number by adding the previous two Fibonacci numbers
prev2 = prev1; // Update the previous two Fibonacci numbers for the next iteration
prev1 = curr;
}
return prev1;
}
// Driver code
let n = 9;
console.log(fib(n));
Python3
def fib(n):
prev2, prev1 = 0, 1
if n == 0:
return prev2
for i in range(2, n + 1):
curr = prev1 + prev2
prev2, prev1 = prev1, curr
return prev1
# Driver code
if __name__ == "__main__":
n = 9
print(fib(n))
Time Complexity: O(N)
Auxillary space: O(1)
Space optimization from O(N*Sum)Quadratic to O(Sum)Linear In Subset Sum Problem:
Subset Sum problem Using Dynamic programming:
In approach of dynamic programming we have derived the relation between states as given below:
if (A[i-1] > j)
dp[i][j] = dp[i-1][j]
else
dp[i][j] = dp[i-1][j] OR dp[i-1][j-A[i-1]]
Steps To Optimize Space in action for above problem:
- If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j] or dp[i-1][j-A[i-1]].There is no need to store all the previous states just one previous state is used to compute result.
- Define two arrays prev and curr of size Sum+1 to store the just previous row result and current row result respectively.
- Once curr array is calculated then curr becomes our prev for the next row.
- When all rows are processed the answer is stored in prev array.
Space optimised Implementation:
C++
// A Dynamic Programming solution
// for subset sum problem with space optimization
#include <bits/stdc++.h>
using namespace std;
// Returns true if there is a subset of set[]
// with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
vector<bool> prev(sum + 1);
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
prev[0] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
prev[i] = false;
// curr array to store the current row result generated
// with help of prev array
vector<bool> curr(sum + 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < set[i - 1])
curr[j] = prev[j];
if (j >= set[i - 1])
curr[j] = prev[j] || prev[j - set[i - 1]];
}
// now curr becomes prev for i+1 th element
prev = curr;
}
return prev[sum];
}
// Driver code
int main()
{
int set[] = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
cout << "Found a subset with given sum";
else
cout << "No subset with given sum";
return 0;
}
Java
import java.util.*;
class SubsetSum {
// Returns true if there is a subset of set[]
// with sum equal to given sum
static boolean isSubsetSum(int[] set, int n, int sum) {
boolean[] prev = new boolean[sum + 1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
prev[0] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
prev[i] = false;
// curr array to store the current row result generated
// with help of prev array
boolean[] curr = new boolean[sum + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < set[i - 1])
curr[j] = prev[j];
if (j >= set[i - 1])
curr[j] = prev[j] || prev[j - set[i - 1]];
}
// now curr becomes prev for i+1 th element
prev = curr.clone();
}
return prev[sum];
}
// Driver code
public static void main(String args[]) {
int[] set = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n = set.length;
if (isSubsetSum(set, n, sum))
System.out.println("Found a subset with given sum");
else
System.out.println("No subset with given sum");
}
}
//This code is contributed by Utkarsh
C#
using System;
public class SubsetSum {
// Returns true if there is a subset of set[]
// with sum equal to given sum
public static bool IsSubsetSum(int[] set, int n,
int sum)
{
// Create a boolean array to store the results
// of subproblems. The value dp[i, j] will be
// true if there is a subset of set[0..j-1]
// with sum equal to i.
bool[, ] dp = new bool[sum + 1, n + 1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
dp[0, i] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
dp[i, 0] = false;
// Fill dp[][] in bottom up manner
for (int i = 1; i <= sum; i++) {
for (int j = 1; j <= n; j++) {
dp[i, j] = dp[i, j - 1];
if (i >= set[j - 1])
dp[i, j] = dp[i, j]
|| dp[i - set[j - 1], j - 1];
}
}
return dp[sum, n];
}
// Driver code
public static void Main(string[] args)
{
int[] set = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
int n = set.Length;
if (IsSubsetSum(set, n, sum))
Console.WriteLine(
"Found a subset with given sum");
else
Console.WriteLine("No subset with given sum");
}
}
Javascript
// Returns true if there is a subset of set[]
// with sum equal to given sum
function isSubsetSum(set, n, sum) {
let prev = new Array(sum + 1);
// If sum is 0, then answer is true
for (let i = 0; i <= n; i++)
prev[0] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (let i = 1; i <= sum; i++)
prev[i] = false;
// curr array to store the current row result generated
// with help of prev array
let curr = new Array(sum + 1);
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= sum; j++) {
if (j < set[i - 1])
curr[j] = prev[j];
if (j >= set[i - 1])
curr[j] = prev[j] || prev[j - set[i - 1]];
}
// now curr becomes prev for i+1 th element
prev = curr.slice(); // Copying array to avoid reference sharing
}
return prev[sum];
}
// Driver code
function main() {
let set = [3, 34, 4, 12, 5, 2];
let sum = 9;
let n = set.length;
if (isSubsetSum(set, n, sum))
console.log("Found a subset with given sum");
else
console.log("No subset with given sum");
}
// Call the main function
main();
Python3
def isSubsetSum(set, n, sum):
prev = [False] * (sum + 1)
# If sum is 0, then answer is true
for i in range(n + 1):
prev[0] = True
# If sum is not 0 and set is empty,
# then answer is false
for i in range(1, sum + 1):
prev[i] = False
# curr array to store the current row result generated
# with help of prev array
curr = [False] * (sum + 1)
for i in range(1, n + 1):
for j in range(1, sum + 1):
if j < set[i - 1]:
curr[j] = prev[j]
if j >= set[i - 1]:
curr[j] = prev[j] or prev[j - set[i - 1]]
# now curr becomes prev for i+1 th element
prev = curr[:]
return prev[sum]
# Driver code
if __name__ == "__main__":
set = [3, 34, 4, 12, 5, 2]
sum = 9
n = len(set)
if isSubsetSum(set, n, sum):
print("Found a subset with given sum")
else:
print("No subset with given sum")
OutputFound a subset with given sum
Complexity Analysis:
- Time Complexity: O(sum * n), where n is the size of the array.
- Auxiliary Space: O(sum), as the size of the 1-D array is sum+1.
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