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 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:
Longest Subsequence with at least one common digit in every element
Next article icon

Longest Subsequence where index of next element is arr[arr[i] + i]

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to find the maximum length sub-sequence from the array which satisfy the following condition: 
Any element can be chosen as the first element of the sub-sequence but the index of the next element will be determined by arr[arr[i] + i] where i is the index of the previous element in the sequence.

Examples: 

Input: arr[] = {1, 2, 3, 4, 5} 
Output: 1 2 4 
arr[0] = 1, arr[1 + 0] = arr[1] = 2, arr[2 + 1] = arr[3] = 4 
Other possible sub-sequences are {2, 4}, {3}, {4} and {5}

Input: arr[] = {1, 6, 3, 1, 12, 1, 4} 
Output: 3 1 4 

Approach: 

  • Make use of two arrays temp and print.
  • The temp array will store the array elements that are currently under consideration and the print array will store the array elements that are to be printed as the final output.
  • Iterate from 0 to n – 1 and consider the current element as the first element of the sequence.
  • Store all the elements of the current sequence into temp array.
  • If the size of the temp array becomes greater than print array then copy all the contents of the temp array to the print array.
  • When all the sequences have been considered, print the contents of the print array.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> using namespace std;  // Function to print the maximum length sub-sequence void maxLengthSubSeq(int a[], int n) {     // Arrays to store the values to be printed     vector<int> temp, print;      for (int i = 0; i < n; i++) {         int x = i;         temp.clear();          // Iterate till index is in range of the array         while (x < n) {             temp.push_back(a[x]);             x = a[x] + x;  // Move to the next index         }          // If the length (temp) > the length (print) then         // copy the contents of the temp array into         // the print array         if (print.size() < temp.size()) {             print = temp;         }     }      // Print the contents of the array     for (int i = 0; i < print.size(); i++)         cout << print[i] << " "; }  // Driver code int main() {     int a[] = {1, 6, 3, 1, 12, 1, 4};     int n = sizeof(a) / sizeof(a[0]);     maxLengthSubSeq(a, n);     return 0; } 
