Automation QA Testing Course Content

Showing posts with label JavaCodingChallenge. Show all posts
Showing posts with label JavaCodingChallenge. Show all posts

Get distinct words from a given file in Java

 We will extract distinct words from a given file using Java.

Concepts

  • Set data structure does not allow duplicate elements, so it can be used for filtering out duplicate words.

  • Using regex we can split the given text file into words, Java provides StringTokenizer class that can help splitting each line of file.

  • We need to close any input file so as to avoid file handle leaks inside Java program. try with resource takes care of automatically closing the underlying input stream once block of code is executed.

import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; public class DistinctWords { private static final Logger LOGGER = Logger.getLogger("DistinctWords"); public Set<String> getDistinctWords(String fileName) { Set<String> wordSet = new HashSet<>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) { String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, " ,.;:\""); while (st.hasMoreTokens()) { wordSet.add(st.nextToken().toLowerCase()); } } } catch (IOException e) { LOGGER.log(Level.SEVERE, "IOException occurred", e); } return wordSet; } public static void main(String[] args) { DistinctWords distinctFileWords = new DistinctWords(); Set<String> wordList = distinctFileWords.getDistinctWords("<path-to-file>"); for (String str : wordList) { System.out.println(str); } } }

Create anagram buckets from a given input array of words

 Two strings are called anagrams if they contain same set of characters but in different order. For example,

  • peek and keep are anagrams

  • spar and rasp are anagrams

  • listen and silent are anagrams

For more info:

https://en.wikipedia.org/wiki/Anagram

Here we get an input array of words that contains anagram string, and we need to create buckets for all the anagrams words.

Input:

{"akka", "akak", "baab", "baba", "bbaa"}

Output:

{
    [akka, akak],
    [baab, baba, bbaa]
}

Approach

  1. Create a hashmap that will hold sorted word as the key and list of anagrams as the value. We will use this hashmap to store the results.

  2. For each word in the input array, create a key by sorting the characters and put this word to that list whose key is the sorted word. for example [aakk → akka, akak] If it does not exist then create a new list with the sorted word as key in map.

  3. In the end, traverse the values of hashmap and we get the desired result.


import java.util.*; public class Anagrams { public static void main(String[] args) { String[] input = {"akka", "akak", "baab", "baba", "bbaa"}; Map<String, List<String>> anagramsMap = anagramBuckets(input); System.out.println("anagramsMap = " + anagramsMap); } private static Map<String, List<String>> anagramBuckets(String[] input) { Map<String, List<String>> anagramsMap = new HashMap<>(100); for (String s : input) { char[] word = s.toCharArray(); Arrays.sort(word); String key = String.valueOf(word); if (!anagramsMap.containsKey(key)) { anagramsMap.put(key, new ArrayList<>()); } anagramsMap.get(key).add(s); } return anagramsMap; } }

Reverse position of words in a string using recursion

 In this article, we will write a program to reverse position of words in a given string using recursive approach.

Sample input

I am the best of bests

Output

bests of best the am I

Recursive Approach

  1. We will remove first word from the input string and append it at the end.

  2. Repeat it till all the words are removed and input becomes empty.

public class ReverseWordsInString { public String reverse(String input) { if (input.isEmpty()) { return input; } String[] arr = input.split(" ", 2); String firstWord = arr[0]; String remainingSentence; if (arr.length == 2) remainingSentence = arr[1]; else remainingSentence = ""; return reverse(remainingSentence) + firstWord + " "; } }



1)Base condition in recursion, if the input is empty then we just return (unwind the stack in recursion)
2)We are splitting input string into two parts - first element of array will contain the first word, second element of array will contain the remaining sentence

3)Tail recursion - removes first word and appends it to the last

JUnit testcase

We will write a simple Junit based testcase to assert the correctness of our given program.

JUnit Test
import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

public class ReverseWordsInStringTest {

    @Test
    public void reverse() {
        ReverseWordsInString utils = new ReverseWordsInString();
        assertThat(utils.reverse("I am the best of bests"), equalTo("bests of best the am I"));
    }
}

