Skip to main content
1 of 2
Azee
  • 1.8k
  • 17
  • 24
  1. What will happen if you'll have "-1" in the list?
  2. Your linear algorithm worth O(n^2) which is pretty bad if you are going to increase the number of integers.

I suggest you to load dictionary elements into a hash-map Value -> Index and iterate through the values array looking up for the position in the hashMap. This will give you O(2n) - the complexity will be linear. You'll require 2n of memory but in your case it is insignificant.

public static void main(String[] args) { printResults(new int[]{1, 2, 3, 4}, new int[]{3, 4, 7, 9}); } public static void printResults(int dictionary[], int valuesToSearch[]){ Map<Integer, Integer> positionsMap = new HashMap<>(); IntStream.range(0, dictionary.length).forEach(index -> positionsMap.put(dictionary[index], index)); Arrays.stream(valuesToSearch).mapToObj(value -> positionsMap.containsKey(value) ? format("Value %s is present in the array at index %s", value, positionsMap.get(value)) : format("Value %s is not present in the array", value, positionsMap.get(value) )).forEach(System.out::println); } 
Azee
  • 1.8k
  • 17
  • 24