Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Introduction to Dynamic Programming on Trees
Next article icon

Count of AP (Arithmetic Progression) Subsequences in an array

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of n positive integers. The task is to count the number of Arithmetic Progression subsequences in the array.
Note: Empty sequence or single element sequence is Arithmetic Progression.

Examples: 

Input: arr[] = [1, 2, 3]
Output: 8
Explanation: Arithmetic Progression subsequence from the given array are: [], [1], [2], [3], [1, 2],
[2, 3], [1, 3], [1, 2, 3].

Input: arr[] = [10, 20]
Output: 4
Explanation: Arithmetic Progression subsequence from the given array are: [], [10], [20], [10, 20].

Table of Content

  • Using Recursion – O(2^n) Time and O(n) Space
  • Using Top-Down DP (Memoization) – O(n^2) Time and O(n^2) Space
  • Using Bottom-Up DP (Tabulation) – O(n^2) Time and O(n^2) Space
  • Using Space Optimized DP – O(n*(max – min)) Time and O(n + max) Space

Using Recursion – O(2^n) Time and O(n) Space

For the recursive approach, the problem involves counting arithmetic subsequences with a certain difference. At each step, the number of available elements decreases by 1. Consider the current element as part of the arithmetic subsequence. In this case, the difference between the current element and the previous element is passed to the recursive call. Alternatively, skip the current element, and the sequence continues without including it.

Base case:

  • if idx == n, return 1 (meaning all elements have been processed)

Mathematically, the recurrence relation looks like this:

numberOfAP(arr, n, idx, pre, count, diff) = numberOfAP(arr, n, idx + 1, idx, count + 1, arr[idx] – arr[pre]) OR
numberOfAP(arr, n, idx + 1, pre, count, diff)