Find two numbers of which the product is maximum in an array

 We can easily find two number in an array whose product is maximum using the below approach:

  1. Sort the input integer array in descending order

  2. multiply first and second element of the array, the product will be maximum.Find product of max two elements of an integer array

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class ArrayUtils {
    
        long productMinMax(Integer[] array) {
            Arrays.sort(array, Comparator.reverseOrder());
            int maxNumber = array[0];
            int secondMaxNumber = array[1];
            System.out.println("maxNumber = " + maxNumber);
            System.out.println("secondMaxNumber = " + secondMaxNumber);
            return secondMaxNumber * maxNumber;
        }
    
        public static void main(String[] args) {
            long product = new ArrayUtils().productMinMax(new Integer[]{10, 11, 13, 9, 2, 4});
            System.out.println("Product of min and max element = " + product);
        }
    }
    Program output
    maxNumber = 13
    secondMaxNumber = 11
    Product of min and max element = 143

Java Interview Coding Challenge


 Problem #1

Consider the Following Problem:

  Write a short program that prints each number from 1 to 100 on a new line.

            For each multiple of 3, print "Fizz" instead of the number.

           For each multiple of 5, print "Buzz" instead of the number.

           For numbers which are multiple of both 3 and 5, print "FizzBuzz" instead of the number.


Solution:

public static void printFizzBuzz(int n) {

for(int i=1;i<=n;i++) {

if((i%3==0) && (i%5==0)) {

System.out.println("FizzBuzz");

}else if(i%3==0) {

System.out.println("Fizz");

}else if(i%5==0) {

System.out.println("Buzz");

}else {

System.out.println(i);

}

}

}

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

Problem #2

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

      Given nums = [2,7,11,15], target = 9,

                Because nums[0] + nums[1] = 2 + 7 =9,

                return [0,1] 

Solution:

public class GetTwoSum{

protected static int[] getTwoSum(int[] numbers, int target) {

//create a Map

Map<Integer, Integer>visitedNumbers = new HashMap<>();

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

int delta = target - numbers[i];

if(visitedNumbers.containsKey(delta)) {

return new int[] {i, visitedNumbers.get(delta) };

}

visitedNumbers.put(numbers[i], i);

}

return new int[] {-1, -1};

}

public static void main(String[] args) {

printFizzBuzz(100);


int[] numbers = new int[] {2,3,7,4,8};

int target = 6;

int[] result = getTwoSum(numbers, target);

System.out.println(result[0] +" "+result[1]);

}


}

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

Problem # 3

               ReverseString


public class Ch03ReverseString {


public static void main(String[] args) {

String str = "Hello World!";

System.out.println(reverseWithStringBuilder(str));

System.out.println(reverseManually(str));


}


private static String reverseManually(String str) {

// Create object fir StringBuilder

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--) {

sb.append(str.charAt(i));

}

return sb.toString();

}


private static String reverseWithStringBuilder(String str) {

return new StringBuilder(str)

.reverse()

.toString();

}


}

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

Problem #4

        Implement a Stack in java


public class Stack {


private int array[];

private int top;

private int capacity;

Stack(int capacity){

this.array=new int[capacity];

this.capacity=capacity;

this.top=-1;

}

public void push(int item) {

if(isFull()) {

throw new RuntimeException("Stack is full");

}

array[++top]=item;

}

public boolean isFull() {

return top == capacity - 1;

}



/**

* Pop will return top item and remove from the stack and update the stack

* @return

*/

public int pop() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top--];

}

/**

* peek will return the top item and wont remvoe the item from stack

* @return

*/

public int peek() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top];

}



public boolean isEmpty() {

return top==-1;

}

}

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

Problem # 5

      Reverse an Integer

public class ReverseInteger {


public int reverse(int input) {

int reversed=0;

while(input!=0) {

reversed = reversed*10 + input % 10;

input /=10;

if(reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {

return 0;

}

}

return reversed;

}

public static void main(String[] args) {

System.out.println(new ReverseInteger().reverse(123));


}


}

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

Problem #6

