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, January 29, 2015

Interview Questions Part 1

  • ·         Traverse a binary tree
  • ·         Reverse every k-element in a linked list
  • ·         Find the combination of elements with sum as N.
  • ·         Find the duplicates in Linked List
  • ·         Print binary tree in level order
  • ·         Validation of parenthesis in string (Total number should be equal for “(“ and “)”  )
  • ·         Swap the nodes in binary tree.
  • ·         Print Binary tree in pre order/post order/ inorder
  • ·         Stack operations using O(1)
  • ·         Implement Queue Using Linked List
  • ·         Merge Sort implementation.
  • ·         How to find the linked list is circular or not.
  • ·         Find the repeated values in String.