Friday, April 22, 2022

Programming Interview Questions




First Non Repeating charater in ther String 

package com.example.demo.non_RepeatingChar;


public class FindNonRepeatingChar {
public static void main(String[] args) {

String str = "Particular item P c u";
boolean flag = true;

for(char c : str.toCharArray() ) {
if(str.indexOf(c) == str.lastIndexOf(c)) {
System.out.println("First non repeating character : " + c );
flag = false;
break;
}
}

if(flag) {
System.out.println("Threr is no non repeating character in the string.");
}
}
}

OUTPUT:- 

First non repeating character : l


Reversing a String


package com.example.demo.Reverse_String;
public class StringReverse {
public static void main(String[] args) {

String str = "Hello World How are you ?";
char[] chr = str.toCharArray();

for(int i=chr.length-1; i>=0; i--) {
System.out.print(chr[i]);
}
}
}

OUTPUT:-
? uoy era woH dlroW olleH



 Vowel character in string 


package com.example.demo.FindVowel;

import java.util.HashSet;
import java.util.Set;
public class FindVowel_1 {
public static void findVowelcharacter(String str) {
int count = 0;
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isVowel(c)) {
set.add(c);
count++;
}
}
System.out.println("Total vowel character : "+ count +" --- " +" All vowel character : "+set);
}
public static boolean isVowel(char character) {
if (character == 'a' || character == 'A' || character == 'e' || character == 'E' || character == 'i'
|| character == 'I' || character == 'o' || character == 'O' || character == 'u'
|| character == 'U') {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
findVowelcharacter("Hello ");
}
}
OUTPUT:-

Total vowel character : 2 ---  All vowel character : [e, o]

---------------------------------------------------------------------------------------------------------------

package com.example.demo.FindVowel;

public class FindVowel {
public static boolean finVowelInString(String str) {

return str.toLowerCase().matches(".*[aeiou].*");

}

public static void main(String[] args) {
System.out.println(finVowelInString("Hello"));
System.out.println(finVowelInString("TV"));
}
}

OUTPUT:-

true
false

------------------------------------------------------------------------------------------

With List and ListIterator

package com.example.demo.ReverseString;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class ReverseStringWithList {
public static void main(String[] args) {
String str = "Hello World";
char[] arrayChar = str.toCharArray();
List<Character> listOfCharacter = new ArrayList<Character>();
for (char c : arrayChar) {
listOfCharacter.add(c);
}
Collections.reverse(listOfCharacter);
ListIterator li = listOfCharacter.listIterator();
while (li.hasNext()) {
System.out.print(li.next());
}
// System.out.println(listOfCharacter.toString());
}
}

OUTPUT:--

dlroW olleH


---------------------------------------------------------------------------------------

=================================================================

Arrays


Find Duplicate Elements in Arrays

package com.example.demo.LeetCode;

import java.util.HashSet;
import java.util.Set;
public class FindDupateInArray {
public static void main(String[] args) {

int[] arr = new int[] {2,3,4,5,2,3,4,4,4,2,4};

Set<Integer> set = new HashSet<Integer>();

for(int i=0;i<arr.length;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i]==arr[j]) {
set.add(arr[i]);
}
}
}
System.out.println(set);
}
}


OUTPUT:-

[2, 3, 4]

--------------------------------------------------------------------------------------

Find Duplicate elements in Array for String 


package com.example.demo.LeetCode;

import java.util.HashSet;
import java.util.Set;
public class FindDupateInArray_String {
public static void main(String[] args) {
String[] arrStr = new String[] {"Java","C","Java","Java","C","Python","Python","C++","cobol"};
Set<String> setString = new HashSet<String>();
for(int i=0;i<arrStr.length;i++) {
for(int j=i+1;j<arrStr.length;j++) {
if(arrStr[i]==arrStr[j]) {
setString.add(arrStr[i]);
}
}
}
System.out.println(setString);
}
}

OUTPUT:-
[Java, C, Python]

---------------------------------------------------------------------------------------------------------------


