Skip to content
Related Articles

Related Articles

Improve Article

Subarray/Substring vs Subsequence and Programs to Generate them

  • Difficulty Level : Medium
  • Last Updated : 25 May, 2021

Subarray/Substring

A subarray is a contiguous part of 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.
 

subseq-vs-subarray

How to generate all subarrays? 
We can run two nested loops, the outer loop picks starting element and inner loop considers all elements on right of the picked elements as ending element of 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 toto 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]+" ");
            }
        }
    }
     
    // Driver method to test the above function
    public static void main(String[] args)
    {
        System.out.println("All Non-empty Subarrays");
        subArray(arr.length);
         
    }
}


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.


C#




// C# program toto 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.


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 ocde is contributed by m_kit
?>


Javascript




<script>
 
// Javascript program toto generate all
// possible subarrays/subArrays
// Complexity- O(n^3)
let arr = [1, 2, 3, 4];
  
// Prints all subarrays in arr[0..n-1]
function subArray(n)
{
     
    // Pick starting point
    for(let i = 0; i < n; i++)
    {
          
        // Pick ending point
        for(let j = i; j < n; j++)
        {
             
            // Print subarray between current
            // starting and ending points
            for(let k = i; k <= j; k++)
                document.write(arr[k] + " ");
                 
              document.write("</br>");
        }
    }
}
 
// Driver code
document.write("All Non-empty Subarrays" + "</br>");
 
subArray(arr.length);
 
// This code is contributed by suresh07
    
</script>


Output: 



All Non-empty Subarrays
1 
1 2 
1 2 3 
1 2 3 4 
2 
2 3 
2 3 4 
3 
3 4 
4

Subsequence 
A subsequence is a sequence that can be derived from another sequence by 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.

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);
    }
}


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.


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


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
?>


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>


Output: 

All 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

This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :