Nagarro Interview Question for Java Developers


Country: United States




Comment hidden because of low score. Click to expand.
10
of 10 vote

public boolean checkOrder(String source, String pattern) {
	int iSource = 0;
	int iPattern = 0;

	//we scan source and increase index of next searched char in the pattern;
	for (iSource = 0; iSource<source.length(), iSource++) {
		if (source.charAt[iSource] == pattern[iPattern]) {
			iPattern++;
		}
		if (iPattern == pattern.length()) {
			//all pattern discovered, success
			return true;
		}
	}
	//nope
	return false;

}

- kirillskiy October 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

The solution wont work if, the first occurrence of character is not the right occurrence.
Example:
TextString: abcNjAhNgAhGjhfhAljhRkhgRbhjbevfhO
^ ^
Sample string :NAGARRO

- ashek1520 January 14, 2016 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

#include <stdio.h>

int is_match(char *a, char *b, int i, int j, int k, int l)
{
	if (k >= l)
		return 1;
	if (i >= j)
		return 0;
	if (a[i] == b[k])
		return is_match(a, b, i+1, j, k+1, l);
	else
		return is_match(a, b, i+1, j, k, l);
}

int main()
{
	char foo[] = {"abcNjhgAhGjhfhAljhRkhgRbhjbevfhO"};
	char bar[] = {"NAGARRG"};
	int i, j, k, l;
	i = k = 0;
	j = strlen(foo);
	l = strlen(bar);
	printf("%d\n", is_match(foo, bar, i, j, k, l));
	return 0;
}

- aka October 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class String_Match {

public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "VF5sdR12T12Ec";
String Sample = "VF512Ec";
int m=0;
int i=0;
int j=0;
for (i=0;i<Sample.length();i++)
{
for (j=0;j<test.length();j++)
{
if (Sample.charAt(i)!= test.charAt(j))
{
continue;
}
else
{
i=i+1;
m=m+1;

}
if (i==Sample.length())
break;
}
}
if (m==Sample.length())
{
System.out.println("Matched");
}
else
System.out.println("sdfvdfsv----------"+m);


}

}

- Arun October 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class String_Match {

public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "VF5sdR12T12Ec";
String Sample = "VF512Ec";
int m=0;
int i=0;
int j=0;
for (i=0;i<Sample.length();i++)
{
for (j=0;j<test.length();j++)
{
if (Sample.charAt(i)!= test.charAt(j))
{
continue;
}
else
{
i=i+1;
m=m+1;

}
if (i==Sample.length())
break;
}
}
if (m==Sample.length())
{
System.out.println("Matched");
}
else
System.out.println("sdfvdfsv----------"+m);


}

}

- Arun October 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class String_Match {

public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "VF5sdR12T12Ec";
String Sample = "VF512Ec";
int m=0;
int i=0;
int j=0;
for (i=0;i<Sample.length();i++)
{
for (j=0;j<test.length();j++)
{
if (Sample.charAt(i)!= test.charAt(j))
{
continue;
}
else
{
i=i+1;
m=m+1;

}
if (i==Sample.length())
break;
}
}
if (m==Sample.length())
{
System.out.println("Matched");
}
else
System.out.println("sdfvdfsv----------"+m);


}

}

- Anonymous October 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

According to the requirement, is NRRAGARRO considered a match for NAGARRO?

- IC October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
void main()
{
char a[50];
int i;
printf("\n enter any string");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=65&&a[i]<=90)
{
printf("%c",a[i]);
}
}
}

- Anonymous October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
void main()
{
char a[50];
int i;
printf("\n enter any string");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=65&&a[i]<=90)
{
printf("%c",a[i]);
}
}
}

- Anonymous October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
void main()
{
char a[50];
int i;
printf("\n enter any string");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=65&&a[i]<=90)
{
printf("%c",a[i]);
}
}
}

- VEER October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public boolean isSameOrder(String test, String sample) {

		int indexTest = 0;
		int indexSample = 0;
		while (indexTest < test.length() && indexSample < sample.length()) {
			if (test.charAt(indexTest) == sample.charAt(indexSample)) {
				++indexSample;
			}
			++indexTest;
		}
		return (indexSample == sample.length()) ? true : false;

}

- sammath October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my code in python.

def longers(P,S):
    maps = {}
    str1 = ''
    str2 =''
    for i in S:
        maps[str(i)] = str(ord(i))
    for ij in P:
        str1 = str1 + str(maps.get(ij))
    print str1
    for x in P:
        str2 = str2+str(str(ord(x)))
    print str2
    if str1 == str2:
        return True
    else:
        return False

print longers('NAGARRG', 'abcNjhgAhGjhfhAljhRkhgRbhjbevfhO')

- revanthpobala October 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi Bro,

New in python...

I tried to write this code in other way ..

Please have a look....

def matchOrder(sample, main):
    
    strArr = []
    for i in sample:
        strArr.append(i)    
    k=0;
    counter = 0
    j = 0
    arrLength=len(strArr)
    mainArrLength = len(main)
    
    for eachVal in strArr:
        for i in range(counter,mainArrLength):  
            if main[i] == strArr[k]:
               k+=1
               counter = j
               j+=1
               break
            j+=1            
               
    if k == arrLength:
        return "Same Order"
    else:
        return "Not Same Order"
        
        

print matchOrder('NAGARRO', 'abcNjhgAhGjhfhAljhRkhgRbhjbevfhO')

- saikat1239 November 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Implemented using VC++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
	char str[] = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO";
	char test[] = "NAGARRO";
	char *testptr = test, *strp = str, *strptr;
	int i = -1, j = -1;

	while (*strp != '\0') {
		strptr = strp;
		++i;
		if (*strptr == *testptr) {
			++j;
			++testptr;
		}
		++strp;
	} // end while loop
	if (j == strlen(test)-1)
		printf("Match sequence found\n");
	else
		printf("Match sequence not found\n");
system("pause");
}

- rah October 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
	char str[] = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO";
	char test[] = "NAGARRO";
	char *testptr = test, *strp = str, *strptr;
	int i = -1, j = -1;

	while (*strp != '\0') {
		strptr = strp;
		++i;
		if (*strptr == *testptr) {
			++j;
			++testptr;
		}
		++strp;
	} // end while loop
	if (j == strlen(test)-1)
		printf("Match sequence found\n");
	else
		printf("Match sequence not found\n");
system("pause");
}

- rah October 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
	char str[] = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO";
	char test[] = "NAGARRO";
	char *testptr = test, *strp = str, *strptr;
	int i = -1, j = -1;

	while (*strp != '\0') {
		strptr = strp;
		++i;
		if (*strptr == *testptr) {
			++j;
			++testptr;
		}
		++strp;
	} // end while loop
	if (j == strlen(test)-1)
		printf("Match sequence found\n");
	else
		printf("Match sequence not found\n");
system("pause");
}

- rah October 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class sameorder {

	public static void main(String[] args) {
		System.out.println(isEqual("NAGARRO", "abcNjhgAhGjhfhAljhRkhgRbhjbevfhO"));

	}
	public static Boolean isEqual (String str1, String str2) {
	
		Integer pos = 0;
		for(int i=0; i< str1.length(); i++) {
			if (str2.substring(pos).contains(str1.substring(i, i+1))) {
			     
					pos = str2.substring(pos).indexOf(str1.substring(i, i+1));
					pos = pos +1;
					}
					
			else
					return false;
						
				}
		
		return true;	
			
			}

}

- ikotletka October 31, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static boolean isOrderKept(String bigS, String sample) {
		if(bigS == null || bigS.isEmpty() || sample.isEmpty() || sample == null) return false;
		if(bigS.contains(sample)) return true;
		char[] sampleCh = sample.toCharArray();
		int i=0;
		for(char c : bigS.toCharArray()) {
			if(sampleCh[i] == c) {
				i++;
			}
		}
		return i == sampleCh.length;
	}

- Elica November 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static boolean isOrderKept(String bigS, String sample) {
		if(bigS == null || bigS.isEmpty() || sample.isEmpty() || sample == null) return false;
		if(bigS.contains(sample)) return true;
		char[] sampleCh = sample.toCharArray();
		int i=0;
		for(char c : bigS.toCharArray()) {
			if(sampleCh[i] == c) {
				i++;
			}
		}
		return i == sampleCh.length;
	}

- Elica November 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class GetCharacter
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in); // Create a scanner class object for user input at runtime
System.out.println("Enter a String");
String inputString=sc.next();
findCharacter(inputString); // call the method that find Upper character of given string
}

static void findCharacter(String str)
{
char[]ch=str.toCharArray(); //convert a string to character array
boolean b1; //declare a boolean that's that true /false
{
for(int i=0;i<ch.length;i++) //iterate the charater array
{
if(b1 = Character.isUpperCase(ch[i])) // check if iterate character is upper case
{
System.out.print(ch[i]); // print if upper case
}
}
}
}
}

OutPut:

E:\string>javac GetCharacter.java

E:\string>java GetCharacter
Enter a String
abcNjhgAhGjhfhAljhRkhgRbhjbevfhO
NAGARRO
E:\string>

- Rahul Chaturvedi November 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sss

- Anonymous November 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

sssss

- Anonymous November 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

isValid = True
sast = "abcNjhgAhGjhfhAljhRkhgRbhjbevfhO"
st = "NAGARRO"
p = 0
for ch in st:
    if (sast.find(ch, p) < 0):
        isValid = False
        break
    p +=1

print isValid

- swastik November 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean findContainsString(String s1, String s2){
		
		int count_s2=0;
		for(int i=0;i<s1.length();++i){
			if (s1.charAt(i) == s2.charAt(count_s2)){
				count_s2+=1;
			}
		}
		if(count_s2==s2.length()){
			return true;
		}
		return false;

}

- Nisarg7 November 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void sameOrderStringSearch(){
		String str ="abcNjhgAhGjhfhAljhRkhgRbhjbevfhO";
		String searchStr = "fhAlj";
		sameOrderStringSearchParam(str,searchStr);
	}
	public static void sameOrderStringSearchParam(String str,String searchStr){
		int len = searchStr.length();
		int startPos = 0,indexOfSearchStr = 0;;
		boolean firstMatch = false;
		for( int i = 0 ; i < str.length();i++){
			if( str.charAt(i) == searchStr.charAt(indexOfSearchStr) ){
				
				if( !firstMatch ){
					firstMatch  =true;
					startPos = i;
				}
				indexOfSearchStr++;
				if(  indexOfSearchStr ==  len ){
					break;
				}
			}else{
				firstMatch  =false;
				startPos = -1;
				indexOfSearchStr = 0;
			}
		}
		
		System.out.println(startPos);
	}

- rbl December 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void sameOrderStringSearch(){
		String str ="abcNjhgAhGjhfhAljhRkhgRbhjbevfhO";
		String searchStr = "fhAlj";
		sameOrderStringSearchParam(str,searchStr);
	}
	public static void sameOrderStringSearchParam(String str,String searchStr){
		int len = searchStr.length();
		int startPos = 0,indexOfSearchStr = 0;;
		boolean firstMatch = false;
		for( int i = 0 ; i < str.length();i++){
			if( str.charAt(i) == searchStr.charAt(indexOfSearchStr) ){
				
				if( !firstMatch ){
					firstMatch  =true;
					startPos = i;
				}
				indexOfSearchStr++;
				if(  indexOfSearchStr ==  len ){
					break;
				}
			}else{
				firstMatch  =false;
				startPos = -1;
				indexOfSearchStr = 0;
			}
		}
		
		System.out.println(startPos);
	}

- rbl December 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi folks,
What do you folks think about my python code?
I would be glad for your feedbacks

def collect(text, sample):
	mem = [None] * len(text)
	for i in range(len(text)):
		if text[i] in sample:
			mem[i] = text[i]
	
	return mem

def is_matches_order(collect(text, sample), sample):
	mem = [i for i in collect(text,sample) if i!=None]
	pos = 0
	matches = True
	while pos < len(sample) and matches:
		if sample[pos] != mem[pos]:
			matches = False
		else:
			pos += 1

	if matches:
		return True
	else:
		return False

- Davron December 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

asdasd

- Davron December 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I'm making the assumption that capital letters aren't actually significant, and just coincidental in the example. This code will perform a pass on the "jumble" of letters and keep track of the next position in the desired string that needs to be found. If all letters can be found before it reaches the end of the string, it will exit early.

Either way, we do a check at the end of the function to see whether we're equal to the length of the string, meaning we've captured all letters. This guarantees that we'll find them in the right order, because this code will skip letters that are technically in the string if it hasn't found one that's come before. This code operates in ~O(length(jumble)) time and uses O(1) space.

boolean findInJumble(String jumble, String desired) {
	final int jumbleLength = jumble.length();
	final int desiredLength = desired.length();
	if (jumbleLength < desiredLength) {
		return false;
	}
	
	int desiredPos = 0;
	for (int i = 0; i < jumbleLength; i++) {
		if (desiredPos == desiredLength) {
			break;
		}

		if (jumble.charAt(i) == desired.charAt(desiredPos)) {
			desiredPos++;
		}
	}

	return desiredPos == desiredLength;
}

- Chris December 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def check(text, sample):
    pos = 0 
    for i in range(len(text)):
        if text[i] == sample[pos]: 
            pos += 1
        if pos == len(sample): 
            return True
    return False

- davron.sh.karimov December 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

VB Script:
{
SP = "INDIA"
JB = "sdfIsdfNdfsdDsdfsdfIdfgfA"

Function ValidateStringOrder(SP,JB)


For i = 1 to len(SP)
op = mid(SP,i,1)
If Instr(JB,op) > 1 Then
pos = Instr(JB,op)

If pos > oldPos then
Sq = mid(JB,pos,1)
NewStr = NewStr + Sq

If NewStr = SP Then
msgbox "Value matched"
End If

Else
msgbox "Value NOT matched"
End IF
oldPos = pos
End If
Next

End Function
}

- Suman Lata December 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

SP = "INDIA"
JB = "sdfIsdfNdfsdDsdfsdfIdfgfA"

Function ValidateStringOrder(SP,JB)
	
	
	For i = 1 to len(SP) 
		op = mid(SP,i,1)
		If  Instr(JB,op) > 1 Then
			pos = Instr(JB,op)
						
			If pos > oldPos then 
				Sq = mid(JB,pos,1)
				NewStr = NewStr + Sq
				
				If NewStr = SP Then
					msgbox "Value matched"
				End If
					
			Else 
					msgbox "Value NOT matched"
			End IF
			oldPos = pos
		End If
	Next
	
End Function

- Suman Lata December 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

SP = "INDIA"
JB = "sdfIsdfNdfsdDsdfsdfIdfgfA"

Function ValidateStringOrder(SP,JB)
	
	
	For i = 1 to len(SP) 
		op = mid(SP,i,1)
		If  Instr(JB,op) > 1 Then
			pos = Instr(JB,op)
						
			If pos > oldPos then 
				Sq = mid(JB,pos,1)
				NewStr = NewStr + Sq
				
				If NewStr = SP Then
					msgbox "Value matched"
				End If
					
			Else 
					msgbox "Value NOT matched"
			End IF
			oldPos = pos
		End If
	Next
	
End Function

- Anonymous December 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Ascii {

public static void ascii(String a){
char[] ch=a.toCharArray();
@SuppressWarnings("unused")
String str=null;
for(int i=0;i<a.length();i++){
if(ch[i]>=65 && ch[i]<=96){
str=new String(ch);
System.out.print(ch[i]);
}
}
}
public static void main(String[] args) {
ascii("asdhfjjSbdjsfgAjsfjYjnbhfgAbhjhdsfNjnffjnaj");
}
}
\\Give whatever input you wanna give.It will give output of only the Uppercase letters.

- Sayan Moitra December 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{public class Ascii {
	
	public static void ascii(String a){
		char[] ch=a.toCharArray();
		@SuppressWarnings("unused")
		String str=null;
		for(int i=0;i<a.length();i++){
			if(ch[i]>=65 && ch[i]<=96){
				str=new String(ch);
				System.out.print(ch[i]);
			}
		}
	}
public static void main(String[] args) {
	ascii("asdhfjjSbdjsfgAjsfjYjnbhfgAbhjhdsfNjnffjnaj");
}

}}

- Sayan Moitra December 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Ascii {
	
	public static void ascii(String a){
		char[] ch=a.toCharArray();
		@SuppressWarnings("unused")
		String str=null;
		for(int i=0;i<a.length();i++){
			if(ch[i]>=65 && ch[i]<=96){
				str=new String(ch);
				System.out.print(ch[i]);
			}
		}
	}
public static void main(String[] args) {
	ascii("asdhfjjSbdjsfgAjsfjYjnbhfgAbhjhdsfNjnffjnaj");
}
}

- Sayan Moitra December 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Ascii
public static void ascii(String a)
char[] ch=a.toCharArray();
@SuppressWarnings("unused")
String str=null;
for(int i=0;i<a.length();i++)
if(ch[i]>=65 && ch[i]<=96)
str=new String(ch);
System.out.print(ch[i]);
public static void main(String[] args)
ascii("asdhfjjSbdjsfgAjsfjYjnbhfgAbhjhdsfNjnffjnaj");

- Sayan Moitra December 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

this is more of a state machine can be edited to check other matches as well

private static bool stringordering(string textstring, string tofollow)
        {
            if(textstring == null || tofollow == null)
            {
                return false;
            }
            Dictionary<int,char> charstate = new Dictionary<int, char>();
            for (int i = 0; i < tofollow.Length-1; i++)
            {
                charstate.Add(i+1,tofollow[i]);
            }

            int state = 0;//
            bool flag = false;
            for (int j = 0; j < textstring.Length-1;j++ )
            {
                if(charstate[state+1] == textstring[j])
                {
                    state = state + 1;
                    if (state == tofollow.Length - 1)
                    {
                        flag = true;
                        break;
                    }
                    
                }
            }

            
            return flag;
        }

- prakhar srivastava January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static bool stringordering(string textstring, string tofollow)
{
if(textstring == null || tofollow == null)
{
return false;
}
Dictionary<int,char> charstate = new Dictionary<int, char>();
for (int i = 0; i < tofollow.Length-1; i++)
{
charstate.Add(i+1,tofollow[i]);
}

int state = 0;//
bool flag = false;
for (int j = 0; j < textstring.Length-1;j++ )
{
if(charstate[state+1] == textstring[j])
{
state = state + 1;
if (state == tofollow.Length - 1)
{
flag = true;
break;
}

}
}


return flag;
}

- prakhar srivastava January 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static bool compareSameOrder(string string1, string string2)
        {
            string string3 = string.Empty;
            foreach (char ch in string1)
                if (string2.Contains(ch.ToString()))
                    string3 += ch.ToString();
            if (string2.Equals(string3))
                return true;
            else
                return false;
        }

- NSP February 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static bool compareSameOrder(string string1, string string2)
        {
            string string3 = string.Empty;
            foreach (char ch in string1)
                if (string2.Contains(ch.ToString()))
                    string3 += ch.ToString();
            if (string2.Equals(string3))
                return true;
            else
                return false;
        }

- NSP February 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static bool compareSameOrder(string string1, string string2)
{
string string3 = string.Empty;
foreach (char ch in string1)
if (string2.Contains(ch.ToString()))
string3 += ch.ToString();
if (string2.Equals(string3))
return true;
else
return false;
}

- NSP February 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

posting an O(n) solution:-

#include <iostream>
#include <queue>

#define ASCII_SIZE 256

using namespace std;

int main()
{
    queue<int> counts[ASCII_SIZE];


    string testStr, actualStr;
    cout<<"Enter test string"<<endl;
    getline(cin, testStr);

    cout<<"Enter actual string"<<endl;
    getline(cin, actualStr);

    int curr=1;
    for(int i=0; i<testStr.length(); i++){
        counts[testStr[i]].push(curr);
        ++curr;
    }

    int currentIndex = 1;
    int flag = 1;
    for(int i=0; i<actualStr.length(); i++){
        if(counts[actualStr[i]].empty()){
            continue;
        }
        
        else if(counts[actualStr[i]].front() == currentIndex){
            counts[actualStr[i]].pop();
            ++currentIndex;
        }
        
        else{
            flag = 0;
            break;
        }
    }
    if(flag == 1){
        cout<<"Order preserved"<<endl;
    }
    else{
        cout<<"Order not preserved"<<endl;
    }
  return 0;
}

- Sarthak Gupta February 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

posting an O(n) solution:-

#include <iostream>
#include <queue>

#define ASCII_SIZE 256

using namespace std;

int main()
{
    queue<int> counts[ASCII_SIZE];


    string testStr, actualStr;
    cout<<"Enter test string"<<endl;
    getline(cin, testStr);

    cout<<"Enter actual string"<<endl;
    getline(cin, actualStr);

    int curr=1;
    for(int i=0; i<testStr.length(); i++){
        counts[testStr[i]].push(curr);
        ++curr;
    }

    int currentIndex = 1;
    int flag = 1;
    for(int i=0; i<actualStr.length(); i++){
        if(counts[actualStr[i]].empty()){
            continue;
        }
        
        else if(counts[actualStr[i]].front() == currentIndex){
            counts[actualStr[i]].pop();
            ++currentIndex;
        }
        
        else{
            flag = 0;
            break;
        }
    }
    if(flag == 1){
        cout<<"Order preserved"<<endl;
    }
    else{
        cout<<"Order not preserved"<<endl;
    }
  return 0;
}

