Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Subarray/Substring vs Subsequence and Programs to Generate them
Next article icon

Subarray/Substring vs Subsequence and Programs to Generate them

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 

subseq-vs-subarray


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. 

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  

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. 

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  

Time Complexity: 0(n*(2^n))
Auxiliary Space: 0(1) 


Next Article
Subarray/Substring vs Subsequence and Programs to Generate them

K

kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • subsequence
Practice Tags :
  • Arrays

Similar Reads

    Subarray, Subsequence and Subsets in Python
    Algorithms and data manipulation are areas where it is important to grasp the ideas behind subarrays, subsequences as well as subsets. This article introduces the concepts of subarrays, subsequences along with subsets in Python. You will find out what these terms actually mean and how they differ fr
    7 min read
    Subarrays, Subsequences, and Subsets in Array
    What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1),
    10 min read
    Count of possible subarrays and subsequences using given length of Array
    Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.Examples: Input: N = 5 Output: Count of subarray = 15 Count of subsequence = 32Input: N = 3 Output: Count of subarray = 6 Count of subseque
    3 min read
    Find the longest subsequence of a string that is a substring of another string
    Given two strings X and Y consisting of N and M characters, the task is to find the longest subsequence of a string X which is a substring of the string Y. Examples: Input: X = "ABCD", Y = "ACDBDCD"Output: ACDExplanation:"ACD" is longest subsequence of X which is substring of Y. Input: X = A, Y = AO
    10 min read
    What are Subsequences in an Array?
    Subsequences are a fundamental concept in computer science and programming when working with arrays. A subsequence of an array is a sequence of elements from the array that appear in the same order, but not necessarily consecutively. In this blog post, we'll discuss subsequences, covering their defi
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences