Amazon Interview Question
Software Engineer in TestsThat solution won't actually work. You can't compare Strings with ==, you must use a .equals() comparison. Also, what happens if the String isn't in the array? You need a default return value.
This is one solution, although there are many others:
public static boolean containsValue(String[] arr, String value) {
for(int i = 0; i < arr.length; i++) {
if(arr[i].equals(value)) {
return true;
}
}
return false;
}
Returning the index is a good notion, just depends on what the code is for.
the program also needs to check sub-strings within a string.
for instance
containsValue("Good morning Universe","verse")
should return true
Here is the algorithm
// store the elements of the first array into a hash table
// for every element in the second array, check in the hash table and retrieve the index.
// if the index, forms a sequence, return true.
// else return false.
Time complexity is O(n+m)
To do in O(n)
Step 1: find the occurence of the first character of second array in first array
Step 2: starting from that index, check for each subsequent characters whether they match.
Step 3: if they do not match, go to step 1
Step 4: else, return true
import java.util.Scanner;
public class StringComparisionArray
{
public static void main(String[] a)
{
String[] strings = {"one", "two", "three", "four"};
String str;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the search keyword:");
str = scanner.nextLine();
for (int i = 0; i < strings.length; i++)
{
if (strings[i].equals(str))
{
System.out.println("String is present");
break;
}else
{
System.out.println("String is not present");
}
}
}
}
is this problem solved?
- Anonymous May 06, 2011