Subarray/Substring vs Subsequence and Programs to Generate them
Last Updated :
23 Jul, 2025
Subarray/Substring
A subarray is a contiguous part of the array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/substrings.

How to generate all subarrays?
We can run two nested loops, the outer loop picks the starting element and the inner loop considers all elements on the right of the picked elements as the ending elements of the subarray.
C++
/* C++ code to generate all possible subarrays/subArrays
Complexity- O(n^3) */
#include<bits/stdc++.h>
using namespace std;
// Prints all subarrays in arr[0..n-1]
void subArray(int arr[], int n)
{
// Pick starting point
for (int i=0; i <n; i++)
{
// Pick ending point
for (int j=i; j<n; j++)
{
// Print subarray between current starting
// and ending points
for (int k=i; k<=j; k++)
cout << arr[k] << " ";
cout << endl;
}
}
}
// Driver program
int main()
{
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "All Non-empty Subarrays\n";
subArray(arr, n);
return 0;
}
Java
// Java program to generate all possible subarrays/subArrays
// Complexity- O(n^3) */
class Test
{
static int arr[] = new int[]{1, 2, 3, 4};
// Prints all subarrays in arr[0..n-1]
static void subArray( int n)
{
// Pick starting point
for (int i=0; i <n; i++)
{
// Pick ending point
for (int j=i; j<n; j++)
{
// Print subarray between current starting
// and ending points
for (int k=i; k<=j; k++)
System.out.print(arr[k]+" ");
System.out.println();
}
}
}
// Driver method to test the above function
public static void main(String[] args)
{
System.out.println("All Non-empty Subarrays");
subArray(arr.length);
}
}
C#
// C# program to generate all
// possible subarrays/subArrays
// Complexity- O(n^3)
using System;
class GFG
{
static int []arr = new int[]{1, 2, 3, 4};
// Prints all subarrays in arr[0..n-1]
static void subArray( int n)
{
// Pick starting point
for (int i = 0; i < n; i++)
{
// Pick ending point
for (int j = i; j < n; j++)
{
// Print subarray between current
// starting and ending points
for (int k = i; k <= j; k++)
Console.Write(arr[k]+" ");
Console.WriteLine("");
}
}
}
// Driver Code
public static void Main()
{
Console.WriteLine("All Non-empty Subarrays");
subArray(arr.Length);
}
}
// This code is contributed by Sam007.
JavaScript
//Function that returns all subarrays
let getSubArr = (arr) => {
//Empty array to store subarrays
let arr1 = [];
for(let i=0;i<arr.length;i++) {
//Empty array to store one subarray
let subArr = [];
for(let j=i;j<arr.length;j++) {
//To get elements to the right of selected i th element till j
subArr.push(arr.slice(i,j+1));
}
//Storing individual subarrays into main array
arr1.push(subArr);
}
//Return the array of subarrays
return arr1;
}
//Example Array
let arr = [1,2,3,4];
let arr1 = getSubArr(arr);
console.log(arr1);
PHP
<?php
// PHP code to generate all possible
// subarrays/subArrays Complexity- O(n^3)
// Prints all subarrays
// in arr[0..n-1]
function subArray($arr, $n)
{
// Pick starting point
for ($i = 0; $i < $n; $i++)
{
// Pick ending point
for ($j = $i; $j < $n; $j++)
{
// Print subarray between
// current starting
// and ending points
for ($k = $i; $k <= $j; $k++)
echo $arr[$k] , " ";
echo "\n";
}
}
}
// Driver Code
$arr= array(1, 2, 3, 4);
$n = sizeof($arr);
echo "All Non-empty Subarrays\n";
subArray($arr, $n);
// This code is contributed by m_kit
?>
Python3
# Python3 code to generate all possible
# subarrays/subArrays
# Complexity- O(n^3)
# Prints all subarrays in arr[0..n-1]
def subArray(arr, n):
# Pick starting point
for i in range(0,n):
# Pick ending point
for j in range(i,n):
# Print subarray between
# current starting
# and ending points
for k in range(i,j+1):
print (arr[k],end=" ")
print ("\n",end="")
# Driver program
arr = [1, 2, 3, 4]
n = len(arr)
print ("All Non-empty Subarrays")
subArray(arr, n);
# This code is contributed by Shreyanshi.
OutputAll Non-empty Subarrays
1
1 2
1 2 3
1 2 3 4
2
2 3
2 3 4
3
3 4
4
Time Complexity: 0(n^3)
Auxiliary Space: 0(1)
Subsequence: A subsequence is a sequence that can be derived from another sequence by removing zero or more elements, without changing the order of the remaining elements.
For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1) non-empty sub-sequences in total.
A string example to differentiate: Consider strings "geeksforgeeks" and "gks". "gks" is a subsequence of "geeksforgeeks" but not a substring. "geeks" is both a subsequence and subarray. Every subarray is a subsequence. More specifically, Subsequence is a generalization of substring.
A subarray or substring will always be contiguous, but a subsequence need not be contiguous. That is, subsequences are not required to occupy consecutive positions within the original sequences. But we can say that both contiguous subsequence and subarray are the same.
How to generate all Subsequences?
We can use algorithm to generate power set for generation of all subsequences.
C++
/* C++ code to generate all possible subsequences.
Time Complexity O(n * 2^n) */
#include<bits/stdc++.h>
using namespace std;
void printSubsequences(int arr[], int n)
{
/* Number of subsequences is (2**n -1)*/
unsigned int opsize = pow(2, n);
/* Run from counter 000..1 to 111..1*/
for (int counter = 1; counter < opsize; counter++)
{
for (int j = 0; j < n; j++)
{
/* Check if jth bit in the counter is set
If set then print jth element from arr[] */
if (counter & (1<<j))
cout << arr[j] << " ";
}
cout << endl;
}
}
// Driver program
int main()
{
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "All Non-empty Subsequences\n";
printSubsequences(arr, n);
return 0;
}
Java
/* Java code to generate all possible subsequences.
Time Complexity O(n * 2^n) */
import java.math.BigInteger;
class Test
{
static int arr[] = new int[]{1, 2, 3, 4};
static void printSubsequences(int n)
{
/* Number of subsequences is (2**n -1)*/
int opsize = (int)Math.pow(2, n);
/* Run from counter 000..1 to 111..1*/
for (int counter = 1; counter < opsize; counter++)
{
for (int j = 0; j < n; j++)
{
/* Check if jth bit in the counter is set
If set then print jth element from arr[] */
if (BigInteger.valueOf(counter).testBit(j))
System.out.print(arr[j]+" ");
}
System.out.println();
}
}
// Driver method to test the above function
public static void main(String[] args)
{
System.out.println("All Non-empty Subsequences");
printSubsequences(arr.length);
}
}
C#
// C# code to generate all possible subsequences.
// Time Complexity O(n * 2^n)
using System;
class GFG{
static void printSubsequences(int[] arr, int n)
{
// Number of subsequences is (2**n -1)
int opsize = (int)Math.Pow(2, n);
// Run from counter 000..1 to 111..1
for(int counter = 1; counter < opsize; counter++)
{
for(int j = 0; j < n; j++)
{
// Check if jth bit in the counter is set
// If set then print jth element from arr[]
if ((counter & (1 << j)) != 0)
Console.Write(arr[j] + " ");
}
Console.WriteLine();
}
}
// Driver Code
static void Main()
{
int[] arr = { 1, 2, 3, 4 };
int n = arr.Length;
Console.WriteLine("All Non-empty Subsequences");
printSubsequences(arr, n);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript code to generate all possible subsequences.
// Time Complexity O(n * 2^n)
function printSubsequences(arr, n)
{
// Number of subsequences is (2**n -1)
let opsize = parseInt(Math.pow(2, n), 10);
// Run from counter 000..1 to 111..1
for(let counter = 1; counter < opsize; counter++)
{
for(let j = 0; j < n; j++)
{
// Check if jth bit in the counter is set
// If set then print jth element from arr[]
if ((counter & (1 << j)) != 0)
document.write(arr[j] + " ");
}
document.write("</br>");
}
}
let arr = [ 1, 2, 3, 4 ];
let n = arr.length;
document.write("All Non-empty Subsequences" + "</br>");
printSubsequences(arr, n);
// This code is contributed by divyeshrabadiya07.
</script>
PHP
<?php
// PHP code to generate all
// possible subsequences.
// Time Complexity O(n * 2^n)
function printSubsequences($arr, $n)
{
// Number of subsequences
// is (2**n -1)
$opsize = pow(2, $n);
/* Run from counter
000..1 to 111..1*/
for ($counter = 1;
$counter < $opsize;
$counter++)
{
for ( $j = 0; $j < $n; $j++)
{
/* Check if jth bit in
the counter is set
If set then print jth
element from arr[] */
if ($counter & (1 << $j))
echo $arr[$j], " ";
}
echo "\n";
}
}
// Driver Code
$arr = array (1, 2, 3, 4);
$n = sizeof($arr);
echo "All Non-empty Subsequences\n";
printSubsequences($arr, $n);
// This code is contributed by ajit
?>
Python3
# Python3 code to generate all
# possible subsequences.
# Time Complexity O(n * 2 ^ n)
import math
def printSubsequences(arr, n) :
# Number of subsequences is (2**n -1)
opsize = math.pow(2, n)
# Run from counter 000..1 to 111..1
for counter in range( 1, (int)(opsize)) :
for j in range(0, n) :
# Check if jth bit in the counter
# is set If set then print jth
# element from arr[]
if (counter & (1<<j)) :
print( arr[j], end =" ")
print()
# Driver program
arr = [1, 2, 3, 4]
n = len(arr)
print( "All Non-empty Subsequences")
printSubsequences(arr, n)
# This code is contributed by Nikita Tiwari.
OutputAll Non-empty Subsequences
1
2
1 2
3
1 3
2 3
1 2 3
4
1 4
2 4
1 2 4
3 4
1 3 4
2 3 4
1 2 3 4
Time Complexity: 0(n*(2^n))
Auxiliary Space: 0(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