- Sarthak Gupta February 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean isStringInSameOrder(String source, String sample){
		boolean _result=true;
		
		int fromIndex=0;
		for(char curChar:sample.toCharArray()){
			int id=source.indexOf(curChar, fromIndex);
			if (id!=-1){
				fromIndex=id;		
			}
			else{
				_result=false;
				break;
			}
		}
		
		return _result;
	}

- Eko Susilo February 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean assureRightOrder(String text, String word)
{
int j=0;

try{

//Forward the actual substring for each character
for (int i=0; i<word.length(); i++)
{
//Forward the full text until the character matches
while (word.charAt(i)!=text.charAt(j++));

}
}
catch(StringIndexOutOfBoundsException ex)
{
//If reaches here.. It means that the character not found due to incremented j value
return false;

}
// If all characters succeed.. It is in the correct sequence
return true;
}

- Anonymous February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean assureRightOrder(String text, String word)
	{
		int j=0;
		
		try{
			
			//Forward the actual substring for each character
			for (int i=0; i<word.length(); i++)
			{
					//Forward the full text until the character matches
					while (word.charAt(i)!=text.charAt(j++));
			
			}
		}
		catch(StringIndexOutOfBoundsException ex)
		{ 
			//If reaches here.. It means that the character not found due to incremented j value
			return false; 
		
		}
		// If all characters succeed.. It is in the correct sequence
		return true;
	}

- Anonymous February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static boolean assureRightOrder(String text, String word)
	{
		int j=0;
		
		try{
			
			//Forward the actual substring for each character
			for (int i=0; i<word.length(); i++)
			{
					//Forward the full text until the character matches
					while (word.charAt(i)!=text.charAt(j++));
			
			}
		}
		catch(StringIndexOutOfBoundsException ex)
		{ 
			//If reaches here.. It means that the character not found due to incremented j value
			return false; 
		
		}
		// If all characters succeed.. It is in the correct sequence
		return true;

}

- Anonymous February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void checkOrder(){
int i=0;
String str1="abcNfgfAvmMbE";
String str2="NAME";
String str="";
int temp=0;
while(i<str2.length()){
int k= str1.indexOf(str2.charAt(i));
if(k>temp){

i++;
if(i==str2.length()){
System.out.println("yes");
}
}
else{
System.out.println("No");
break;
}
temp=k;


}

}

- fariha April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void checkOrder(){
		int i=0;
		String str1="abcNfgfAvmMbE";
		String str2="NMAE";
		String str="";
		int temp=0;
		while(i<str2.length()){
		int k= str1.indexOf(str2.charAt(i));
		if(k>temp){
			System.out.println("k....."+k);
			i++;
			if(i==str2.length()){
				System.out.println("yes");
			}
		}
		else{
			System.out.println("No");
			break;
		}
		temp=k;
		
		
		}
		
	}