C++
// C++ Code for count of AP // Subsequences using Recursion #include <bits/stdc++.h> using namespace std;  // Recursive function to count all  // arithmetic subsequences int numberOfAP(vector<int>& arr, int n, int idx,                 int pre, int count, int diff) {        int ans = 0;      // Base case: if we've processed all elements     if (idx == n) {         return 1;     }      // If we have picked one element but      // no difference set yet     if (pre != -1 && diff == INT_MIN) {                // Pick the current element and         // set the difference         ans += numberOfAP(arr, n, idx + 1, idx,                            count + 1, arr[idx] - arr[pre]);     }       // First element or continuation of      // an AP with the same difference     if (pre == -1 || diff == arr[idx] - arr[pre]) {                // Pick the current element to extend the AP         ans += numberOfAP(arr, n, idx + 1,                            idx, count + 1, diff);     }      // Skip the current element     ans += numberOfAP(arr, n, idx + 1, pre, count, diff);      return ans; }  // Wrapper function to start the recursion int count(vector<int>& arr) {     int n = arr.size();     return numberOfAP(arr, n, 0, -1, 0, INT_MIN); }  int main() {      vector<int> arr = {1, 2, 3};       cout << count(arr);     return 0; } 
Java
// Java Code for count of AP // Subsequences using Recursion import java.util.*;  class GfG {      // Recursive function to count all     // arithmetic subsequences     static int numberOfAP(List<Integer> arr, int n, int idx,                             int pre, int count, int diff) {          int ans = 0;          // Base case: if we've processed all elements         if (idx == n) {             return 1;         }          // If we have picked one element but         // no difference set yet         if (pre != -1 && diff == Integer.MIN_VALUE) {              // Pick the current element and             // set the difference             ans += numberOfAP(arr, n, idx + 1, idx,                                count + 1, arr.get(idx) - arr.get(pre));         }          // First element or continuation of         // an AP with the same difference         if (pre == -1 || diff == arr.get(idx) - arr.get(pre)) {              // Pick the current element to extend the AP             ans += numberOfAP(arr, n, idx + 1,                                idx, count + 1, diff);         }          // Skip the current element         ans += numberOfAP(arr, n, idx + 1, pre, count, diff);          return ans;     }      // Wrapper function to start the recursion     static int count(List<Integer> arr) {         int n = arr.size();         return numberOfAP(arr, n, 0, -1, 0, Integer.MIN_VALUE);     }      public static void main(String[] args) {          List<Integer> arr = Arrays.asList(1, 2, 3);                System.out.println(count(arr));     } } 
Python
# Python Code for count of AP # Subsequences using Recursion import sys  # Recursive function to count all  # arithmetic subsequences def number_of_AP(arr, n, idx, pre, count, diff):          ans = 0      # Base case: if we've processed all elements     if idx == n:         return 1      # If we have picked one element but      # no difference set yet     if pre != -1 and diff == float('-inf'):                  # Pick the current element and          # set the difference         ans += number_of_AP(arr, n, idx + 1, idx,                              count + 1, arr[idx] - arr[pre])      # First element or continuation of      # an AP with the same difference     if pre == -1 or diff == arr[idx] - arr[pre]:                  # Pick the current element to extend the AP         ans += number_of_AP(arr, n, idx + 1,                              idx, count + 1, diff)      # Skip the current element     ans += number_of_AP(arr, n, idx + 1, pre, count, diff)      return ans  # Wrapper function to start the recursion def count(arr):     n = len(arr)     return number_of_AP(arr, n, 0, -1, 0, float('-inf'))  if __name__ == "__main__":      arr = [1, 2, 3]      print(count(arr)) 
C#
// C# Code for count of AP // Subsequences using Recursion using System; using System.Collections.Generic;  class GfG {      // Recursive function to count all      // arithmetic subsequences     static int NumberOfAP(List<int> arr, int n, int idx,                                   int pre, int count, int diff) {          int ans = 0;          // Base case: if we've processed all elements         if (idx == n) {             return 1;         }          // If we have picked one element but          // no difference set yet         if (pre != -1 && diff == int.MinValue) {                          // Pick the current element and              // set the difference             ans += NumberOfAP(arr, n, idx + 1, idx,                                count + 1, arr[idx] - arr[pre]);         }          // First element or continuation of          // an AP with the same difference         if (pre == -1 || diff == arr[idx] - arr[pre]) {                          // Pick the current element to extend the AP             ans += NumberOfAP(arr, n, idx + 1, idx, count + 1, diff);         }          // Skip the current element         ans += NumberOfAP(arr, n, idx + 1, pre, count, diff);          return ans;     }      // Wrapper function to start the recursion     static int Count(List<int> arr) {         int n = arr.Count;         return NumberOfAP(arr, n, 0, -1, 0, int.MinValue);     }      static void Main(string[] args) {                  List<int> arr = new List<int> {1, 2, 3};          Console.WriteLine(Count(arr));     } } 
JavaScript
// JavaScript Code for count of AP // Subsequences using Recursion  // Recursive function to count all  // arithmetic subsequences function numberOfAP(arr, n, idx, pre, count, diff) {     let ans = 0;      // Base case: if we've processed all elements     if (idx === n) {         return 1;     }      // If we have picked one element but      // no difference set yet     if (pre !== -1 && diff === Number.MIN_SAFE_INTEGER) {                  // Pick the current element and          // set the difference         ans += numberOfAP(arr, n, idx + 1, idx,                            count + 1, arr[idx] - arr[pre]);     }      // First element or continuation of      // an AP with the same difference     if (pre === -1 || diff === arr[idx] - arr[pre]) {                  // Pick the current element to extend the AP         ans += numberOfAP(arr, n, idx + 1, idx, count + 1, diff);     }      // Skip the current element     ans += numberOfAP(arr, n, idx + 1, pre, count, diff);      return ans; }  // Wrapper function to start the recursion function countAP(arr) {     const n = arr.length;     return numberOfAP(arr, n, 0, -1, 0, Number.MIN_SAFE_INTEGER); }  const arr = [1, 2, 3]; console.log(countAP(arr)); 

Output
8

Using Top-Down DP (Memoization) – O(n^2) Time and O(n^2) Space

1. Optimal Substructure:

The solution to count all arithmetic subsequences can be constructed from optimal solutions to subproblems.

  • If pre != -1 and diff == INT_MIN, we are setting the difference between the current element and the previous element. Once this difference is established, we continue checking if the current element extends the arithmetic progression.
  • If pre == -1, this means we are at the beginning of the subsequence, and we can freely start the subsequence with the current element.
  • If diff == arr[idx] – arr[pre], then the current element fits into the existing arithmetic progression, so we continue the progression by including the current element.

2. Overlapping Subproblems:

Recursive calls for counting AP subsequences involve recalculating the same state multiple times. To avoid recomputation, we use memoization with a unique key for each state. This approach reduces redundant calculations by storing results in memo. For instance, numberOfAP reuses previously computed results whenever it encounters the same key.

The memoization key for each state is:

  • key = to_string(idx) + “_” + to_string(pre) + “_” + to_string(count) + “_” + to_string(diff)

The memoization relation then becomes:

memo[key] = numberOfAP(arr, n, idx + 1, idx, count + 1, arr[idx] – arr[pre], memo
+ numberOfAP(arr, n, idx + 1, idx, count + 1, diff, memo) +
+ numberOfAP(arr, n, idx + 1, pre, count, diff, memo)

C++
// C++ Code for count of AP // Subsequences using Memoization #include <bits/stdc++.h> using namespace std;  // Recursive function to count all  // arithmetic subsequences with memoization int numberOfAP(vector<int>& arr, int n, int idx,                 int pre, int count, int diff,                 unordered_map<string, int>& memo) {      // Base case: if we've processed all elements     if (idx == n) {         return 1;     }      // Create a unique key for the current state     string key = to_string(idx) + "_" + to_string(pre) + "_" +                   to_string(count) + "_" + to_string(diff);      // Check if the result is already memoized     if (memo.find(key) != memo.end()) {         return memo[key];     }      int ans = 0;      // If we have picked one element but      // no difference set yet     if (pre != -1 && diff == INT_MIN) {                  // Pick the current element and          // set the difference         ans += numberOfAP(arr, n, idx + 1, idx,                            count + 1, arr[idx] - arr[pre], memo);     }      // First element or continuation of      // an AP with the same difference     if (pre == -1 || diff == arr[idx] - arr[pre]) {                  // Pick the current element to extend the AP         ans += numberOfAP(arr, n, idx + 1,                            idx, count + 1, diff, memo);     }      // Skip the current element     ans += numberOfAP(arr, n, idx + 1, pre, count, diff, memo);      // Store the result in the memo map     memo[key] = ans;      return ans; }  // Wrapper function to start the recursion int count(vector<int>& arr) {     int n = arr.size();     unordered_map<string, int> memo;      return numberOfAP(arr, n, 0, -1, 0, INT_MIN, memo); }  int main() {        vector<int> arr = {1, 2, 3};       cout << count(arr);     return 0; } 
Java
// Java Code for count of AP // Subsequences using Memoization import java.util.ArrayList; import java.util.HashMap;  class GfG {      // Recursive function to count all      // arithmetic subsequences with memoization     static int numberOfAP(ArrayList<Integer> arr, int n, int idx,                                    int pre, int count, int diff,                                    HashMap<String, Integer> memo) {          // Base case: if we've processed all elements         if (idx == n) {             return 1;         }          // Create a unique key for the current state         String key = idx + "_" + pre + "_" + count + "_" + diff;          // Check if the result is already memoized         if (memo.containsKey(key)) {             return memo.get(key);         }          int ans = 0;          // If we have picked one element but          // no difference set yet         if (pre != -1 && diff == Integer.MIN_VALUE) {                          // Pick the current element and              // set the difference             ans += numberOfAP(arr, n, idx + 1, idx,                                count + 1, arr.get(idx) - arr.get(pre), memo);         }          // First element or continuation of          // an AP with the same difference         if (pre == -1 || diff == arr.get(idx) - arr.get(pre)) {                          // Pick the current element to extend the AP             ans += numberOfAP(arr, n, idx + 1, idx, count + 1, diff, memo);         }          // Skip the current element         ans += numberOfAP(arr, n, idx + 1, pre, count, diff, memo);          // Store the result in the memo map         memo.put(key, ans);          return ans;     }      // Wrapper function to start the recursion     static int count(ArrayList<Integer> arr) {         int n = arr.size();         HashMap<String, Integer> memo = new HashMap<>();         return numberOfAP(arr, n, 0, -1, 0, Integer.MIN_VALUE, memo);     }      public static void main(String[] args) {          ArrayList<Integer> arr = new ArrayList<>();         arr.add(1);         arr.add(2);         arr.add(3);          System.out.println(count(arr));     } } 
Python
# Python Code for count of AP # Subsequences using Memoization def numberOfAP(arr, n, idx, pre, count, diff, memo):      # Base case: if we've processed all elements     if idx == n:         return 1      # Create a unique key for the current state     key = f"{idx}_{pre}_{count}_{diff}"      # Check if the result is already memoized     if key in memo:         return memo[key]      ans = 0      # If we have picked one element but      # no difference set yet     if pre != -1 and diff == float('-inf'):                  # Pick the current element and          # set the difference         ans += numberOfAP(arr, n, idx + 1, idx,                            count + 1, arr[idx] - arr[pre], memo)      # First element or continuation of      # an AP with the same difference     if pre == -1 or diff == arr[idx] - arr[pre]:                  # Pick the current element to extend the AP         ans += numberOfAP(arr, n, idx + 1,                            idx, count + 1, diff, memo)      # Skip the current element     ans += numberOfAP(arr, n, idx + 1, pre, count, diff, memo)      # Store the result in the memo map     memo[key] = ans      return ans  # Wrapper function to start the recursion def count(arr):     memo = {}      return numberOfAP(arr, len(arr), 0, -1, 0, float('-inf'), memo)  if __name__ == "__main__":      arr = [1, 2, 3]      print(count(arr)) 
C#
// C# Code for count of AP // Subsequences using Memoization using System; using System.Collections.Generic;  class GfG {        // Recursive function to count all      // arithmetic subsequences with memoization     static int NumberOfAP(List<int> arr, int n, int idx,                  int pre, int count, int diff,                          Dictionary<string, int> memo) {                // Base case: if we've processed all elements         if (idx == n) {             return 1;         }          // Create a unique key for the current state         string key = idx + "_" + pre + "_" + count + "_" + diff;          // Check if the result is already memoized         if (memo.ContainsKey(key)) {             return memo[key];         }          int ans = 0;          // If we have picked one element but no        	// difference set yet         if (pre != -1 && diff == int.MinValue) {                        // Pick the current element and set the difference             ans += NumberOfAP(arr, n, idx + 1,                        idx, count + 1, arr[idx] - arr[pre], memo);         }          // First element or continuation of an          // AP with the same difference         if (pre == -1 || diff == arr[idx] - arr[pre]) {                        // Pick the current element to extend the AP             ans += NumberOfAP(arr, n, idx + 1,                         idx, count + 1, diff, memo);         }          // Skip the current element         ans += NumberOfAP(arr, n, idx + 1,                          pre, count, diff, memo);          // Store the result in the memo map         memo[key] = ans;          return ans;     }      // Wrapper function to start the recursion     static int Count(List<int> arr) {         var memo = new Dictionary<string, int>();          return NumberOfAP(arr, arr.Count, 0, -1,                             0, int.MinValue, memo);     }      static void Main() {                List<int> arr = new List<int> { 1, 2, 3 };         Console.WriteLine(Count(arr));     } } 
JavaScript
// Javascript Code for count of AP // Subsequences using Memoization  // Recursive function to count all arithmetic  // subsequences with memoization function numberOfAP(arr, n, idx, pre, count, diff, memo) {      // Base case: if we've processed all elements     if (idx === n) {         return 1;     }      // Create a unique key for the current state     const key = idx + "_" + pre + "_" + count + "_" + diff;      // Check if the result is already memoized     if (memo.has(key)) {         return memo.get(key);     }      let ans = 0;      // If we have picked one element but      // no difference set yet     if (pre !== -1 && diff === Number.MIN_SAFE_INTEGER) {          // Pick the current element and set the difference         ans += numberOfAP(arr, n, idx + 1, idx,         count + 1, arr[idx] - arr[pre], memo);     }      // First element or continuation of an      // AP with the same difference     if (pre === -1 || diff === arr[idx] - arr[pre]) {              // Pick the current element to extend the AP         ans += numberOfAP(arr, n, idx + 1, idx,         count + 1, diff, memo);     }      // Skip the current element     ans += numberOfAP(arr, n, idx + 1, pre,     				  count, diff, memo);      // Store the result in the memo map     memo.set(key, ans);      return ans; }  // Wrapper function to start the recursion function count(arr) {     const memo = new Map();     return numberOfAP(arr, arr.length, 0, -1, 0,              Number.MIN_SAFE_INTEGER, memo); }  const arr = [1, 2, 3]; console.log(count(arr)); 

Output
8

Using Bottom-Up DP (Tabulation) – O(n^2) Time and O(n^2) Space

We create a 2D table dp of size(n) where each dp[i] is a map (hash table) storing the count of subsequences ending at index i for each common difference. The keys of the map are the common differences (diff), and the values are the counts of subsequences that end at arr[i] with that particular common difference (diff).

  • dp[i]: Represents the number of subsequences ending at index i with common difference diff.
  • Base Case: Each element itself is an arithmetic subsequence of length 1.

For each pair of indices (i, j) where i > j: Calculate the common difference diff = arr[i] – arr[j].

  • If subsequences with this diff exist at arr[j], extend them by adding arr[i].
  • If no such subsequences exist at arr[j], start a new subsequence with (arr[j], arr[i]).

The total number of arithmetic subsequences will be the sum of all values in all maps at all indices i, i.e., sum(dp[i]) for all i and diff.

C++
// C++ code to count the number of AP // subsequences using Tabulation #include <bits/stdc++.h> using namespace std;  // Function to count all AP subsequences using DP int count(vector<int>& arr) {     int n = arr.size();     if (n == 0) return 0;      // Total number of AP subsequences     int count = n + 1;        // DP map to store subsequences ending at      // each element with specific common differences     vector<unordered_map<int, int>> dp(n);      // Traverse through each pair to populate dp table     for (int i = 0; i < n; i++) {         for (int j = 0; j < i; j++) {                        // Calculate the common difference for           	// the current pair             int diff = arr[i] - arr[j];              // Get the count of subsequences with the              // same difference ending at j             int countj = dp[j].count(diff) ? dp[j][diff] : 0;              // Update the count of subsequences with              // this difference ending at i             dp[i][diff] += countj + 1;              // Add the count of new subsequences            	// to the total             count += countj + 1;         }     }     return count; }  int main() {        vector<int> arr = {1, 2, 3};     cout << count(arr);     return 0; } 
Java
// Java code to count the number of AP // subsequences using Tabulation import java.util.HashMap; import java.util.Map; import java.util.ArrayList;  class GfG {      // Function to count all AP subsequences using DP     static int count(ArrayList<Integer> arr) {         int n = arr.size();         if (n == 0) return 0;          // Total number of AP subsequences         int count = n + 1;          // DP map to store subsequences ending at          // each element with specific common differences         Map<Integer, Integer>[] dp = new HashMap[n];         for (int i = 0; i < n; i++) {             dp[i] = new HashMap<>();         }          // Traverse through each pair to populate dp table         for (int i = 0; i < n; i++) {             for (int j = 0; j < i; j++) {                  // Calculate the common difference               	// for the current pair                 int diff = arr.get(i) - arr.get(j);                  // Get the count of subsequences with the                  // same difference ending at j                 int countj = dp[j].getOrDefault(diff, 0);                  // Update the count of subsequences with                  // this difference ending at i                 dp[i].put(diff, dp[i].getOrDefault(diff, 0) + countj + 1);                  // Add the count of new subsequences to the total                 count += countj + 1;             }         }         return count;     }      public static void main(String[] args) {          ArrayList<Integer> arr = new ArrayList<>();         arr.add(1);         arr.add(2);         arr.add(3);         System.out.println(count(arr));     } } 
Python
# Python code to count the number of AP # subsequences using Tabulation from collections import defaultdict  # Function to count all AP subsequences using DP def count(arr):     n = len(arr)     if n == 0:         return 0      # Total number of AP subsequences     count = n + 1      # DP dictionary to store subsequences ending at      # each element with specific common differences     dp = [defaultdict(int) for _ in range(n)]      # Traverse through each pair to populate dp table     for i in range(n):         for j in range(i):              # Calculate the common difference              # for the current pair             diff = arr[i] - arr[j]              # Get the count of subsequences with the              # same difference ending at j             countj = dp[j][diff]              # Update the count of subsequences with              # this difference ending at i             dp[i][diff] += countj + 1              # Add the count of new subsequences             # to the total             count += countj + 1      return count  if __name__ == "__main__":        arr = [1, 2, 3]     print(count(arr)) 
C#
// C# code to count the number of AP // subsequences using Tabulation using System; using System.Collections.Generic;  class GfG {      // Function to count all AP subsequences using DP     static int Count(List<int> arr) {         int n = arr.Count;         if (n == 0) return 0;          // Total number of AP subsequences         int count = n + 1;          // DP map to store subsequences ending at          // each element with specific common differences         var dp = new Dictionary<int, int>[n];         for (int i = 0; i < n; i++) {             dp[i] = new Dictionary<int, int>();         }          // Traverse through each pair to populate dp table         for (int i = 0; i < n; i++) {             for (int j = 0; j < i; j++) {                  // Calculate the common difference               	// for the current pair                 int diff = arr[i] - arr[j];                  // Get the count of subsequences with the                  // same difference ending at j                 int countj = dp[j].ContainsKey(diff) ? dp[j][diff] : 0;                  // Update the count of subsequences with                  // this difference ending at i                 if (dp[i].ContainsKey(diff))                     dp[i][diff] += countj + 1;                 else                     dp[i][diff] = countj + 1;                  // Add the count of new subsequences               	// to the total                 count += countj + 1;             }         }         return count;     }      static void Main() {                  List<int> arr = new List<int> { 1, 2, 3 };         Console.WriteLine(Count(arr));     } } 
JavaScript
// Javascript code to count the number of AP // subsequences using Tabulation  // Function to count all AP subsequences using DP function count(arr) {     const n = arr.length;     if (n === 0) return 0;      // Total number of AP subsequences     let count = n + 1;      // DP map to store subsequences ending at      // each element with specific common differences     const dp = Array.from({ length: n }, () => new Map());      // Traverse through each pair to populate dp table     for (let i = 0; i < n; i++) {         for (let j = 0; j < i; j++) {              // Calculate the common difference for             // the current pair             const diff = arr[i] - arr[j];              // Get the count of subsequences with the              // same difference ending at j             const countj = dp[j].get(diff) || 0;              // Update the count of subsequences with              // this difference ending at i             dp[i].set(diff, (dp[i].get(diff) || 0) + countj + 1);              // Add the count of new subsequences to the total             count += countj + 1;         }     }     return count; }  const arr = [1, 2, 3]; console.log(count(arr)); 

Output
8

Using Space Optimized DP – O(n*(max – min)) Time and O(n + max) Space

Since empty sequence and single element sequence is also arithmetic progression, so we initialize the answer with n(number of element in the array) + 1. 
Now, we need to find the arithmetic progression subsequence of length greater than or equal to 2. Let minimum and maximum of the array be minarr and maxarr respectively. Observe, in all the arithmetic progression subsequences, the range of common difference will be from (minarr – maxarr) to (maxarr – minarr). Now, for each common difference, say d, calculate the subsequence of length greater than or equal to 2 using dynamic programming. 

The number of subsequence of length greater than or equal to 2 with common difference d is sum of dp[i] – 1, 0 <= i = 2 with difference d. To speed up, store the sum of dp[j] with arr[j] + d = arr[i] and j < i. 

C++
// C++ program to find number of AP // subsequences in the given array #include <bits/stdc++.h> using namespace std;  // Function to count the number of AP subsequences int count(vector<int>& arr) {     int n = arr.size();         int minarr = INT_MAX;     int maxarr = INT_MIN;      // Finding the minimum and maximum value of the array.     for (int i = 0; i < n; i++) {         minarr = min(minarr, arr[i]);         maxarr = max(maxarr, arr[i]);     }      // dp[i] is going to store the count of     // APs ending with arr[i].     // sum[j] is going to store the sum of      // all dp[]'s with j as an AP element.     vector<int> dp(n, 0);     vector<int> sum(1000001, 0);      int ans = n + 1;      // Traversing with all common differences.     for (int d = (minarr - maxarr); d <= (maxarr - minarr); d++) {         fill(sum.begin(), sum.end(), 0);          // Traversing all the elements of the array.         for (int i = 0; i < n; i++) {                        // Initialize dp[i] = 1.             dp[i] = 1;              // Adding counts of APs with given differences             // and arr[i] is the last element.             // We consider all APs where an array element              // is the previous element of the AP             // with a particular difference.             if (arr[i] - d >= 1 && arr[i] - d <= 1000000) {                 dp[i] += sum[arr[i] - d];             }              ans += dp[i] - 1;             sum[arr[i]] += dp[i];         }     }      return ans; }  int main() {        vector<int> arr = {1, 2, 3};         cout << count(arr) << endl;     return 0; } 
Java
// Java program to find number of AP // subsequences in the given array import java.util.ArrayList; import java.util.Arrays;  class GfG {      static int count(ArrayList<Integer> arr) {         int n = arr.size();                  // initializing the minimum value and         // maximum value of the array.         int minarr = Integer.MAX_VALUE;         int maxarr = Integer.MIN_VALUE;          // Finding the minimum and maximum         // value of the array.         for (int i = 0; i < n; i++) {             minarr = Math.min(minarr, arr.get(i));             maxarr = Math.max(maxarr, arr.get(i));         }          // dp[i] is going to store count of          // APs ending with arr[i].         // sum[j] is going to store sum of          // all dp[]'s with j as an AP element.         int[] dp = new int[n];         int[] sum = new int[1000001];          // Initialize answer with n + 1 as          // single elements and empty array          // are also DP.         int ans = n + 1;          // Traversing with all common          // difference.         for (int d = (minarr - maxarr);                  d <= (maxarr - minarr); d++) {             Arrays.fill(sum, 0);              // Traversing all the elements              // of the array.             for (int i = 0; i < n; i++) {                                  // Initialize dp[i] = 1.                 dp[i] = 1;                  // Adding counts of APs with                 // given differences and arr[i]                  // is last element.                 // We consider all APs where                  // an array element is previous                  // element of AP with a particular                 // difference                 if (arr.get(i) - d >= 1 &&                               arr.get(i) - d <= 1000000)                     dp[i] += sum[arr.get(i) - d];                  ans += dp[i] - 1;                 sum[arr.get(i)] += dp[i];             }         }          return ans;     }      public static void main(String[] args) {                ArrayList<Integer> arr            = new ArrayList<>(Arrays.asList(1, 2, 3));                  System.out.println(count(arr));     } } 
Python
# Python program to find number of AP # subsequences in the given array  def count(arr):      n = len(arr)      # initializing the minimum value and     # maximum value of the array.     minarr = +2147483647     maxarr = -2147483648      # Finding the minimum and      # maximum value of the array.     for i in range(n):         minarr = min(minarr, arr[i])         maxarr = max(maxarr, arr[i])           # dp[i] is going to store count of APs ending     # with arr[i].     # sum[j] is going to store sum of all dp[]'s     # with j as an AP element.     dp = [0 for i in range(n + 1)]           # Initialize answer with n + 1 as single      # elements and empty array are also DP.     ans = n + 1      # Traversing with all common difference.     for d in range((minarr - maxarr), (maxarr - minarr) + 1):         sum = [0 for i in range(1000001 + 1)]                  # Traversing all the element of the array.         for i in range(n):                      # Initialize dp[i] = 1.             dp[i] = 1              # Adding counts of APs with given differences             # and arr[i] is last element.              # We consider all APs where an array element             # is previous element of AP with a particular              # difference             if (arr[i] - d >= 1 and arr[i] - d <= 1000000):                 dp[i] += sum[arr[i] - d]              ans += dp[i] - 1             sum[arr[i]] += dp[i]      return ans  if __name__ == "__main__":        arr = [1, 2, 3]      print(count(arr)) 
C#
// C# program to find number of AP // subsequences in the given array using System; using System.Collections.Generic;  class GfG {      // Function to find number of AP     // subsequences in the given array     static int count(List<int> arr) {                  int n = arr.Count;                 // initializing the minimum value and         // maximum value of the array.         int minarr = +2147483647;         int maxarr = -2147483648;         int i;                  // Finding the minimum and maximum         // value of the array.         for (i = 0; i < n; i++)  {             minarr = Math.Min(minarr, arr[i]);             maxarr = Math.Max(maxarr, arr[i]);         }          // dp[i] is going to store count of          // APs ending with arr[i].         // sum[j] is going to store sum of          // all dp[]'s with j as an AP element.         int[] dp = new int[n];         int[] sum = new int[1000001];          // Initialize answer with n + 1 as          // single elements and empty array          // are also DP.         int ans = n + 1;          // Traversing with all common          // difference.         for (int d = (minarr - maxarr);                   d <= (maxarr - minarr); d++) {                          for(i = 0; i < sum.Length; i++)                 sum[i] = 0;                      // Traversing all the element              // of the array.             for ( i = 0; i < n; i++) {                                  // Initialize dp[i] = 1.                 dp[i] = 1;                  // Adding counts of APs with                 // given differences and arr[i]                  // is last element.                 // We consider all APs where                  // an array element is previous                  // element of AP with a particular                 // difference                 if (arr[i] - d >= 1 &&                      arr[i] - d <= 1000000)                     dp[i] += sum[arr[i] - d];                  ans += dp[i] - 1;                 sum[arr[i]] += dp[i];             }         }          return ans;     }          static void Main() {                List<int> arr = new List<int> {1, 2, 3};                  Console.WriteLine(count(arr));     } } 
JavaScript
// JavaScript program to find the number of AP // subsequences in the given array  function count(arr) {      // Initialize the minimum and maximum      // values of the array.     let minarr = +2147483647;     let maxarr = -2147483648;      // Finding the minimum and maximum values of the array.     for (let i = 0; i < arr.length; i++) {         minarr = Math.min(minarr, arr[i]);         maxarr = Math.max(maxarr, arr[i]);     }      // dp[i] stores the count of APs ending with arr[i].     // sum[j] stores the sum of all dp[]'s with j as an AP element.     let dp = new Array(arr.length);     let sum = new Array(1000001);      // Initialize answer with arr.length + 1, as single      // elements and an empty array are also APs.     let ans = arr.length + 1;      // Traversing all possible common differences.     for (let d = minarr - maxarr; d <= maxarr - minarr; d++) {         sum.fill(0);          // Traverse each element of the array.         for (let i = 0; i < arr.length; i++) {                      // Initialize dp[i] = 1.             dp[i] = 1;              // Add counts of APs with the given difference              // and arr[i] as the last element.             // We consider all APs where a previous array              // element is part of an AP with the same difference.             if (arr[i] - d >= 1 && arr[i] - d <= 1000000) {                 dp[i] += sum[arr[i] - d];             }              ans += dp[i] - 1;             sum[arr[i]] += dp[i];         }     }      return ans; }  let arr = [1, 2, 3]; console.log(count(arr)); 

Output
8 


Next Article
Introduction to Dynamic Programming on Trees

A

Anuj Chauhan
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • arithmetic progression
Practice Tags :
  • Dynamic Programming

Similar Reads

  • Dynamic Programming or DP
    Dynamic 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
  • What is Memoization? A Complete Tutorial
    In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
    6 min read
  • Dynamic Programming (DP) Introduction
    Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again. The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way
    15+ min read
  • Tabulation vs Memoization
    Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches. Memoization:Top-down approachStores the results of function c
    9 min read
  • Optimal Substructure Property in Dynamic Programming | DP-2
    The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
    4 min read
  • Overlapping Subproblems Property in Dynamic Programming | DP-1
    Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
    10 min read
  • Steps to solve a Dynamic Programming Problem
    Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
    14 min read
  • Advanced Topics

    • Count Ways To Assign Unique Cap To Every Person
      Given n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps. Example: Input: caps = [[3, 4], [4, 5], [5]] Outpu
      15+ min read

    • Digit DP | Introduction
      Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
      14 min read

    • Sum over Subsets | Dynamic Programming
      Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
      10 min read

    Easy problems in Dynamic programming

    • Coin Change - Count Ways to Make Sum
      Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
      15+ min read

    • Subset Sum Problem
      Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = [3, 34,
      15+ min read

    • Introduction and Dynamic Programming solution to compute nCr%p
      Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
      15+ min read

    • Rod Cutting
      Given a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces. Note: price[] is 1-indexed array. Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explana
      15+ min read

    • Painting Fence Algorithm
      Given a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color. Examples: Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways whe
      15 min read

    • Longest Common Subsequence (LCS)
      Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
      15+ min read

    • Longest Increasing Subsequence (LIS)
      Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest incre
      14 min read

    • Longest subsequence such that difference between adjacents is one
      Given an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1. Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], whe
      15+ min read

    • Maximum size square sub-matrix with all 1s
      Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s. Example: Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ] Output: 3Explanation: The maximum length of
      15+ min read

    • Min Cost Path
      You are given a 2D matrix cost[][] of dimensions m × n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0).The total cost of a path is the sum of
      15+ min read

    • Longest Common Substring (Space optimized DP solution)
      Given two strings ‘s1‘ and ‘s2‘, find the length of the longest common substring. Example: Input: s1 = “GeeksforGeeks”, s2 = “GeeksQuiz” Output : 5 Explanation:The longest common substring is “Geeks” and is of length 5. Input: s1 = “abcdxyz”, s2 = “xyzabcd” Output : 4Explanation:The longest common s
      7 min read

    • Count ways to reach the nth stair using step 1, 2 or 3
      A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs. Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}
      15+ min read

    • Grid Unique Paths - Count Paths in matrix
      Given an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down. Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
      15+ min read

    • Unique paths in a Grid with Obstacles
      Given a grid[][] of size m * n, let us assume we are starting at (1, 1) and our goal is to reach (m, n). At any instance, if we are on (x, y), we can either go to (x, y + 1) or (x + 1, y). The task is to find the number of unique paths if some obstacles are added to the grid.Note: An obstacle and sp
      15+ min read

    Medium problems on Dynamic programming

    • 0/1 Knapsack Problem
      Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
      15+ min read

    • Printing Items in 0/1 Knapsack
      Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
      12 min read

    • Unbounded Knapsack (Repetition of items allowed)
      Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
      15+ min read

    • Egg Dropping Puzzle | DP-11
      You are given n identical eggs and you have access to a k-floored building from 1 to k. There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below: An egg
      15+ min read

    • Word Break
      Given a string s and y a dictionary of n words dictionary, check if s can be segmented into a sequence of valid words from the dictionary, separated by spaces. Examples: Input: s = "ilike", dictionary[] = ["i", "like", "gfg"]Output: trueExplanation: The string can be segmented as "i like". Input: s
      12 min read

    • Vertex Cover Problem (Dynamic Programming Solution for Tree)
      A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
      15+ min read

    • Tile Stacking Problem
      Given integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note: A stable tower consists of exactly n tiles, each sta
      15+ min read

    • Box Stacking Problem
      Given three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
      15+ min read

    • Partition a Set into Two Subsets of Equal Sum
      Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both. Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: T
      15+ min read

    • Travelling Salesman Problem using Dynamic Programming
      Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost. Note the differenc
      15 min read

    • Longest Palindromic Subsequence (LPS)
      Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Examples: Input: s = "bbabcbcab"Output: 7Explanation: Subsequence "babcbab" is the longest su
      15+ min read

    • Longest Common Increasing Subsequence (LCS + LIS)
      Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS. Examples: Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The lo
      15+ min read

    • Find all distinct subset (or subsequence) sums of an array
      Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
      15+ min read

    • Weighted Job Scheduling
      Given a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges. Note: If the job ends at time X, it is allowed to
      15+ min read

    • Count Derangements (Permutation such that no element appears in its original position)
      A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements. Examples : Input: n = 2Output: 1Explanation: For two balls [
      12 min read

    • Minimum insertions to form a palindrome
      Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions. Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic str
      15+ min read

    • Ways to arrange Balls such that adjacent balls are of different types
      There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QP Input: p = 1, q = 1,
      15+ 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