Java Coding

How do you remove duplicates from a String?

This question is about to delete or remove duplicate characters from a given String in Java. You have to write an algorithm or code in Java.

have a look at the link Remove duplicates from a String

How to find start and end index of a given element in a sorted array?

This question is regarding to find out the start and end index of the given element in a sorted array. So it means the array contains duplicate elements.

Let’s say a sorted array is given with the elements in it as [1 2 2 3 3 3 3 5 6] and you need to find out the start and end indices of element 3. Therefore the start index is 3 and end index is 6.

Now you can iterate the array and find out the indices but it won’t give you the result in optimized way. So to find out the result in optimized way you need to use Binary Search algorithm and you can find the solution here using Kotlin. The same algorithm you can implement in other language, for example, in Java given below:

public class StartAndEndIndexOfValueInArray {
	public static void main(String[] args) {
		int[] arr = new int[] { 1, 1, 2, 2, 3, 3, 3, 3, 3, 5, 8, 6, 9 };
		StartAndEndIndexOfValueInArray findIdx = new StartAndEndIndexOfValueInArray();
		int totalElements = arr.length;
		int startIndex = findIdx.findStartIndex(arr, 0, totalElements, 3);
		int endIndex = findIdx.findEndIndex(arr, 0, totalElements, 3, totalElements);
		System.out.println("Start Index: " + startIndex + ", End Index: " + endIndex);
	}
		   
	private int findStartIndex(int[] arr, int low, int high, int x) {
		if (high > low) {
			int mid = low + (high - low) / 2;
			if ((mid == 0 || x > arr[mid - 1]) && x == arr[mid]) {
				return mid;
			} else if (x > arr[mid]) {
				return findStartIndex(arr, mid + 1, high, x);
			} else {
				return findStartIndex(arr, low, mid - 1, x);
			}
		}
		return -1;
	}
		   
	private int findEndIndex(int[] arr, int low, int high, int x, int totalElements) {
		if (high > low) {
			int mid = low + (high - low) / 2;
			if ((mid == totalElements - 1 || x < arr[mid + 1]) && x == arr[mid]) {
				return mid;
			} else if (x < arr[mid]) {
				return findEndIndex(arr, low, mid - 1, x, totalElements);
			} else {
				return findEndIndex(arr, mid + 1, high, x, totalElements);
			}
		}
		return -1;
	}
}

Write an algorithm to return an output array of products of all other numbers from a given array.

Let’s say you are given an array of non-zero integers. So you have to return an output array of products of all other numbers except the number itself.

For example, an input array a[]={1, 2, 3, 4}, so the output array will be out[]={24, 12, 8, 6}.

Please find the solution here

Write an algorithm to find out reverse of a given String.

We have different ways to reverse a string in Java as given below:

Using reverse() method in StringBuffer
Using reverse() method in StringBuilder
Using custom reverse method
Using recursion

You can find the details here at  String reverse example in java

Find out minimum moves to equalize array elements.

This is about to find out minimum moves to equalize two array elements at each index.

You can find the solution here at Minimum moves to equal array elements

How would you check if a binary tree is binary search tree?

A binary search tree (BST) is a node based binary tree data structure which satisfies the following properties:

The left sub-tree of a node contains only nodes with keys less than the root node’s key.

The right sub-tree of a node contains only nodes with keys greater than the root node’s key.

Both the left and right sub-trees must also be again binary search trees.

Please find the implementation to check if a binary tree is binary search tree.

Find out minimum moves to segregate even followed by odd elements in an array.

In this solution you have to arrange even numbers first, and then odd numbers and finally count the number of moves required to arrange all elements in the desired order.

You can find the solution here

How to read last n lines from the file?

Here is the solution to read n last lines from a file using Java.

How to segregate positive followed by negative array elements?

Please refer to the example Segregate positive followed by negative elements in Array

Print prime numbers between 1 and 1000.

The checking can be done with two loops: starting from 2 to n (n being integer value), have a function that tests whether given number is prime by checking divisibility (using modulo operator) from 2 to n; if it’s divisible, then it’s not a prime number.

Here is the complete source code:

public class PrintPrime {

	public static void main(String[] args) {
		printPrimeUpto(1000);
	}

	public static void printPrimeUpto(int num) {
		String sep = "";
		int i = 1;
		while (i <= num) {
			if (isPrime(i)) {
				System.out.print(sep);
				System.out.print(i);
				sep = ", ";
			}
			i++;
		}
	}

	public static boolean isPrime(int num) {
		for (int i = 2; i <= num / 2; i++) {
			if (num % i == 0) {
				return false;
			}
		}
		return true;
	}

}

Print prime numbers between 1 to 1000 using Java code

package com.jeejava.prime;

public class PrintPrime {

	public static void main(String[] args) {
		printPrimeUpto(1000);
	}

	public static void printPrimeUpto(int num) {
		String sep = "";
		int i = 1;
		while (i <= num) {
			if (isPrime(i)) {
				System.out.print(sep);
				System.out.print(i);
				sep = ", ";
			}
			i++;
		}
	}

	public static boolean isPrime(int num) {
		for (int i = 2; i <= num / 2; i++) {
			if (num % i == 0) {
				return false;
			}
		}
		return true;
	}

}

Output

1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997

Find out how many times each character is showing up in the given string ?

You are given a string input, let’s say “Hello World!”. Your output should be, how many times each character is showing up in the string. So, in this example, it should write: H: 1 e: 1 l: 3 o: 2 etc.

package com.jeejava.string;

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

public class CharacterCounter {

	public static void main(String[] args) {
		Map<String, Integer> cMap = countChars("Hello World");
		cMap.forEach((k, v) -> System.out.println(k + " => " + v));
	}

	public static Map<String, Integer> countChars(final String str) {
		Map<String, Integer> cMap = new HashMap<>();

		for (int i = 0; i < str.length(); i++) {
			String s = str.substring(i, i + 1);

			if (s == null || " ".equals(s)) {
				continue;
			}

			if (cMap.get(s) != null) {
				cMap.put(s, cMap.get(s) + 1);
			} else {
				cMap.put(s, 1);
			}
		}

		return cMap;
	}

}

Scroll to top