Java
import java.util.ArrayList;  public class MaxLengthSubSeq {     // Function to print the maximum length sub-sequence     public static void maxLengthSubSeq(int[] a, int n) {         ArrayList<Integer> temp = new ArrayList<>();  // Temp array to store current sequence         ArrayList<Integer> print = new ArrayList<>(); // Print array to store the longest sequence          for (int i = 0; i < n; i++) {             int x = i;             temp.clear();              // Build the sequence starting from index i             while (x < n) {                 temp.add(a[x]);                 x = a[x] + x;  // Move to the next index             }              // Update print array if temp has a longer sequence             if (print.size() < temp.size()) {                 print = new ArrayList<>(temp);             }         }          // Print the longest sequence         for (int num : print) {             System.out.print(num + " ");         }     }      public static void main(String[] args) {         int[] a = {1, 6, 3, 1, 12, 1, 4};         int n = a.length;         maxLengthSubSeq(a, n);     } } 
Python
def max_length_subseq(a):     n = len(a)     temp = []     print_seq = []      for i in range(n):         x = i         temp = []          # Build the sequence starting from index i         while x < n:             temp.append(a[x])             x = a[x] + x  # Move to the next index          # Update print_seq if temp has a longer sequence         if len(print_seq) < len(temp):             print_seq = temp      # Print the longest sequence     for num in print_seq:         print(num, end=" ")  a = [1, 6, 3, 1, 12, 1, 4] max_length_subseq(a) 
C#
using System; using System.Collections.Generic;  class MaxLengthSubSeq {     // Function to print the maximum length sub-sequence     static void MaxLengthSubSeqMethod(int[] a, int n) {         List<int> temp = new List<int>();  // Temp list to store current sequence         List<int> print = new List<int>(); // Print list to store the longest sequence          for (int i = 0; i < n; i++) {             int x = i;             temp.Clear();              // Build the sequence starting from index i             while (x < n) {                 temp.Add(a[x]);                 x = a[x] + x;  // Move to the next index             }              // Update print list if temp has a longer sequence             if (print.Count < temp.Count) {                 print = new List<int>(temp);             }         }          // Print the longest sequence         foreach (int num in print) {             Console.Write(num + " ");         }     }      static void Main(string[] args) {         int[] a = {1, 6, 3, 1, 12, 1, 4};         int n = a.Length;         MaxLengthSubSeqMethod(a, n);     } } 
JavaScript
function maxLengthSubSeq(a) {     let n = a.length;     let temp = [];   // Temp array to store current sequence     let print = [];  // Print array to store the longest sequence      for (let i = 0; i < n; i++) {         let x = i;         temp = [];          // Build the sequence starting from index i         while (x < n) {             temp.push(a[x]);             x = a[x] + x;  // Move to the next index         }          // Update print array if temp has a longer sequence         if (print.length < temp.length) {             print = [...temp];         }     }      // Print the longest sequence     for (let num of print) {         console.log(num + " ");     } }  let a = [1, 6, 3, 1, 12, 1, 4]; maxLengthSubSeq(a); 
PHP
<?php function maxLengthSubSeq($a, $n) {     $temp = array();  // Temp array to store current sequence     $print = array(); // Print array to store the longest sequence      for ($i = 0; $i < $n; $i++) {         $x = $i;         $temp = array();          // Build the sequence starting from index i         while ($x < $n) {             $temp[] = $a[$x];             $x = $a[$x] + $x;  // Move to the next index         }          // Update print array if temp has a longer sequence         if (count($print) < count($temp)) {             $print = $temp;         }     }      // Print the longest sequence     foreach ($print as $num) {         echo $num . " ";     } }  $a = array(1, 6, 3, 1, 12, 1, 4); $n = count($a); maxLengthSubSeq($a, $n); ?> 

Output
3 1 4 

Complexity Analysis:

  • Time Complexity: O(n*n)
  • Auxiliary Space: O(n)


Next Article
Longest Subsequence with at least one common digit in every element

S

SanjayR
Improve
Article Tags :
  • Arrays
  • DSA
  • Technical Scripter
  • subsequence
Practice Tags :
  • Arrays

Similar Reads

  • Longest subsequence of even numbers in an Array
    Given an array arr[] containing N integers, the task is to print the length of the longest subsequence of even numbers in the array. Examples: Input: arr[] = {3, 4, 11, 2, 9, 21} Output: 2 Explanation: The longest subsequence containing even numbers is {4, 2}. Hence, the answer is 2. Input: arr[] =
    5 min read
  • Longest increasing sequence by the boundary elements of an Array
    Given an array arr[] of length N with unique elements, the task is to find the length of the longest increasing subsequence that can be formed by the elements from either end of the array.Examples: Input: arr[] = {3, 5, 1, 4, 2} Output: 4 Explanation: The longest sequence is: {2, 3, 4, 5} Pick 2, Se
    8 min read
  • Longest increasing sequence possible by the boundary elements of an Array
    Given an array arr[] of length N consisting of positive integers, the task is to find the longest increasing subsequence that can be formed by the elements from either end of the array. Examples : Input: N=4 arr[] ={ 1, 4, 2, 3 }Output: 1 3 4Explanation: Append arr[0] to the sequence. Sequence = {1}
    14 min read
  • Longest Subsequence with at least one common digit in every element
    Given an array. The task is to find the length of the longest subsequence in which all elements must have at least one digit in common. Examples: Input : arr[] = { 11, 12, 23, 74, 13 } Output : 3 Explanation: The elements 11, 12, and 13 have the digit '1' as common. So it is the required longest sub
    9 min read
  • Length of longest subsequence in an Array having all elements as Nude Numbers
    Given an array arr[] of N positive integers, the task is to print the length of the longest subsequence of the array such that all of its elements are Nude Numbers. Examples: Input: arr[] = {34, 34, 2, 2, 3, 333, 221, 32 }Output: 4Explanation:Longest Nude number subsequence is {2, 2, 3, 333} and hen
    11 min read
  • Longest alternating subsequence which has maximum sum of elements
    Given a list of length N with positive and negative integers. The task is to choose the longest alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite of the sign of the current element). Among all such subsequences, we have to choose one which has the maxi
    10 min read
  • Longest permutation subsequence in a given array
    Given an array arr containing N elements, find the length of the longest subsequence such that it is a valid permutation of a particular length. If no such permutation sequence exists then print 0.Examples: Input: arr[] = {3, 2, 1, 6, 5} Output: 3 Explanation: Longest permutation subsequence will be
    5 min read
  • Longest alternating subsequence in terms of positive and negative integers
    Given an array arr[] of positive and negative numbers only. The task is to find the length of the longest alternating (means negative-positive-negative or positive-negative-positive) subsequence present in the array. Examples: Input: arr[] = {-4, 3, -5, 9, 10, 12, 2, -1} Output: 5 Explanation: The l
    15+ min read
  • Find the Longest Increasing Subsequence in Circular manner
    Given an array, the task is to find LIS (Longest Increasing Subsequence) in a circular way. Examples : Input : arr[] = {5, 4, 3, 2, 1}Output : 2Although there is no LIS in a given array but in a circular form there can be{1, 5}, {2, 5}, ...... Input : arr[]= {5, 6, 7, 1, 2, 3}Output : 6{1, 2, 3, 5,
    11 min read
  • Longest Subsequence with difference between max and min at most K
    Given an array arr[] of size N and a non-negative integer K, the task is to find the length of the longest subsequence such that the difference between the maximum and the minimum of the subsequence is at most K. Examples: Input: arr[] = {1, 3, 5, 4, 2}, N = 5, K = 3Output: 4Explanation: If we consi
    5 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