Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created August 10, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravichandrae/384630499ba3059c94d0 to your computer and use it in GitHub Desktop.
Save ravichandrae/384630499ba3059c94d0 to your computer and use it in GitHub Desktop.
Given two arrays of numbers, how to check if the first sequence is a sub sequence of second sequence.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
while( t-- > 0 )
{
int n = reader.nextInt();
int i;
int [] seq = new int[n];
for( i = 0; i < n; i++ )
seq[i] = reader.nextInt();
int m = reader.nextInt();
int [] subSeq = new int[m];
for( i = 0; i < m; i++ )
subSeq[i] = reader.nextInt();
if( isSubSequence(subSeq,seq) )
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
public static boolean isSubSequence(int []subSeq, int []seq)
{
int i,j;
for( i = 0, j = 0; i < subSeq.length && j < seq.length; )
{
if (subSeq[i] == seq[j])
i++;
j++;
}
return i == subSeq.length? true:false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment