0% found this document useful (0 votes)
3 views

Interview Programs for 0 to 5 years experience

The document contains multiple Java programs demonstrating various algorithms and data structures, including a custom HashMap implementation, palindrome detection, string comparison, sorting HashMap keys, and more. Each program includes a main method that executes specific functionality, such as displaying outputs or manipulating data. The document serves as a collection of coding examples for educational purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Interview Programs for 0 to 5 years experience

The document contains multiple Java programs demonstrating various algorithms and data structures, including a custom HashMap implementation, palindrome detection, string comparison, sorting HashMap keys, and more. Each program includes a main method that executes specific functionality, such as displaying outputs or manipulating data. The document serves as a collection of coding examples for educational purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Custom HashMap

package com.binarytree;

class ListNode {
private Integer value;
private Integer key;
private ListNode next;

public ListNode(Integer key, Integer value) {


this.key = key;
this.value = value;
}

public Integer getValue() {


return value;
}

public void setValue(Integer value) {


this.value = value;
}

public Integer getKey() {


return key;
}

public void setKey(Integer key) {


this.key = key;
}

public ListNode getNext() {


return next;
}

public void setNext(ListNode next) {


this.next = next;
}

public class CustomHashTable {


ListNode[] hashTable;
int table_size = 5;
int size = 0;

public CustomHashTable(int size) {


hashTable = new ListNode[size];
table_size = size;
this.size = 0;
for (int i = 0; i < table_size; i++) {
hashTable[i] = null;
}
}

public void put(Integer key, Integer value) {


int hash = (myHash(key) % table_size);
if (hashTable[hash] == null) {
hashTable[hash] = new ListNode(key, value);
} else {
ListNode entry = hashTable[hash];
while (entry.getNext() != null && !entry.getKey().equals(key)) {
entry = entry.getNext();
}

if (entry.getKey().equals(key)) {
entry.setValue(key);
} else {
entry.setNext(new ListNode(key, value));
}
}
size++;
}

private int myHash(Integer key) {


int hashvalue = key.hashCode();
hashvalue %= table_size;
if (hashvalue < 0) {
hashvalue += table_size;
}
return hashvalue;
}

public int get(Integer key) {


int hash = (myHash(key) % table_size);
if (hashTable[hash] == null) {
return 0;
} else {
ListNode entry = hashTable[hash];
while (entry != null && !entry.getKey().equals(key)) {
entry = entry.getNext();
}
if (entry == null) {
return -1;
} else {
return entry.getValue();
}
}
}

public void remove(int key) {


int hash = (myHash(key) % table_size);
if (hashTable[hash] == null) {
return;
} else {
ListNode entry = hashTable[hash];
ListNode prev = null;
while (entry.getNext() != null && !entry.getKey().equals(key)) {
prev = entry;
entry = entry.getNext();
}

if (entry.getKey().equals(key)) {
if (prev == null) {
hashTable[hash] = entry.getNext();
} else {
prev.setNext(entry.getNext());
}
}
}
size--;
}

public void display() {


for (int i = 0; i < table_size; i++) {
ListNode entry = hashTable[i];
while (entry != null) {
System.out.println("Key: " + entry.getKey() + " Value: "
+ entry.getValue());
entry = entry.getNext();
}
}
}

public static void main(String[] args) {


CustomHashTable hashtable = new CustomHashTable(5);

hashtable.put(4, 1);
hashtable.put(44, 3);
hashtable.put(444, 5);
hashtable.display();
int value = hashtable.get(444);
System.out.println(value);

hashtable.remove(4);
hashtable.display();
}

O/P:
Key: 4 Value: 1
Key: 44 Value: 3
Key: 444 Value: 5
5
Key: 44 Value: 3
Key: 444 Value: 5

Longest Palindrome
package com.binarytree;

import java.util.ArrayList;
import java.util.List;

public class LongestPalindrom {


public static void main(String[] args) {
String str = "abcdedefgh";
for(int i =str.length() ; i>1; i--){
List<String> allString = findAllSubstrings(str, i);
for(String item: allString){
StringBuffer buff = new StringBuffer(item);
StringBuffer rev = buff.reverse();
if(item.equals(rev.toString())){
System.out.println("Biggest Palindrome:" + buff);
break;
}
}
}
}
private static List<String> findAllSubstrings(String str, int length){
List<String> allStrings = new ArrayList<>();
int startIndex =0;
int endIndex = length;
while(endIndex <= str.length()){
allStrings.add(str.substring(startIndex, endIndex));
startIndex++;
endIndex++;
}
return allStrings;
}
}
O/P:
Biggest Palindrome:ded

Compare two String’s


package com.examp;
import java.util.Arrays;
public class SameCharacters {
public static void main(String[] args) {
SameCharacters sc = new SameCharacters();
String str = "naresh";
String str2 = "anrsheasffsd";
boolean flag = sc.checkCharacters(str, str2);
if (flag) {
System.out.println("same");
} else {
System.out.println("not same");
}
StringBuffer sb = new StringBuffer(str);
for (int i = 0; i < str.length(); i++) {
int index = sb.indexOf(str2.charAt(i) + "");
if (index > -1) {
sb.deleteCharAt(index);
}
}
if (sb.toString().equalsIgnoreCase("")) {
System.out.println("same");
} else {
System.out.println("not same");
}
}
// Using compare Sorted String's using Arrays.Sort
private boolean checkCharacters(String str, String str1) {
// boolean flag = false;
char[] ch = str.toCharArray();
char[] ch1 = str1.toCharArray();
Arrays.sort(ch);
Arrays.sort(ch1);
if (Arrays.equals(ch, ch1)) {
return true;
}
return false;
}
}
O/P:
not same
same
4. Sort key’s in HashMap
package com.examp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class HashMapSort {


public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("abc", "dbc");
map.put("xyz", "aaa");
map.put("naresh", "babu");
LinkedHashMap<String, String> linkedMap = getSortedMap(map);
System.out.println(linkedMap);
TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.putAll(map);
System.out.println(treeMap);
}
private static LinkedHashMap<String, String> getSortedMap(
Map<String, String> map) {
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(
map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<String, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, String> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return (LinkedHashMap<String, String>) sortedMap;
}

}
O/P:

Swap Two String using XOR


package com.test;

public class SwapStringUsingXor {


public static void main(String[] args) {
String str = "naresh";
char [] ch = str.toCharArray();
int start = 0;
int end = str.length()-1;
while(start<end){
ch[start] = (char) (ch[start]^ch[end]);
ch[end] = (char) (ch[end]^ch[start]);
ch[start] = (char) (ch[start]^ch[end]);
start++;
end--;
}
System.out.println(ch);
}
}
O/P
Hseran

Print Matrix in Spiral


package com.test;

public class SpiralMatrix {


public static void main(String[] args) {
int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int m = 3, n = 4;
int row = 0, col = 0, i;
while (row < m && col < n) {
for (i = col; i < n; i++) {
System.out.print(mat[row][i] + " ");
}
row++;
for (i = row; i < m; i++) {
System.out.print(mat[i][n - 1] + " ");
}
n--;
if (row < m) {
for (i = n - 1; i >= col; i--) {
System.out.print(mat[m - 1][i] + " ");
}
m--;
}
if (col < n) {
for (i = m - 1; i >= row; i--) {
System.out.print(mat[i][col] + " ");
}
col++;
}
System.out.print(" ");
}
}
}
O/P:
1 2 3 4 8 12 11 10 9 5 6 7

Write Program suffix + and prefix +


package com.test;

public class CheckPrefixAndSufix {


public static void main(String[] args) {
String str = "+t++b++c+e++d+e+";
char[] c = str.toCharArray();
if(Character.isAlphabetic(c[0])){
System.out.println("Not match");
} else {
for(int i = 1;i<str.length();i++){
if(Character.isAlphabetic(c[i])){
if(i==str.length()-1|| c[i-1]!='+'||c[i+1]!='+') {
System.out.println("Not Match");
return;
}

}
}
}
}
}
O/P:

Match Brackets in a String

package com.test;

import java.util.Stack;

public class MatchBracket {


public static void main(String[] args) {
String str = "{a(b[c]d)e";
char[] ch = str.toCharArray();
Stack<Character> stack = new Stack<>();

for (int i = 0; i < ch.length; i++) {


if (ch[i] == '(' || ch[i] == '{' || ch[i] == '[') {
stack.push(ch[i]);
} else if (ch[i] == ')') {
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else {
System.out.println("not matching");
return;
}
} else if (ch[i] == '}') {
if (!stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
System.out.println("not matching");
return;
}
} else if (ch[i] == ']') {
if (!stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else {
System.out.println("not matching");
return;
}
}
}
if (stack.isEmpty()) {
System.out.println("matched");
} else {
System.out.println("Not Matched");
}
}
}

O/P:
Not Matched
Print Values in Zig Zag manner.
package com.test;

public class PrintNumberInZigZag {


public static void main(String[] args) {
int[] array = { 4, 3, 7, 8, 6, 2, 1 };
for (int i = 0; i < array.length; i += 2) {
if (i > 0 && array[i - 1] > array[i]) {
swap(i, i - 1, array);
}
if (i < array.length - 1 && array[i] < array[i + 1]) {
swap(i, i + 1, array);
}
}
for (int i : array) {
System.out.print(i);
}
}
private static void swap(int i, int j, int[] array) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}

O/P:

4386712

***************************************************************************

Print Stars

package com.test;

public class StarDisplay {


public static void main(String[] args) {
//int n = 5;
for(int i = 5; i>=1;i--){
for(int j = 1;j<6;j++){
if(i<=j){
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}

for (int i = 0; i < 5; i++) {


for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}

for(int i = 0;i<5;i++){
for(int j = 0;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
O/P:

*
**
***
****
*****
*
**
***
****
*****
*
**
***
****

Reverse words in String

package com.test;

import java.util.Scanner;

public class ReverseWord {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Statement");
String str =sc.nextLine();// "Hi Naresh";
String temp = "", reverse = "";
for(int i = 0; i<str.length();i++){
temp += str.charAt(i);
if(str.charAt(i) == ' ' || str.length()==i+1){
for(int j=temp.trim().length()-1;j>=0;j--){
reverse += temp.charAt(j);
if(j==0 && (i+1!=str.length())){
reverse += " ";
}
}
temp = "";
}
}
System.out.println(reverse);

String name = "Naresh babu abc";

String[] ch = name.split(" ");


StringBuffer sb ;
StringBuffer temp = new StringBuffer();
for(int i = 0;i<ch.length; i++){
sb = new StringBuffer();
sb.append(ch[i]);
temp .append(sb.reverse().append(" ").toString());
// sb.
}
System.out.println(temp);
//System.out.println("1.1"/"0");
}

}
O/P: hseraN ubab cba

Custom ArrayList Example

package com.binarytree;

public class ArrayListExam {


//ArrayList
Object[] arrayList;
int size = -1;
int totalCap = 0;
ArrayListExam(){
arrayList = new Object[10];
totalCap = 10;
}
ArrayListExam(int capacity){
arrayList = new Object[capacity];
totalCap = capacity;
}

public void add(Object obj){


if(size+1==totalCap){
resize();
}
arrayList[++size] = obj;
}
private void resize() {
Object[] newArray = new Object[totalCap+10];
System.arraycopy(arrayList, 0, newArray, 0, arrayList.length);
arrayList = newArray;
/*arrayList = Arrays.copyOf(arrayList, totalCap+10);*/
}

private Object get(int index){


if(index<size){
return arrayList[index];
}
throw new ArrayIndexOutOfBoundsException("index not found");
}

private int size(){


return size;
}

private Object remove(int index){


if(index>size){
throw new ArrayIndexOutOfBoundsException("Index is not found");
}
Object obj = arrayList[index];
int temp = index;
while(temp<size){
arrayList[temp] = arrayList[temp+1];
arrayList[temp+1] = null;
temp++;
}
size--;
return obj;
}

public static void main(String[] args) {


ArrayListExam array = new ArrayListExam();
array.add(10);
array.add(20);
array.add(30);
array.add(40);
array.add(50);
array.add(10);
array.add(20);
array.add(30);
array.add(40);
array.add(50);
array.add(10);
array.add(20);
array.add(30);
array.add(40);
array.add(50);
System.out.println(array.get(3));
System.out.println(array.remove(3));
for(Object obj : array.arrayList){
System.out.println( obj);
}
Object[] list = array.arrayList;

}
O/P:

Print 3rd and 5th char in String and 5th char should be Upper character

package com.test;

public class NextGenExample {


public static void main(String[] args) {
String str = "NareshbabuNuthanapati";
StringBuilder sb = new StringBuilder();
char[] ch = str.toCharArray();
int index = 1;
for(int i=0;i<str.length();i++){
if(index==3){
sb.append(ch[i]);
} else if(index==5){
sb.append(String.valueOf(ch[i]).toUpperCase());
index=0;
}
index++;
}
System.out.println(sb.toString());
}

}
O/P: rSaUtApT

Print sum of array with matching 61

package com.test;

public class CountArrayElements {


public static void main(String[] args) {
int[] a = {12, 5, 31, 9, 21, 8};
int[] s = null;
int total=0;
int k=0;
for(int i = 0;i<a.length;i++){
total = 0;
k=0;
for(int j=i;j<a.length;j++){
total = total+a[j];
k++;
if(total==61){
s = new int[k];
System.arraycopy(a, i, s, 0, s.length);
System.out.println(s);
for(int m=0;m<s.length;m++)
System.out.println(s[m]);
return;
}
}
}
}

}
O/P: 31 9 21

Write Program count repeated characters

package com.test;

public class CountSequenceCh {


public static void main(String[] args) {
String str = "abbbbcccccddddddffffff";
char[] ch = str.toCharArray();
int count = 1;
int i = 0;
while (i < str.length()) {
char c = ch[i];
count = 0;
do {
i++;
count++;
} while (i < ch.length && ch[i] == c);
System.out.println(c + " " + count);
}
}
}

O/P: a=1 b=4 c=5 d=6 f=6


Fibonacci series
package com.test;

import java.util.Scanner;

public class FibbonicExample {


public static void main(String[] args) {
int fib1 = 0, fib2 = 1, fib3 = 0;

Scanner sc = new Scanner(System.in);


System.out.println("Enter value");
Integer n = sc.nextInt();
while (n >= 0) {
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
System.out.println(fib3);
n--;
}
}
}

O/P: Enter value 5


1 2 3 5 8 13

Factorial of give number

package com.test;

public class FactorialExample {


public static void main(String[] args) {
int n = 5, i = 1;
while (n != 0) {
i = i * n;
n--;
}
System.out.println(i);
}
}
O/P: 120

Reverse Number

package com.test;

public class ReverseNum {


public static void main(String[] args) {
int num = 56789;
int rev = 0, sum = 0;
while (num > 0) {
rev = num % 10;
sum = sum * 10 + rev;
num = num / 10;
}
System.out.println(sum);
}
}

1. Connect Same order in tree.


package com.datastru;
class Node{
String data;
Node left, right, nextRight;
Node(String data){
this.data = data;
left = right = nextRight = null;
}
}
public class SameOrder {
public static void main(String[] args) {
Node root = new Node("A");
Node rootl = new Node("B");
Node rootr = new Node("C");
Node rootll = new Node("D");
Node rootlr = new Node("E");
Node rootrl = new Node("F");
Node rootrr = new Node("G");

root.left = rootl;
root.right = rootr;
root.left.left = rootll;
root.left.right = rootlr;
root.right.left = rootrl;
root.right.right = rootrr;

connectSameNode(root);

String r = root.nextRight!=null?root.nextRight.data:"null";
String r2 = root.left.nextRight!=null?root.left.nextRight.data:"null";
String r3 = root.right.nextRight!=null?root.right.nextRight.data:"null";
String r4 = root.left.left.nextRight!=null?root.left.left.nextRight.data:"null";
String r5 = root.left.right.nextRight!=null?root.left.right.nextRight.data:"null";
String r6 = root.right.left.nextRight!=null?root.right.left.nextRight.data:"null";
String r7 = root.right.right.nextRight!=null?root.right.right.nextRight.data:"null";
System.out.println("A->"+r);
System.out.println("B->"+r2);
System.out.println("C->"+r3);
System.out.println("D->"+r4);
System.out.println("E->"+r5);
System.out.println("F->"+r6);
System.out.println("G->"+r7);

private static void connectSameNode(Node root) {


if(root==null){
return;
}
root.nextRight = null;
while(root!=null){
Node temp = root;
while(temp!=null){
if(temp.left!=null){
if(temp.right!=null){
temp.left.nextRight = temp.right;
}else {
temp.left.nextRight = getNextRight(temp);
}
}
if(temp.right!=null){
temp.right.nextRight = getNextRight(temp);
}
temp = temp.nextRight;
}
if(root.left!=null){
root = root.left;
} else if(root.right!=null){
root = root.right;
} else {
root = getNextRight(root);
}
}
}
private static Node getNextRight(Node root) {
Node temp = root.nextRight;
while(temp!=null){
if(temp.left!=null){
return temp.left;
}
if(temp.right!=null){
return temp.right;
}
temp = temp.nextRight;
}
return null;
}
}
o/p.

2. Find Missing value in sequence.


public class FindMissingValue {
public static void main(String[] args) {
int[] arr = { 0, 1, 9, 3, 4, 4, 5, 7, 8, 2 };
int found = 0;
for (int i = 1; i <= arr.length; i++) {
found = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == i) {
found = 1;
break;
}
}
if (found == 0){
// turn i;
System.out.println(i);
break;
}
}
}
}

3. Number Format

public class PhoneParser {

private static final String SEPARATOR = "-";

// 00-44 48 5555 8361 -> 004-448-555-583-61 (14 sign)


// 0 - 22 1985--324 -> 022-198-53-24 (10 sign)
// 555372654 -> 555-372-654 (9 sign)

public static void main(String[] args) {


String case1 = "00-44 48 5555 8361";
String case2 = "0 - 22 1985--324";
String case3 = "555372654";
System.out.println("case1: " + parse(case1)); //case1: 004-448-555-583-61
System.out.println("case2: " + parse(case2)); //case2: 022-198-53-24
System.out.println("case3: " + parse(case3)); //case3: 555-372-654
}

public static String parse(String input) {


input = input.replaceAll(" ", "").replaceAll("-", "");
int inputLength = input.length();
if (inputLength <= 3) {
return input;
} else {
int mod = inputLength % 3;
if (mod == 0) {
return split3(input);
} else if (mod == 1) {
int baseEnd = inputLength - 4;
String base = split3(input.substring(0, baseEnd));
String suffix = split2(input.substring(baseEnd, inputLength));
return base + "-" + suffix;
} else {
int baseEnd = inputLength - 2;
String base = split3(input.substring(0, baseEnd));
String suffix = input.substring(baseEnd, inputLength);
return base + "-" + suffix;
}
}
}

private static String split2(String input) {


return splitTemplate(input, 2);
}

private static String split3(String input) {


return splitTemplate(input, 3);
}

private static String splitTemplate(String input, int splitSize) {


String result = "";
int length = input.length();
for (int i = 0; i < length; i += splitSize) {
String sub = input.substring(i, i + splitSize);
result = result.concat(sub);
if (i != length - splitSize) {
result = result.concat(SEPARATOR);
}
}
return result;
}

You might also like