Even or Odd String Interview Question – Hacker Rank

It is asked in the coding challenge taken through Hacker Rank.

Goal: To determine if it is a even or odd string.
Input: Number and Array of String containing lower case
Output:
For each string compute:
[ Char[0]^Number  X  Char[1]^Number   X   …… (All character of String[0])  +

Char[0]^Number   X Char[1]^Number    X   …… (All character of String[1])  +

…………… ] is Even Number or Odd Number ?

Here Char[i] is the ASCII value of character.

For example:
For input: abc bd    and 2

=  (97^2  X   98^2   X    99^2)  + (98^2   X   100^2)

=  ( 9409 X 9604 X 9801 )  + ( 9604 X 10000)

=  885657916836 + 96040000

=  885753956836

So it should return Even.

The catch here is not to compute complex mathematical formulas. There are very basic mathematical checks that needs to be followed to compute if this whole sum is even or odd.
1. Even^AnyNumber = Even & Odd^AnyNumber = Odd
So you do not need to compute the powers.

2. Even X Any Number = Even
Odd X Odd = Odd
So you just need to identify whether there is any even number present in the multiplication.

3. For sum: if Odd numbers occur odd times, final sum will be Odd.
So you need to compute the odd count.

Below is the project structure and source code for the same:

ProjectStructure

Code is as below:

public class OddStrings {

	public static void main(String args[]){
		
		String data[] = {"aceace","ceceaa","abdbdbdbakjkljhkjh"};
		System.out.println(checkComputation(data));
		
		String data2[] = {"azbde","abcher","acegk"};
		System.out.println(checkComputation(data2));
				
	}
	
	public static  boolean checkComputation(String data[] ){
		
		boolean isStringEvenArray[] = new boolean[data.length] ;
		int tempVal;
		boolean isEvenPresent = false;
		
		for(int i=0; i<data.length;i++){
			isEvenPresent= false;
			
			for(int j=0; j<data[i].length();j++ ){
				tempVal = (int) data[i].charAt(j);
				if(tempVal%2==0){
					isEvenPresent = true;
				}
			}			
			isStringEvenArray[i] = isEvenPresent;			
		}
		
		int oddCount=0;		
		for(int i=0; i<data.length; i++){			
			if(!isStringEvenArray[i])
				oddCount++;			
		}
		
		if(oddCount%2!=0)return false;
		else return true;
		
	}
	
}

The output of the above code:

Input:
"aceace","ceceaa","abdbdbdbakjkljhkjh"

Output:
true

Input:
"azbde","abcher","acegk"

Output:
false

You can have above code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git

 


Leave a Reply

Your email address will not be published. Required fields are marked *