package com.example.demo.LeetCode;
import java.util.HashSet;
import java.util.Set;
public class FindDupateInArray {
public static void main(String[] args) {
int[] arr = new int[] { 2, 3, 4, 5, 2, 3, 4, 4, 4, 2, 4, 90, 90, 55, 55, 5, 89, 78, 56 };
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
set.add(arr[i]);
}
}
}
System.out.println("Duplicate Elements are : "+set);
Set<Integer> setRemoveDuplicate = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0 ; j < arr.length; j++) {
if (arr[i] != arr[j]) {
setRemoveDuplicate.add(arr[i]);
}
}
}
System.out.println("After Removing DuplicateElements : "+setRemoveDuplicate);
}
}

OUTPUT :-

Duplicate Elements are : [2, 3, 4, 5, 55, 90]
After Removing DuplicateElements : [2, 3, 4, 5, 55, 56,89, 90, 78]
--------------------------------------------------------------------------------------------------------------


package com.example.demo.java_8.Duplicate_Array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

public class ArraysDuplicateRemoval {

public static void main(String[] args) {

int[] array = new int[] { 14, 5, 26, 998, 56, 34, 9, 12, 89, 14, 5, 26, 34 };
Set<Integer> set = new HashSet<Integer>();

for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
set.add(array[i]);
}
}
}

System.out.println("Duplicate Elements : "+set);

SortedSet<Integer> setRemoveDuplicateElement = new TreeSet<Integer>();
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] != array[j]) {
setRemoveDuplicateElement.add(array[i]);
}
}
}

System.out.println("List of non-Duplicate elements : "+setRemoveDuplicateElement);

String[] arrayString = new String[] { "Kunal", "Ali", "Tiwari", "Ghulam", "Ravi", "Abdul", "Rahim", "Tabish" ,"Tiwari","Kunal","Ravi" };

SortedSet<String> setRemoveDuplicateElementString = new TreeSet<String>();
for (int i = 0; i < arrayString.length; i++) {
for (int j = 0; j < arrayString.length; j++) {
if (arrayString[i].equals(arrayString[j])) {
setRemoveDuplicateElementString.add(arrayString[i]);
}
}
}

System.out.println("non duplicate list of String : "+ setRemoveDuplicateElementString);
Arrays.sort(arrayString);

//Arrays.sort(array);
System.out.print("Original sorted list : [");
for (String str : arrayString) {
System.out.print(str + ", ");
}
System.out.print("]");
}

}

OUTPUT:-

Duplicate Elements : [34, 5, 26, 14]
List of non-Duplicate elements : [5, 9, 12, 14, 26, 34, 56, 89, 998]
non duplicate list of String : [Abdul, Ali, Ghulam, Kunal, Rahim, Ravi, Tabish, Tiwari]
Original sorted list : [Abdul, Ali, Ghulam, Kunal, Kunal, Rahim, Ravi, Ravi, Tabish, Tiwari, Tiwari, ]


---------------------------------------------------------------------------------------------------------------

Fabonacci series


package com.Fabonacci;

public class FabonacciTest {


public static void main(String[] args) {

int n1=0, n2=1, n3, i , count=10;
System.out.print(n1+" "+n2);

for(i=2; i<count;i++){

n3 = n2+n1;
System.out.print(" "+n3);
n1 = n2;
n2 = n3;
}


}


}

OUTPUT:       0 1 1 2 3 5 8 13 21 34

=================================================================

Find Second Highest number in the Array  


package com.example.demo.java_8.Second_highest_num_Array;
import java.util.SortedSet;
import java.util.TreeSet;
public class SecondHighestNumberInArray {
public static void main(String[] args) {
int[] array = new int[] { 23, 56, 89, 34, 22, 23, 56, 99, 101, 101, 101 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int element : array) {
set.add(element);
}
System.out.println(set);
set.remove(set.last());
System.out.println(set.last());
}
}

  
OUTPUT:-

[22, 23, 34, 56, 89, 99, 101]
99


---------------------------------------------------------------------------------------------------------------------

package com.example.demo.java_8.Second_highest_num_Array;

import java.util.Arrays;
public class SeconLargestNumInArray_2 {
public static void main(String[] args) {
int[] array = new int[] { 24, 68, 8, 52, 22, 47, 9, 75, 3, 24, 22,99 };
int largestNum = 0;
int secondLargestNum = 0;

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

if(array[i]>largestNum) {
secondLargestNum = largestNum;
largestNum = array[i];
}else if(array[i]>secondLargestNum) {
secondLargestNum = array[i];
}
}

System.out.println(Arrays.toString(array));
System.out.println("Second Largest number : "+ secondLargestNum );
}
}

OUTPUT:- 
[24, 68, 8, 52, 22, 47, 9, 75, 3, 24, 22, 99]
Second Largest number : 75


=================================================================

Copy Constructor 

package com.example.demo.copyConstructor;

class Rectangle {
int length;
int breadth;
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public Rectangle(Rectangle obj) {
length = obj.length;
breadth = obj.breadth ;
}
public int area() {
return length * breadth;
}
}
public class CopyConstructorTest {

    public static void main(String[] args) {

Rectangle firstRectangel = new Rectangle(10,20);

Rectangle CopyfirstRectangel = new Rectangle(firstRectangel);

System.out.println("Area of Rectangle : "+firstRectangel.area());

System.out.println("Copy constructor " + CopyfirstRectangel.area());

}
}


OUTPUT:-

Area of Rectangle : 200
Copy constructor 200



Remove duplicate element from Array


package com.DuplicateArray;

public class DuplicationTest {

public static void main(String[] args) {

int arr[] = {12,15,65,12,17,15,65,98,78,78};
int len = arr.length;

for(int k=0; k<len;k++){
System.out.print(arr[k]+" ");
}

for(int i =0; i<len-1;i++){
for(int j=i+1; j<len;j++){

if(arr[i] == arr[j]){
arr[j] = arr[len-1];
len--;
}

}
}
System.out.println();
for(int k=0; k<len;k++){
System.out.print(arr[k]+" ");
}
}


}

OUTPUT:-

12 15 65 12 17 15 65 98 78 78 

12 15 65 78 17 98 


------------------------------------------------------------------------------------------------

Removal of duplicate element from Array String form.

package com.DuplicateArray;

import java.util.Arrays;

public class StringDuplicationRemove {

public static void main(String[] args) {

String names[] = {"Ali","Kunal","Paridhi","Paridhi","Paritosh","Ali","Sakshi","Tushar"};
int len= names.length;
//Arrays.sort(names);

for(int k=0; k<len;k++){
System.out.print(names[k]+" ");
}
for(int i =0; i<len-1; i++){
for(int j=i+1; j<len; j++){
if(names[i] == names[j]){
names[i] = names[len-1];
len--;
}
}
}
System.out.println();
for(int k=0; k<len;k++){
System.out.print(names[k]+" ");
}
System.out.println();
for(int k=0; k<names.length;k++){
System.out.print(names[k] + " ");
}

}


}

OUTPUT:-

Ali Kunal Paridhi Paridhi Paritosh Ali Sakshi Tushar 
Tushar Kunal Sakshi Paridhi Paritosh Ali 
Tushar Kunal Sakshi Paridhi Paritosh Ali Sakshi Tushar

----------------------------------------------------------------------------------------------------------

Arrays.sort() in Java with examples

sort() method is a java.util.Arrays class method.
A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
 
public class SortExample
{
    public static void main(String[] args)
    {
        // Our arr contains 8 elements
        int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
 
        Arrays.sort(arr);
 
        System.out.printf("Modified arr[] : %s",
                          Arrays.toString(arr));
    }
}
Output:
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]
We can also use sort() to sort a subarray of arr[]

// A sample Java program to sort a subarray
// using Arrays.sort().
import java.util.Arrays;
 
