Sunday, 10 September 2023

Java Most asked Coding/Programming Interview Questions

1. Find the first non-repeating character in a string.

package com.javaforsomeone.example;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

class Main {

    public static void main(String[] args) {
	  String name = "this is the java coding test";
	  firstNonRepeated(name);
	}

	public static void firstNonRepeated(String k) {

	Map hMap = new LinkedHashMap();
	for (char data : k.toCharArray()) {

		if (hMap.containsKey(data)) {
			hMap.put(data, hMap.get(data) + 1);
		} else {
			hMap.put(data, 1);
		}
	}
	Set data = hMap.keySet();
	for (Character a : data) {
	  if (hMap.get(a) == 1) {
		  System.out.println("First Non 
		  Repeated Character is " + a);
		  break;
	  }
	}

	}

}

Output: First Non Repeated Character is j

  

2. The sum of largest contiguous subarray.

package com.javaforsomeone.example;

public class Main {

	public static void main(String[] args) {

	  int[] arr = { -2, 1, -3, 4, -1, 2 };

	  System.out.println("The sum of contiguous subarray with the " 
	  + "largest sum is " + testMaxSum(arr));
	}

	private static Integer testMaxSum(int[] arr) {

	  int maxSum = 0;
	  int currentSum = 0;
	  for (Integer k : arr) {
	    currentSum = currentSum + k;
	    if (currentSum > maxSum) {
		    maxSum = currentSum;
	       } else if (currentSum < 0) {
		     currentSum = 0;
           }
		}
		return maxSum;
	}

}

Output: The sum of contiguous subarray with the largest sum is 5

  

3. Write a program to delete the Mid element from the Stack.

package com.javaforsomeone.example;

import java.util.Stack;

public class Main {

	public static void main(String[] args) {
		
		Stack stack=new Stack();
		stack.push('A');
		stack.push('B');
		stack.push('C');
		stack.push('D');
		stack.push('E');
		System.out.println("The Stack after the deletion 
		of Mid Element "+deleteMid(stack));

	}
	
	public static Stack deleteMid(Stack st){
		
		int n=st.size();
		Stack tempStack =new Stack();
		int count=0;
		while(count<n/2) {
			char c =st.peek();
			st.pop();
			tempStack.push(c);
			count++;
		}
		st.pop();
		while(!tempStack.empty())
		{
			st.push(tempStack.peek());
			tempStack.pop();
		}
		return st;
	}

}

Output: The Stack after the deletion of Mid Element [A, B, D, E]
  

No comments:

Post a Comment