     Convert from Integer to Roman numeral

    I -->1

  II -->2

 III -->3

IV -->4

V -->5

VI -->6

X -->10

L -50

C- 100

D -500

M -1000

public class IntegerToRoman {


public static String intToRoman(int num) {

String[] thousands = new String[]{"","M","MM","MMM"};

String[] hundreds = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};

String[] tens = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};

String[] units = {"","I","II","III","IV","V","VI","VII","VIII","IX"};

return thousands[num / 1000] +

hundreds[(num%1000)/100] +

tens[(num % 100) / 10] +

units[num % 10];

}

public static void main(String[] args) {

System.out.println(intToRoman(124));


}

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

Problem # 7

 Convert Roman numeral to Integer

public int romanToInt(String s) {

Map<Character,Integer>map = new HashMap();

map.put('I', 1);

map.put('V', 5);

map.put('X', 10);

map.put('L', 50);

map.put('C', 100);

map.put('D', 500);

map.put('M', 1000);

int result = 0;

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

if(i>0 && map.get(s.charAt(i)) >map.get(s.charAt(i-1))){

result += map.get(s.charAt(i)) - 2 *map.get(s.charAt(i-1));

} else {

result +=map.get(s.charAt(i));

}

}

return result;

}

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

Problem # 8

Longest Palindrome Substring

public class LongestPalindromeSubstring {

 int resultStart;

 int resultLength;

public String longestPalindrome(String s) {

int strLength = s.length();

if(strLength < 2) {

return s;

}

for(int start = 0; start < strLength -1; start++) {

expandRange(s,start,start);

expandRange(s,start,start + 1);

}

return s.substring(resultStart,resultStart + resultLength);

}

private void expandRange(String str, int begin, int end) {

while(begin >= 0 && end < str.length() && str.charAt(begin) == str.charAt(end)) {

begin--;

end++;

}

if(resultLength < end -begin -1) {

resultStart = begin +1;

resultLength = end - begin -1;

}

}

}

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

Problem # 9:

    Detect Capital

    Given a word, you need to judge whether the usage of capitals in it is right or not.

 Right Usage:

  1. All letters in this word are capitals
  2. All letters in this word are not capitals
  3. Only the first letter in this word is capital   
  • Example:
  • All caps : "USA"     
  •     

public class DetectCapital {

/**
* Approach 1 : The "clever" solution
* Count the number of uppercase letters
* if it is zero or length of string, return true
* if it is not 1, return false
* if it is 1 and the first letter is uppercase, return true
* Time Complexity -- O(N)
* can we do better?
* Disadvantage:
* Quit at the first wrong character
*  valid --AAAAA
*  Valid : aaaa
*  valid : Aaaaa
* @param word
* @return 
*/
public static boolean detectCapitalUse(String word) {
int numberOfCapitals = 0;
for(int i = 0; i < word.length(); i++) {
if(Character.isUpperCase(word.charAt(i))) {
numberOfCapitals++;
}
}
if(numberOfCapitals == word.length() || numberOfCapitals == 0) return true;
return numberOfCapitals == 1 && Character.isUpperCase(word.charAt(0));
}
/**
* Approach 2:
*
*/
public static boolean detectCapitalUse2(String word) {
//Case 1 : All Capitals
int n = word.length();
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
for(int i = 2; i< n; i++) {
if(Character.isLowerCase(word.charAt(i))) {
return false;
}
}
}else {
for(int i = 1; i<n;i ++) {
if(Character.isUpperCase(word.charAt(i))) {
return false;
}
}
}
return true;
}
/**
* Approach using LAMBDA 
* Time Complexity - O(N)
* @param args
*/
public boolean detectCapitalUse3(String word) {
if(word.length() <= 1) return true;
Predicate<Character> correctCase = Character::isLowerCase;
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
correctCase = Character::isUpperCase;
}
for(int i = 1; i < word.length(); i++) {
if(!correctCase.test(word.charAt(i))) return false;
}
return true;
}