Showing posts with label coding interview. Show all posts
Showing posts with label coding interview. Show all posts

Friday, August 30, 2019

Finding the numbers in Array for Given Sum


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class LocalTest {

// Finding sum of two numbers using O(n2)
public static int[] getSum(int arra[], int sum) {

for (int i = 0; i < arra.length; i++) {
for (int j = 0; j < arra.length; j++) {
if (arra[i] + arra[j] == sum) {
return new int[] { arra[i], arra[j] };
}

}
}
return null;
}

//Finding sum of two numbers using O(n)
public static int[] findSum(int arra[], int sum) {

Map<Integer, Integer> arraryMap = new HashMap<Integer, Integer>();
for (int i = 0; i < arra.length; i++) {
int value = arra[i];
if (arraryMap.containsKey(sum - value)) {
return new int[] { arra[arraryMap.get(sum - value)], arra[i]  };
}
arraryMap.put(value, i);
}
return null;
}

public static void main(String[] args) {
int arrValues[] = {2,5,7,9,11,3,8 };
System.out.println(Arrays.toString(getSum(arrValues,13)));
System.out.println(Arrays.toString(findSum(arrValues,13)));

}

}

Output
[2, 11]

[2, 11]
Thanks for your valuable comments

Thursday, December 25, 2014

Algorithm coding interview questions

Following should be prepared before preparing interview for product/development base companies

Implement stack
Implementation of queue
Linked list implementation
Stack and queue implementation using linked list
Tree and binary tree implementation
Double linked list
Merge and quick sort
String operations
Arrays rotation
Search for integers in collection
Min, max and sum of elements