- fariha April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void checkOrder(){
int i=0;
String str1="abcNfgfAvmMbE";
String str2="NMAE";

- fariha April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

cdc

- fariha April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void CompileWord()
{
string TextString = "abcNjhgAhGjhfhAljhRkhgRbhjbevfhO";
string Match = "NAGARRO";
int T = TextString.Length;
int M = Match.Length;
int count = 0;
string name = null;
for (int i = 0; i <T; i++)
{
if (Match[count] == TextString[i])
{
name = name + Match[count];
count++;
}
if(count==M)
{
Console.WriteLine(name);
}
}
}

- Satyendra April 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

input_str = "abcNjhgAhGGjhfhAljhRkhgRbhjbevfO"
sample_str = "NAGARRO"

j=count=0

for i in range(len(input_str)):
    #print input_str[i]
    if sample_str[j]==input_str[i]:
        print sample_str[j]
        j+=1
        count+=1

if count==len(sample_str):
    print "In order"
else:
    print"out of order"

- Shiva June 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C++:

//use a queue to mark off the pattern, at the end
	//if the queue is empty this means we have gone
	//and found the pattern in order
	bool has_order( queue<char> order, string str ) {
		for( int i = 0; i < str.size( ); ++i ) if( str[i] == order.front( ) ) order.pop( );
		if( order.size( ) == 0 ) return true;
		else return false
	}

- Matheus Barbosa August 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simple solution in C programming.

int find(char *text,char *sample){

int n = strlen(text);
int l = strlen(sample);
int count = 0;
int flag;

while(*text){
flag = 0;
if (*text >= 'A' && *text <= 'Z'){
if(*sample == *text){
flag = 1;
count++;
sample++;
}
if(flag == 0)
return 0;
}
text++;
}

if(l==count)
return 1;
else
return 0;
}

- Amrutha September 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class NAGARRO{
	
	public static void main(String a[]){
		
		String text="abcNjhgAhGjhfhAljhRkhgRbhjbevfhOPPPP";
		String sample="NAGARRO";
		
		if(findOrder(text, sample)){
			System.out.println("Match");
		}else{
			System.out.println("Not Match");
		}
		
	}
		
		public static boolean findOrder(String text, String sample){
			
			int textLnth=text.length();
			int sampleLnth=sample.length();
			int textStart=0;
			int sampleStart=0;
			if(textLnth<sampleLnth){
				return false;
			}
				for(int j=sampleStart; j<sampleLnth; j++){
					
					for(int i=textStart; i<textLnth; i++){
						
						char textChar=text.charAt(i);
						char sampleChar=sample.charAt(j);	
						
						if(sampleChar==textChar){
							
							if((textLnth-(i+1))<(sampleLnth-(j+1))){
								return false;
							}
						textStart=i+1;
						sampleStart=j+1;
						break;	
						}	
					}
			}
			return true;	
		}
	}

- jai kishan sharma September 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
import java.lang.*;
import java.io.*;

class PatternSequence
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="Hello World"; //br.readLine();
String pat="eol"; //br.readLine();

int len=str.length(); // System.out.println(len);
int pate=pat.length(); // System.out.println(pate);
int A[]=new int[pate];
int j=0;

while(j<pate)
{
for(int i=0;i<len;i++)
{
if(pat.charAt(j)==(str.charAt(i)))
{A[j]=i;}

}
j++;
}
/* for(int n=0;n<pate;n++)
System.out.println(A[n]); */

int res=0;
for(int m=0;m<pate-1;m++)
{
for(int n=m+1;n<pate;n++) // exception out of bound will come if i put pate+1 in place of pate
{
if(A[m]>A[n])
{ res++; }
}

}

if(res>0)
{System.out.println("False");}
else
{System.out.println("true");}
/**/
}
}

- Jedi Warrior October 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static boolean inSameOrder(char[] source, String sampleString) {
int i , j=0 , count=0 ;
for ( i =0 ; i <source.length ; i++) {
if(sampleString.charAt(j)==input[i]){
j++;
count++;
}
}
return (count == sampleString.length()) ? true : false ;
}

- Anonymous October 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static boolean inSameOrder(char[] source, String sampleString) {
int i , j=0 , count=0 ;
for ( i =0 ; i <source.length ; i++) {

if(sampleString.charAt(j)==source[i]){
j++;
count++;
}

}

return (count == sampleString.length()) ? true :false ;
}

- Shadab Ahmad October 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
            char[] Pattern = "NAGARRO".ToCharArray();
            int k = -1;
            int count = 0;
            for (int i=0;i<Pattern.Length;i++)
            {
                k++;
                for (; k < TextString.Length; k++)
                {
                    if (Pattern[i] == TextString[k])
                    {
                        count++;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (count == Pattern.Length)
            {
                Console.WriteLine("True");
            }
            else
            {
                Console.WriteLine("False");
            }
            Console.ReadLine();

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
            char[] Pattern = "NAGARRO".ToCharArray();
            int k = -1;
            int count = 0;
            for (int i=0;i<Pattern.Length;i++)
            {
                k++;
                for (; k < TextString.Length; k++)
                {
                    if (Pattern[i] == TextString[k])
                    {
                        count++;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (count == Pattern.Length)
            {
                Console.WriteLine("True");
            }
            else
            {
                Console.WriteLine("False");
            }
            Console.ReadLine();

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
char[] Pattern = "NAGARRO".ToCharArray();
int k = -1;
int count = 0;
for (int i=0;i<Pattern.Length;i++)
{
k++;
for (; k < TextString.Length; k++)
{
if (Pattern[i] == TextString[k])
{
count++;
break;
}
else
{
continue;
}
}
}
if (count == Pattern.Length)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Console.ReadLine();

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Main(String[] args)
        {
            char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
            char[] Pattern = "NAGARRO".ToCharArray();
            int k = -1;
            int count = 0;
            for (int i=0;i<Pattern.Length;i++)
            {
                k++;
                for (; k < TextString.Length; k++)
                {
                    if (Pattern[i] == TextString[k])
                    {
                        count++;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (count == Pattern.Length)
            {
                Console.WriteLine("True");
            }
            else
            {
                Console.WriteLine("False");
            }
            Console.ReadLine();

}

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Main(String[] args)
{
char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
char[] Pattern = "NAGARRO".ToCharArray();
int k = -1;
int count = 0;
for (int i=0;i<Pattern.Length;i++)
{
k++;
for (; k < TextString.Length; k++)
{
if (Pattern[i] == TextString[k])
{
count++;
break;
}
else
{
continue;
}
}
}
if (count == Pattern.Length)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Console.ReadLine();
}

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Main(String[] args)
        {
            char[] TextString = "abcNjhgAhKjhfhAljhRkhgRbhjbevfO".ToCharArray();
            char[] Pattern = "NAGARRO".ToCharArray();
            int k = -1;
            int count = 0;
            for (int i=0;i<Pattern.Length;i++)
            {
                k++;
                for (; k < TextString.Length; k++)
                {
                    if (Pattern[i] == TextString[k])
                    {
                        count++;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (count == Pattern.Length)
            {
                Console.WriteLine("True");
            }
            else
            {
                Console.WriteLine("False");
            }
            Console.ReadLine();

}

- Rama October 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var str = 'abcNjhgAhGjhfhAljhRkhgRbhjbevfhO';
var word = 'NAGARRO', checkword = '', placeAt=0; 
for(var i=0; i<word.length; i++){
	placeAt = str.indexOf(word.charAt(i), placeAt);
	if( placeAt != -1){
  	checkword = checkword.concat(word.charAt(i));
  }
  if(i == word.length-1){
  	if(checkword == word)
  		alert('word found');
     else
      alert('could not find the word.');
  }
}

- Gautam Kumar October 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var str = 'abcNjhgAhGjhfhAljhRkhgRbhjbevfhO';

var word = 'NAGARRO', checkword = '', placeAt=0;

for(var i=0; i<word.length; i++){

placeAt = str.indexOf(word.charAt(i), placeAt);

if( placeAt != -1){

checkword = checkword.concat(word.charAt(i));

}

if(i == word.length-1){

if(checkword == word)

alert('word found');

else

alert('could not find the word.');

}

}

- Gautam Kumar October 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void FindIfCharactersOfSampleStringExistsInSameOrderInText()
{
string TextString = "abcNjhgAhGjhfhAljhRkhgRbhjbevfhO";
string Sample = "NAGARRO";
char[] TextStringCharArr = TextString.ToCharArray();
char[] SampleCharArr = Sample.ToCharArray();
int i = 0;
bool isCharMatched = false;
for(int j=0; j<SampleCharArr.Length;j++)
{
while(i< TextStringCharArr.Length)
{
if(SampleCharArr[j]== TextStringCharArr[i])
{
isCharMatched = true;
i++;
break;
}
else
{
isCharMatched = false;
i++;
}

}
if (!isCharMatched)
break;
}
Console.WriteLine(isCharMatched);
}

- Baliram August 24, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void FindIfCharactersOfSampleStringExistsInSameOrderInText()
        {
            string TextString = "abcNjhgAhGjhfhAljhRkhgRbhjbevfhO";
            string Sample = "NAGARRO";
            char[] TextStringCharArr = TextString.ToCharArray();
            char[] SampleCharArr = Sample.ToCharArray();
            int i = 0;
            bool isCharMatched = false;
            for(int j=0; j<SampleCharArr.Length;j++)
            {
                while(i< TextStringCharArr.Length)
                {
                    if(SampleCharArr[j]== TextStringCharArr[i])
                    {
                        isCharMatched = true;
                        i++;
                        break;
                    }
                    else
                    {
                        isCharMatched = false;
                        i++;
                    }
                   
                }
                if (!isCharMatched)
                    break;
            }
            Console.WriteLine(isCharMatched);
        }

- Baliram August 24, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More