public class SortExample
{
    public static void main(String[] args)
    {
        // Our arr contains 8 elements
        int[] arr = {13, 7, 6, 45, 21, 9, 2, 100};
 
        // Sort subarray from index 1 to 4, i.e.,
        // only sort subarray {7, 6, 45, 21} and
        // keep other elements as it is.
        Arrays.sort(arr, 1, 5);
 
        System.out.printf("Modified arr[] : %s",
                          Arrays.toString(arr));
    }
}
Output:
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]
We can also sort in descending order.
// A sample Java program to sort a subarray
// in descending order using Arrays.sort().
import java.util.Arrays;
import java.util.Collections;
 
public class SortExample
{
    public static void main(String[] args)
    {
        // Note that we have Integer here instead of
        // int[] as Collections.reverseOrder doesn't
        // work for primitive types.
        Integer[] arr = {13, 7, 6, 45, 21, 9, 2, 100};
 
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
 
        System.out.printf("Modified arr[] : %s",
                          Arrays.toString(arr));
    }
}
Output:
Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]
We can also sort strings in alphabetical order.
// A sample Java program to sort an array of strings
// in ascending and descending orders using Arrays.sort().
import java.util.Arrays;
import java.util.Collections;
 
public class SortExample
{
    public static void main(String[] args)
    {
        String arr[] = {"practice.geeksforgeeks.org",
                        "quiz.geeksforgeeks.org",
                        "code.geeksforgeeks.org"
                       };
 
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.printf("Modified arr[] : \n%s\n\n",
                          Arrays.toString(arr));
 
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
 
        System.out.printf("Modified arr[] : \n%s\n\n",
                          Arrays.toString(arr));
    }
}
Output:
Modified arr[] : 


Modified arr[] : 
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]


https://javahungry.blogspot.com/2013/12/first-non-repeated-character-in-string-java-program-code-example.html?m=1

Find The First Non Repeated Character In A String : Technical Interview Question


If the word "stress" is input  then it should print  't'   as output .

If the word "teeter" is input  then it should print  'r'   as output .

Now , we should understand the pseudo algorithm or logic to achieve this task , code is given in the end of this post .
import java.util.HashMap;
import java.util.Scanner;


public class FirstNonRepeated {
    
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        
        System.out.println(" Please enter the input string :" );
        Scanner in = new Scanner (System.in);
        String s=in.nextLine();
        char c=firstNonRepeatedCharacter(s);
        System.out.println("The first non repeated character is :  " + c);
    }
    
    public static Character firstNonRepeatedCharacter(String str)
    {
        HashMap<Character,Integer>  characterhashtable= 
                     new HashMap<Character ,Integer>();
        int i,length ;
        Character c ;
        length= str.length();  // Scan string and build hash table
        for (i=0;i < length;i++)
        {
            c=str.charAt(i);
            if(characterhashtable.containsKey(c))
            {
                // increment count corresponding to c
                characterhashtable.put(  c ,  characterhashtable.get(c) +1 );
            }
            else
            {
                characterhashtable.put( c , 1 ) ;
            }
        }
        // Search characterhashtable in in order of string str
        
        for (i =0 ; i < length ; i++ )
        {
            c= str.charAt(i);
            if( characterhashtable.get(c)  == 1 )
            return c;
        }
        return null ;
    }
} 

Count Number

Of Words In The String With Example :

Java Program Code

public class StringDemo
{
    static int i,c=0,res;
    static int wordcount(String s)
    {
        char ch[]= new char[s.length()];      //in string especially we have to mention the () after length
        for(i=0;i<s.length();i++)
        {
            ch[i]= s.charAt(i);
            if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
            c++;
        }
        return c;
    }
    
    public static void main (String args[])
    {
        res=StringDemo.wordcount("   manchester united is also known as red devil ");
        //string is always passed in double quotes
        
        System.out.println("The number of words in the String are :  "+res);
    }
}


2.
 public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\\s+"); return words.length; }

Read more: 
3.
public static int countWordsUsingStringTokenizer(String sentence) {
 if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); }


4.
public static int count(String word) { if (word == null || word.isEmpty()) 
{ return 0; } 
int wordCount = 0; 
boolean isWord = false; 
int endOfLine = word.length() - 1;
 char[] characters = word.toCharArray(); 
for (int i = 0; i < characters.length; i++) 
{ // if the char is a letter, word = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; }