Virtusa Polaris – Fresher Interview Questions with answers

This blog explains about Virtusa Polaris – Fresher Interview Questions with answers . Some of them are discussed below :

_______________________________________________________

LONGEST COMMON SEQUENCE

Virtusa Core COE Version 1

Given two strings, ‘x’ and ‘y’ (1 <= lenth(x), length(y) <= 1000), find the length of their Longest Common Subsequence (LCS). The strings contains only lowercase letters.

You need to fill in a function that takes input two strings and sets the output variable to the length of their LCS.

Input

inputl the string ‘x’

input2: the string ‘y’

Output

Return the length of the LCS of ‘x’ and ‘y’

________________________________________________________________

/* A Naive recursive implementation of LCS problem in java*/

public class LongestCommonSubsequence

{

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */

int lcs( char[] X, char[] Y, int m, int n )

{

if (m == 0 || n == 0)

return 0;

if (X[m-1] == Y[n-1])

return 1 + lcs(X, Y, m-1, n-1);

else

return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

}

/* Utility function to get max of 2 integers */

int max(int a, int b)

{

return (a > b)? a : b;

}

public static void main(String[] args)

{

LongestCommonSubsequence lcs = new LongestCommonSubsequence();

String s1 = “aba”;

String s2 = “ababa”;

char[] X=s1.toCharArray();

char[] Y=s2.toCharArray();

int m = X.length;

int n = Y.length;

System.out.println(“Length of LCS is” + ” ” +

lcs.lcs( X, Y, m, n ) );

}

}

_________________________________________________________________

LCS Problem Statement:

2 ) Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.

For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.

Here is the source code of the Java Program to implement Longest Common Substring Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.